Search Results

Search found 499 results on 20 pages for 'bird jaguar iv'.

Page 3/20 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Optimizing AES modes on Solaris for Intel Westmere

    - by danx
    Optimizing AES modes on Solaris for Intel Westmere Review AES is a strong method of symmetric (secret-key) encryption. It is a U.S. FIPS-approved cryptographic algorithm (FIPS 197) that operates on 16-byte blocks. AES has been available since 2001 and is widely used. However, AES by itself has a weakness. AES encryption isn't usually used by itself because identical blocks of plaintext are always encrypted into identical blocks of ciphertext. This encryption can be easily attacked with "dictionaries" of common blocks of text and allows one to more-easily discern the content of the unknown cryptotext. This mode of encryption is called "Electronic Code Book" (ECB), because one in theory can keep a "code book" of all known cryptotext and plaintext results to cipher and decipher AES. In practice, a complete "code book" is not practical, even in electronic form, but large dictionaries of common plaintext blocks is still possible. Here's a diagram of encrypting input data using AES ECB mode: Block 1 Block 2 PlainTextInput PlainTextInput | | | | \/ \/ AESKey-->(AES Encryption) AESKey-->(AES Encryption) | | | | \/ \/ CipherTextOutput CipherTextOutput Block 1 Block 2 What's the solution to the same cleartext input producing the same ciphertext output? The solution is to further process the encrypted or decrypted text in such a way that the same text produces different output. This usually involves an Initialization Vector (IV) and XORing the decrypted or encrypted text. As an example, I'll illustrate CBC mode encryption: Block 1 Block 2 PlainTextInput PlainTextInput | | | | \/ \/ IV >----->(XOR) +------------->(XOR) +---> . . . . | | | | | | | | \/ | \/ | AESKey-->(AES Encryption) | AESKey-->(AES Encryption) | | | | | | | | | \/ | \/ | CipherTextOutput ------+ CipherTextOutput -------+ Block 1 Block 2 The steps for CBC encryption are: Start with a 16-byte Initialization Vector (IV), choosen randomly. XOR the IV with the first block of input plaintext Encrypt the result with AES using a user-provided key. The result is the first 16-bytes of output cryptotext. Use the cryptotext (instead of the IV) of the previous block to XOR with the next input block of plaintext Another mode besides CBC is Counter Mode (CTR). As with CBC mode, it also starts with a 16-byte IV. However, for subsequent blocks, the IV is just incremented by one. Also, the IV ix XORed with the AES encryption result (not the plain text input). Here's an illustration: Block 1 Block 2 PlainTextInput PlainTextInput | | | | \/ \/ AESKey-->(AES Encryption) AESKey-->(AES Encryption) | | | | \/ \/ IV >----->(XOR) IV + 1 >---->(XOR) IV + 2 ---> . . . . | | | | \/ \/ CipherTextOutput CipherTextOutput Block 1 Block 2 Optimization Which of these modes can be parallelized? ECB encryption/decryption can be parallelized because it does more than plain AES encryption and decryption, as mentioned above. CBC encryption can't be parallelized because it depends on the output of the previous block. However, CBC decryption can be parallelized because all the encrypted blocks are known at the beginning. CTR encryption and decryption can be parallelized because the input to each block is known--it's just the IV incremented by one for each subsequent block. So, in summary, for ECB, CBC, and CTR modes, encryption and decryption can be parallelized with the exception of CBC encryption. How do we parallelize encryption? By interleaving. Usually when reading and writing data there are pipeline "stalls" (idle processor cycles) that result from waiting for memory to be loaded or stored to or from CPU registers. Since the software is written to encrypt/decrypt the next data block where pipeline stalls usually occurs, we can avoid stalls and crypt with fewer cycles. This software processes 4 blocks at a time, which ensures virtually no waiting ("stalling") for reading or writing data in memory. Other Optimizations Besides interleaving, other optimizations performed are Loading the entire key schedule into the 128-bit %xmm registers. This is done once for per 4-block of data (since 4 blocks of data is processed, when present). The following is loaded: the entire "key schedule" (user input key preprocessed for encryption and decryption). This takes 11, 13, or 15 registers, for AES-128, AES-192, and AES-256, respectively The input data is loaded into another %xmm register The same register contains the output result after encrypting/decrypting Using SSSE 4 instructions (AESNI). Besides the aesenc, aesenclast, aesdec, aesdeclast, aeskeygenassist, and aesimc AESNI instructions, Intel has several other instructions that operate on the 128-bit %xmm registers. Some common instructions for encryption are: pxor exclusive or (very useful), movdqu load/store a %xmm register from/to memory, pshufb shuffle bytes for byte swapping, pclmulqdq carry-less multiply for GCM mode Combining AES encryption/decryption with CBC or CTR modes processing. Instead of loading input data twice (once for AES encryption/decryption, and again for modes (CTR or CBC, for example) processing, the input data is loaded once as both AES and modes operations occur at in the same function Performance Everyone likes pretty color charts, so here they are. I ran these on Solaris 11 running on a Piketon Platform system with a 4-core Intel Clarkdale processor @3.20GHz. Clarkdale which is part of the Westmere processor architecture family. The "before" case is Solaris 11, unmodified. Keep in mind that the "before" case already has been optimized with hand-coded Intel AESNI assembly. The "after" case has combined AES-NI and mode instructions, interleaved 4 blocks at-a-time. « For the first table, lower is better (milliseconds). The first table shows the performance improvement using the Solaris encrypt(1) and decrypt(1) CLI commands. I encrypted and decrypted a 1/2 GByte file on /tmp (swap tmpfs). Encryption improved by about 40% and decryption improved by about 80%. AES-128 is slighty faster than AES-256, as expected. The second table shows more detail timings for CBC, CTR, and ECB modes for the 3 AES key sizes and different data lengths. » The results shown are the percentage improvement as shown by an internal PKCS#11 microbenchmark. And keep in mind the previous baseline code already had optimized AESNI assembly! The keysize (AES-128, 192, or 256) makes little difference in relative percentage improvement (although, of course, AES-128 is faster than AES-256). Larger data sizes show better improvement than 128-byte data. Availability This software is in Solaris 11 FCS. It is available in the 64-bit libcrypto library and the "aes" Solaris kernel module. You must be running hardware that supports AESNI (for example, Intel Westmere and Sandy Bridge, microprocessor architectures). The easiest way to determine if AES-NI is available is with the isainfo(1) command. For example, $ isainfo -v 64-bit amd64 applications pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu 32-bit i386 applications pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu No special configuration or setup is needed to take advantage of this software. Solaris libraries and kernel automatically determine if it's running on AESNI-capable machines and execute the correctly-tuned software for the current microprocessor. Summary Maximum throughput of AES cipher modes can be achieved by combining AES encryption with modes processing, interleaving encryption of 4 blocks at a time, and using Intel's wide 128-bit %xmm registers and instructions. References "Block cipher modes of operation", Wikipedia Good overview of AES modes (ECB, CBC, CTR, etc.) "Advanced Encryption Standard", Wikipedia "Current Modes" describes NIST-approved block cipher modes (ECB,CBC, CFB, OFB, CCM, GCM)

    Read the article

  • Why don't languages include implication as a logical operator?

    - by Maciej Piechotka
    It might be a strange question, but why there is no implication as a logical operator in many languages (Java, C, C++, Python Haskell - although as last one have user defined operators its trivial to add it)? I find logical implication much clearer to write (particularly in asserts or assert-like expressions) then negation with or: encrypt(buf, key, mode, iv = null) { assert (mode != ECB --> iv != null); assert (mode == ECB || iv != null); assert (implies(mode != ECB, iv != null)); // User-defined function }

    Read the article

  • Rijndael managed: plaintext length detction

    - by sheepsimulator
    I am spending some time learning how to use the RijndaelManaged library in .NET, and developed the following function to test encrypting text with slight modifications from the MSDN library: Function encryptBytesToBytes_AES(ByVal plainText As Byte(), ByVal Key() As Byte, ByVal IV() As Byte) As Byte() ' Check arguments. If plainText Is Nothing OrElse plainText.Length <= 0 Then Throw New ArgumentNullException("plainText") End If If Key Is Nothing OrElse Key.Length <= 0 Then Throw New ArgumentNullException("Key") End If If IV Is Nothing OrElse IV.Length <= 0 Then Throw New ArgumentNullException("IV") End If ' Declare the RijndaelManaged object ' used to encrypt the data. Dim aesAlg As RijndaelManaged = Nothing ' Declare the stream used to encrypt to an in memory ' array of bytes. Dim msEncrypt As MemoryStream = Nothing Try ' Create a RijndaelManaged object ' with the specified key and IV. aesAlg = New RijndaelManaged() aesAlg.BlockSize = 128 aesAlg.KeySize = 128 aesAlg.Mode = CipherMode.ECB aesAlg.Padding = PaddingMode.None aesAlg.Key = Key aesAlg.IV = IV ' Create a decrytor to perform the stream transform. Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV) ' Create the streams used for encryption. msEncrypt = New MemoryStream() Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) Using swEncrypt As New StreamWriter(csEncrypt) 'Write all data to the stream. swEncrypt.Write(plainText) End Using End Using Finally ' Clear the RijndaelManaged object. If Not (aesAlg Is Nothing) Then aesAlg.Clear() End If End Try ' Return the encrypted bytes from the memory stream. Return msEncrypt.ToArray() End Function Here's the actual code I am calling encryptBytesToBytes_AES() with: Private Sub btnEncrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncrypt.Click Dim bZeroKey As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} PrintBytesToRTF(encryptBytesToBytes_AES(bZeroKey, bZeroKey, bZeroKey)) End Sub However, I get an exception thrown on swEncrypt.Write(plainText) stating that the 'Length of the data to encrypt is invalid.' However, I know that the size of my key, iv, and plaintext are 16 bytes == 128 bits == aesAlg.BlockSize. Why is it throwing this exception? Is it because the StreamWriter is trying to make a String (ostensibly with some encoding) and it doesn't like &H0 as a value?

    Read the article

  • Received a RAMPAGE IV FORMULA MOBO. Possible CPU Socket problems

    - by Tantan
    I recently received a Rampage IV Formula MOBO in a trade. From everything I read online this seems like a pretty nice piece of hardware. There's one thing I'm worried about though. It appears as though the socket where the CPU goes might have some bent/missing pins. I'm not exactly a computer expert and I wanted to know if this could be any sort of problem. I would post a picture but I apparently don't have enough rep for that... Also, if I did want to move my current rig onto the new MOBO would it even be worth it? MY CURRENT COMPUTER SPECS i3-3220 CPU 8GB DDR3 RAM GeForce GTX460 GPU With a Biostar MOBO!

    Read the article

  • constructors and inheritance in JS

    - by nandinga
    Hi all, This is about "inheritance" in JavaScript. Supose I create a constructor Bird(), and another called Parrot() which I make to "inherit" the props of Bird by asigning an instance of it to Parrot's prototype, like the following code shows: function Bird() { this.fly = function(){}; } function Parrot() { this.talk = function(){ alert("praa!!"); }; } Parrot.prototype = new Bird(); var p = new Parrot(); p.talk(); // Alerts "praa!!" alert(p.constructor); // Alerts the Bird function!?!?! After I've created an instance of Parrot, how comes that the .constructor property of it is Bird(), and not Parrot(), which is the constructor I've used to create the object? Thanks!!

    Read the article

  • Why to say, my function is of IFly type rather than saying it's Airplane type

    - by Vishwas Gagrani
    Say, I have two classes: Airplane and Bird, both of them fly. Both implement the interface IFly. IFly declares a function StartFlying(). Thus both Airplane and Bird have to define the function, and use it as per their requirement. Now when I make a manual for class reference, what should I write for the function StartFlying? 1) StartFlying is a function of type IFly . 2) StartFlying is a function of type Airplane 3) StartFlying is a function of type Bird. My opinion is 2 and 3 are more informative. But what i see is that class references use the 1st one. They say what interface the function is declared in. Problem is, I really don't get any usable information from knowing StartFlying is IFly type. However, knowing that StartFlying is a function inside Airplane and Bird, is more informative, as I can decide which instance (Airplane or Bird ) to use. Any lights on this: how saying StartFlying is a function of type IFly, can help a programmer understanding how to use the function?

    Read the article

  • Spaces around all hyphens in a string without double-up

    - by Dave
    I'm after a regex that puts spaces around each "-" in a string, eg. 02 jaguar-leopard, tiger-panther 08 would become 02 jaguar - leopard, tiger - panther 08 Note that if the "-" already has spaces around it, no changes are to be made, eg. 02 jaguar - leopard, tiger - panther 08 should not become 02 jaguar - leopard, tiger - panther 08 The number of hyphens are unknown in advance. Thanks for any ideas... Edit: I'm not actually using a language for this. I'm using Ant Renamer (a mass file renaming utility). There are two fields in the renamer GUI, "Expression" and "New name" to provide inputs. This is from the help file as an example: Swapping artist and title from mp3 file names: "Expression" = (.*) - (.*)\.mp3 "New name" = $2 - $1.mp3 Extract episode number and title from series video files with episode number as SnnEmm followed by title: "Expression" = Code\.Quantum\.S([0-9]{2})E([0-9]{2})\.(.*)\.FRENCH.XViD\.avi "New name" = Code Quantum - $1$2 - $3.avi

    Read the article

  • Characteristics of an Initialization Vector

    - by Jamie Chapman
    I'm by no means a cryptography expert, I have been reading a few questions around Stack Overflow and on Wikipedia but nothing is really 'clear cut' in terms of defining an IV and it's usage. Points I have discovered: An IV is pre-pended to a plaintext message in order to strengthen the encryption The IV is truely random Each message has it's own unique IV Timestamps and cryptographic hashes are sometimes used instead of random values, but these are considered to be insecure as timestamps can be predicted One of the weaknesses of WEP (in 802.11) is the fact that the IV will reset after a specific amount of encryptions, thus repeating the IV I'm sure there are many other points to be made, what have I missed? (or misread!)

    Read the article

  • La chine possède le deuxième supercalculateur le plus rapide au monde, qui vient juste derrière le s

    La Chine possède le deuxième supercalculateur le plus rapide au monde, qui arrive juste derrière le supercalculateur américain Jaguar XT Selon le classement semestriel Top500 mis à jour à l'occasion de l'International Supercomputing Conference (ISC), la chine occupe la deuxième position des supercalculateurs les plus rapides au monde, grâce à son supercalculateur Nebulae qui vient juste derrière l'américain Jaguar XT. [IMG]http://djug.developpez.com/rsc/Top-10-supercalc-june2010.PNG[/IMG] Ce monstre chinois possède une puissance de calcule de 1,271 petaflops sachant que le petaflops correspond à 10^15 d'opérations à la seconde, et qui peut arriver théoriquement jusqu'à 2,98 petaflops ce qui le place loin d...

    Read the article

  • highlight the word in the string, if it contains the keyword

    - by Syom
    how write the script, which menchion the whole word, if it contain the keyword? example: keyword "fun", string - the bird is funny, result - the bird is * funny*. i do the following $str = "the bird is funny"; $keyword = "fun"; $str = preg_replace("/($keyword)/i","<b>$1</b>",$str); but it menshions only keyword. the bird is *fun*ny

    Read the article

  • A more elegant way to parse a string with ruby regular expression using variable grouping?

    - by i0n
    At the moment I have a regular expression that looks like this: ^(cat|dog|bird){1}(cat|dog|bird)?(cat|dog|bird)?$ It matches at least 1, and at most 3 instances of a long list of words and makes the matching words for each group available via the corresponding variable. Is there a way to revise this so that I can return the result for each word in the string without specifying the number of groups beforehand? ^(cat|dog|bird)+$ works but only returns the last match separately , because there is only one group.

    Read the article

  • Using the Rijndael Object in VB.NET

    - by broke
    I'm trying out the Rijndael to generate an encrypted license string to use for our new software, so we know that our customers are using the same amount of apps that they paid for. I'm doing two things: Getting the users computer name. Adding a random number between 100 and 1000000000 I then combine the two, and use that as the license number(This probably will change in the final version, but I'm just doing something simple for demonstration purposes). Here is some sample codez: Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim generator As New Random Dim randomValue As Integer randomValue = generator.Next(100, 1000000000) ' Create a new Rijndael object to generate a key ' and initialization vector (IV). Dim RijndaelAlg As Rijndael = Rijndael.Create ' Create a string to encrypt. Dim sData As String = My.Computer.Name.ToString + randomValue.ToString Dim FileName As String = "C:\key.txt" ' Encrypt text to a file using the file name, key, and IV. EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV) ' Decrypt the text from a file using the file name, key, and IV. Dim Final As String = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV) txtDecrypted.Text = Final End Sub That's my load event, but here is where the magic happens: Sub EncryptTextToFile(ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate) Dim RijndaelAlg As Rijndael = Rijndael.Create Dim cStream As New CryptoStream(fStream, _ RijndaelAlg.CreateEncryptor(Key, IV), _ CryptoStreamMode.Write) Dim sWriter As New StreamWriter(cStream) sWriter.WriteLine(Data) sWriter.Close() cStream.Close() fStream.Close() End Sub There is a couple things I don't understand. What if someone reads the text file and recognizes that it is Rijndael, and writes a VB or C# app that decrypts it? I don't really understand all of this code, so if you guys can help me out I will love you all forever. Thanks in advance

    Read the article

  • UIImageView and UIScrollView load lot of pictures

    - by Allan.Chen
    In my app, i use UIImageView and UIScrollView to show lot of pictures(Every time there are about 20 pictures and every pictures about 600px*500px and size is about 600KB ), i use for this code to do this function. Here is code: //Here is pictures Data; self.klpArry = self.pictureData; CGSize size = self.klpScrollView1.frame.size; for (int i=0; i < [klpArr count]; i++) { UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake((size.width * i)+300, 20, 546, 546)]; NSString *filePath = [[NSBundle mainBundle] pathForResource:[klpArr objectAtIndex:i] ofType:@"jpg"]; UIImage *imageData = [[UIImage alloc]initWithData:[NSData dataWithContentsOfFile:filePath]]; [iv setImage:imageData]; iv.backgroundColor = [UIColor grayColor]; [self.klpScrollView1 addSubview:iv]; imageData = nil; iv = nil; iv.image = nil; filePath = nil; [imageData release]; [filePath release]; [iv release]; } // show the picture in scrollview; [self.klpScrollView1 setContentSize:CGSizeMake(size.width * numImage, size.height)]; self.klpScrollView1.pagingEnabled = YES; self.klpScrollView1.showsHorizontalScrollIndicator = NO; self.klpScrollView1.backgroundColor = [UIColor grayColor]; But everytime i init this function, the memory will increase about 5MB, Actually i release UIImageView, UIimage and UIScrollView (vi.image=nil,[vi release]) but i doesn't work, it can't release the memory. BTW, i use my friend code first vi.image=nil then vi=nil; but the pictures not to show on scrollview. any one can help me ?? Thx ~~

    Read the article

  • Jquery convert string of one type to string array.....

    - by chandru_cp
    Consider a string which is {"Table" : [{"Bird" : "Peacock"}, {"Bird" : "Crow"}]} to this ["Peacock", "Crow"] in jquery... Is this possible? EDIT: I am doing this but didnt work... $(document).ready(function() { var obj = JSON.parse('{"Table" : [{"Bird" : "Peacock"},{"Bird" : "Crow"}]}'); myarray = []; $.each(obj.table, function(i, v) { myarray.push(v.Bird); }); $("#tags").autocomplete(myarray, { width: 138, max: 4, highlight: false, multiple: true, multipleSeparator: " ", scroll: true, scrollHeight: 300 }); });

    Read the article

  • PHP: Simple, Validate if string is hex?

    - by oni-kun
    I have no clue how to validate this string. I am simply supplying an IV for an encryption, but can find no "is_hex()" or similar function, I can't wrap my head around it! I read on a comment in the php documentation (user contrib. notes) this: if($iv == dechex(hexdec($iv))) { //True } else { //False } But that doesn't seem to work at all.. It only says false. If it helps my input of my IV would be this: 92bff433cc639a6d

    Read the article

  • is this aes encryption wrapper safe ? - yet another take...

    - by user393087
    After taking into accound answers for my questions here and here I created (well may-be) improved version of my wrapper. The key issue was what if an attacker is knowing what is encoded - he might then find the key and encode another messages. So I added XOR before encryption. I also in this version prepend IV to the data as was suggested. sha256 on key is only for making sure the key is as long as needed for the aes alg, but I know that key should not be plain text but calculated with many iterations to prevent dictionary attack function aes192ctr_en($data,$key) { $iv = mcrypt_create_iv(24,MCRYPT_DEV_URANDOM); $xor = mcrypt_create_iv(24,MCRYPT_DEV_URANDOM); $key = hash_hmac('sha256',$key,$iv,true); $data = $xor.((string)$data ^ (string)str_repeat($xor,(strlen($data)/24)+1)); $data = hash('md5',$data,true).$data; return $iv.mcrypt_encrypt('rijndael-192',$key,$data,'ctr',$iv); } function aes192ctr_de($data,$key) { $iv = substr($data,0,24); $data = substr($data,24); $key = hash_hmac('sha256',$key,$iv,true); $data = mcrypt_decrypt('rijndael-192',$key,$data,'ctr',$iv); $md5 = substr($data,0,16); $data = substr($data,16); if (hash('md5',$data,true)!==$md5) return false; $xor = substr($data,0,24); $data = substr($data,24); $data = ((string)$data ^ (string)str_repeat($xor,(strlen($data)/24)+1)); return $data; } $encrypted = aes192ctr_en('secret text','password'); echo $encrypted; echo aes192ctr_de($encrypted,'password'); another question is if ctr mode is ok in this context, would it be better if I use cbc mode ? Again, by safe I mean if an attacter could guess password if he knows exact text that was encrypted and knows above method. I assume random and long password here. Maybe instead of XOR will be safer to random initial data with another run of aes or other simpler alg like TEA or trivium ?

    Read the article

  • WP: AesManaged encryption vs. mcrypt_encrypt

    - by invalidusername
    I'm trying to synchronize my encryption and decryption methods between C# and PHP but something seems to be going wrong. In the Windows Phone 7 SDK you can use AESManaged to encrypt your data I use the following method: public static string EncryptA(string dataToEncrypt, string password, string salt) { AesManaged aes = null; MemoryStream memoryStream = null; CryptoStream cryptoStream = null; try { //Generate a Key based on a Password, Salt and HMACSHA1 pseudo-random number generator Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt)); //Create AES algorithm with 256 bit key and 128-bit block size aes = new AesManaged(); aes.Key = rfc2898.GetBytes(aes.KeySize / 8); aes.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // rfc2898.GetBytes(aes.BlockSize / 8); // to check my results against those of PHP var blaat1 = Convert.ToBase64String(aes.Key); var blaat2 = Convert.ToBase64String(aes.IV); //Create Memory and Crypto Streams memoryStream = new MemoryStream(); cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write); //Encrypt Data byte[] data = Encoding.Unicode.GetBytes(dataToEncrypt); cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); //Return Base 64 String string result = Convert.ToBase64String(memoryStream.ToArray()); return result; } finally { if (cryptoStream != null) cryptoStream.Close(); if (memoryStream != null) memoryStream.Close(); if (aes != null) aes.Clear(); } } I solved the problem of generating the Key. The Key and IV are similar as those on the PHP end. But then the final step in the encryption is going wrong. here is my PHP code <?php function pbkdf2($p, $s, $c, $dk_len, $algo = 'sha1') { // experimentally determine h_len for the algorithm in question static $lengths; if (!isset($lengths[$algo])) { $lengths[$algo] = strlen(hash($algo, null, true)); } $h_len = $lengths[$algo]; if ($dk_len > (pow(2, 32) - 1) * $h_len) { return false; // derived key is too long } else { $l = ceil($dk_len / $h_len); // number of derived key blocks to compute $t = null; for ($i = 1; $i <= $l; $i++) { $f = $u = hash_hmac($algo, $s . pack('N', $i), $p, true); // first iterate for ($j = 1; $j < $c; $j++) { $f ^= ($u = hash_hmac($algo, $u, $p, true)); // xor each iterate } $t .= $f; // concatenate blocks of the derived key } return substr($t, 0, $dk_len); // return the derived key of correct length } } $password = 'test'; $salt = 'saltsalt'; $text = "texttoencrypt"; #$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); #echo $iv_size . '<br/>'; #$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); #print_r (mcrypt_list_algorithms()); $iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; $key = pbkdf2($password, $salt, 1000, 32); echo 'key: ' . base64_encode($key) . '<br/>'; echo 'iv: ' . base64_encode($iv) . '<br/>'; echo '<br/><br/>'; function addpadding($string, $blocksize = 32){ $len = strlen($string); $pad = $blocksize - ($len % $blocksize); $string .= str_repeat(chr($pad), $pad); return $string; } echo 'text: ' . $text . '<br/>'; echo 'text: ' . addpadding($text) . '<br/>'; // -- works till here $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv); echo '1.' . $crypttext . '<br/>'; $crypttext = base64_encode($crypttext); echo '2.' . $crypttext . '<br/>'; $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, addpadding($text), MCRYPT_MODE_CBC, $iv); echo '1.' . $crypttext . '<br/>'; $crypttext = base64_encode($crypttext); echo '2.' . $crypttext . '<br/>'; ?> So to point out, the Key and IV look similar on both .NET and PHP, but something seems to be going wrong in the final call when executing mcrypt_encrypt(). The end result, the encrypted string, differs from .NET. Can anybody tell me what i'm doing wrong. As far as i can see everything should be correct. Thank you! EDIT: Additional information on the AESManaged object in .NET Keysize = 256 Mode = CBC Padding = PKCS7

    Read the article

  • mcrypt_decrypt return strange code

    - by Jin Yong
    I tried to encrypt an array then decrypt it back to string by calling a function, it's seem return the correct value if I does all encrypt and decrypt at once time in the function, however, if I return the encrypt value, then call the function again to decrypt it will return me some strange code. Exmaple: public main() { $dataArray = array("one"=>1, "two"=>2, "three"=>3); $a = $this->encryptDecryptInfo(json_encode($dataArray),$this->key); var_dump($a); } public function encryptDecryptInfo($text,$key) { $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, $text= base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CFB, $iv)); return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($text), MCRYPT_MODE_CFB, $iv); } This will return me the correct value which is string(27) "{"one":1,"two":2,"three":3}" Exmaple 2: public main() { $dataArray = array("one"=>1, "two"=>2, "three"=>3); $a = $this->encryptDecryptInfo(json_encode($dataArray),$this->key,"encrypt"); $b = $this->encryptDecryptInfo($a,$this->key,"decrypt"); var_dump($b); } public function encryptDecryptInfo($text,$key,$type) { $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), MCRYPT_RAND); if($type == "encrypt") return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CFB, $iv)); else return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($text), MCRYPT_MODE_CFB, $iv); } However if I do my code in this way, it will return me strange value which is like this string(27) "?ÔérôŸY éXgíœÈÐN*é౜CµÖ" .Deos anyone know why this is happen?

    Read the article

  • Decryption Key value not match

    - by Jitendra Jadav
    public class TrippleENCRSPDESCSP { public TrippleENCRSPDESCSP() { } public void EncryptIt(string sData,ref byte[] sEncData,ref byte[] Key1,ref byte[] Key2) { try { // Create a new TripleDESCryptoServiceProvider object // to generate a key and initialization vector (IV). TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider(); // Create a string to encrypt. // Encrypt the string to an in-memory buffer. byte[] Data = EncryptTextToMemory(sData,tDESalg.Key,tDESalg.IV); sEncData = Data; Key1 = tDESalg.Key; Key2 = tDESalg.IV; } catch (Exception) { throw; } } public string DecryptIt(byte[] sEncData) { //byte[] toEncrypt = new ASCIIEncoding().GetBytes(sEncData); //XElement xParser = null; //XmlDocument xDoc = new XmlDocument(); try { //string Final = ""; string sPwd = null; string sKey1 = null; string sKey2 = null; //System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string soutxml = ""; //soutxml = encoding.GetString(sEncData); soutxml = ASCIIEncoding.ASCII.GetString(sEncData); sPwd = soutxml.Substring(18, soutxml.LastIndexOf("</EncPwd>") - 18); sKey1 = soutxml.Substring(18 + sPwd.Length + 15, soutxml.LastIndexOf("</Key1>") - (18 + sPwd.Length + 15)); sKey2 = soutxml.Substring(18 + sPwd.Length + 15 + sKey1.Length + 13, soutxml.LastIndexOf("</Key2>") - (18 + sPwd.Length + 15 + sKey1.Length + 13)); //xDoc.LoadXml(soutxml); //xParser = XElement.Parse(soutxml); //IEnumerable<XElement> elemsValidations = // from el in xParser.Elements("EmailPwd") // select el; #region OldCode //XmlNodeList objXmlNode = xDoc.SelectNodes("EmailPwd"); //foreach (XmlNode xmllist in objXmlNode) //{ // XmlNode xmlsubnode; // xmlsubnode = xmllist.SelectSingleNode("EncPwd"); // xmlsubnode = xmllist.SelectSingleNode("Key1"); // xmlsubnode = xmllist.SelectSingleNode("Key2"); //} #endregion //foreach (XElement elemValidation in elemsValidations) //{ // sPwd = elemValidation.Element("EncPwd").Value; // sKey1 = elemValidation.Element("Key1").Value; // sKey2 = elemValidation.Element("Key2").Value; //} //byte[] Key1 = encoding.GetBytes(sKey1); //byte[] Key2 = encoding.GetBytes(sKey2); //byte[] Data = encoding.GetBytes(sPwd); byte[] Key1 = ASCIIEncoding.ASCII.GetBytes(sKey1); byte[] Key2 = ASCIIEncoding.ASCII.GetBytes(sKey2); byte[] Data = ASCIIEncoding.ASCII.GetBytes(sPwd); // Decrypt the buffer back to a string. string Final = DecryptTextFromMemory(Data, Key1, Key2); return Final; } catch (Exception) { throw; } } public static byte[] EncryptTextToMemory(string Data,byte[] Key,byte[] IV) { try { // Create a MemoryStream. MemoryStream mStream = new MemoryStream(); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream cStream = new CryptoStream(mStream, new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), CryptoStreamMode.Write); // Convert the passed string to a byte array. //byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data); byte[] toEncrypt = ASCIIEncoding.ASCII.GetBytes(Data); // Write the byte array to the crypto stream and flush it. cStream.Write(toEncrypt, 0, toEncrypt.Length); cStream.FlushFinalBlock(); // Get an array of bytes from the // MemoryStream that holds the // encrypted data. byte[] ret = mStream.ToArray(); // Close the streams. cStream.Close(); mStream.Close(); // Return the encrypted buffer. return ret; } catch (CryptographicException e) { MessageBox.Show("A Cryptographic error occurred: {0}", e.Message); return null; } } public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV) { try { // Create a new MemoryStream using the passed // array of encrypted data. MemoryStream msDecrypt = new MemoryStream(Data); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream csDecrypt = new CryptoStream(msDecrypt, new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), CryptoStreamMode.Write); csDecrypt.Write(Data, 0, Data.Length); //csDecrypt.FlushFinalBlock(); msDecrypt.Position = 0; // Create buffer to hold the decrypted data. byte[] fromEncrypt = new byte[msDecrypt.Length]; // Read the decrypted data out of the crypto stream // and place it into the temporary buffer. msDecrypt.Read(fromEncrypt, 0, msDecrypt.ToArray().Length); //csDecrypt.Close(); MessageBox.Show(ASCIIEncoding.ASCII.GetString(fromEncrypt)); //Convert the buffer into a string and return it. return new ASCIIEncoding().GetString(fromEncrypt); } catch (CryptographicException e) { MessageBox.Show("A Cryptographic error occurred: {0}", e.Message); return null; } } }

    Read the article

  • Suggestion for creating custom sound recognition software to toggle audio

    - by Parrot owner
    I need to develop a program that toggles a particular audio track on or off when it recognizes a parrot scream or screech. The software would need to recognize a particular range of sounds and allow some variations in the range (as a parrot likely won't replicate its sreeches EXACTLY each time). Example: Bird screeches, no audio. Bird stops screeching for five seconds, audio track praising the bird plays. Regular chattering needs to be ignored completely, as it is not to be discouraged. I've heard of java libraries that have speech recognition with dictionaries built in, but the software would need to be taught the particular sounds that my particular parrot makes - not words or any random bird sound. In addition as I mentioned above, it would need to allow for slight variation in the sound, as the screech will likely never be 100% identical to the recorded version. What would be the best way to go about this/what language should I look into?

    Read the article

  • Is foreign key reference from two different primary key from two different tables valid?

    - by arundex
    I have a foreign key that has to refer primary keys of two different tables. Table 1: animal animal_ id (primary key) Table 2: bird bird_ id (primary key) Table 3: Pet_info pet_id, type ENUM ('bird', 'animal') foreign key (pet_ id) references animal(animal_id), bird(bird_id) So, I need to check for pet_id either from animal or bird table depending on the need. Is this valid? Or should I go for some restructuring . . . NOTE: I referred this . . but I'm not sure whether I have to change my existing design

    Read the article

  • Camera lookAt target changes when rotating parent node

    - by Michael IV
    have the following issue.I have a camera with lookAt method which works fine.I have a parent node to which I parent the camera.If I rotate the parent node while keeping the camera lookAt the target , the camera lookAt changes too.That is nor what I want to achieve.I need it to work like in Adobe AE when you parent camera to a null object:when null object is rotated the camera starts orbiting around the target while still looking at the target.What I do currently is multiplying parent's model matrix with camera model matrix which is calculated from lookAt() method.I am sure I need to decompose (or recompose ) one of the matrices before multiplying them .Parent model or camera model ? Anyone here can show the right way doing it ? UPDATE: The parent is just a node .The child is the camera.The parented camera in AfterEffects works like this: If you rotate the parent node while camera looks at the target , the camera actually starts orbiting around the target based on the parent rotation.In my case the parent rotation changes also Camera's lookAt direction which IS NOT what I want.Hope now it is clear .

    Read the article

  • SSIS Training 15-19 Oct in Reston Virginia

    - by andyleonard
    Early bird registration is now open for Linchpin People ’s SSIS training course From Zero To SSIS scheduled for 15-19 Oct 2012 in Reston Virginia! Register today – the early bird discount ends 28 Sep 2012. Training Description From Zero to SSIS was developed by Andy Leonard to train technology professionals in the fine art of using SQL Server Integration Services (SSIS) to build data integration and Extract-Transform-Load (ETL) solutions. The training is focused around labs and emphasizes a hands-on...(read more)

    Read the article

  • Index independent character comparison within text blocks

    - by Michael IV
    I have the following task: developing a program where there is a block of sample text which should be typed by user. Any typos the user does during the test are registered. Basically, I can compare each typed char with the sample char based on caret index position of the input, but there is one significant flaw in such a "naive" approach. If the user typed mistakenly more letters than a whole string has, or inserted more white spaces between the string than should be, then the rest of the comparisons will be wrong because of the index offsets added by the additional wrong insertions. I have thought of designing some kind of parser where each string (or even a char ) is tokenized and the comparisons are made "char-wise" and not "index-wise," but that seems to me like an overkill for such a task. I would like to get a reference to possibly existing algorithms which can be helpful in solving this kind of problem.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >