Search code examples
c#encryptionaes

CBC Encryption block size for 128 bit mode


I have a requirement to encrypt a string using AES with CBC in 128 bits

What do I need to set the block size to for this?

 var iv = "0000000000000000000000000000000000000000000000000000000000000000".ToByteArray();

 using (Aes myAes = Aes.Create())
 {
     myAes.Mode = CipherMode.CBC;

     // Encrypt the string to an array of bytes.
     byte[] encrypted = EncryptStringToBytes_Aes(xml, myAes.Key, iv);

     // Decrypt the bytes to a string.
     string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, iv);

     //Display the original data and the decrypted data.
     Console.WriteLine("Original:   {0}", xml);
     Console.WriteLine("Round Trip: {0}", roundtrip);
 }

Strangely enough my specification doesnt appear to cater for the IV

I havent been given anyway of telling the other side what the IV is so I think I will have to use a string of 0s, I thought it was 64 characters long so I have used the code above

Can someone help please?


Solution

  • Putting aside any and all notion of security for a second that comes with sending the key/IV value or initializing them to static values...

    Your code appears to come from the AES documentation from Microsoft, so why not just stick with the generated IV value?

    In case you absolutely want to set the IV yourself (shudders) you need to set it to a 128 bit value or 16 bytes. I don't know what your String.ToByteArray() code does exactly but if I were to hazard a guess, it probably converts the String to bytes using some encoding like UTF8 or ASCII. In either case, your IV array is going to be a lot more than 16 bytes in length. Just use something like byte[] iv = new byte[16]; which will default initialize all slots to 0.

    HOWEVER, since you mentioned I highly encourage you to double check how the key/IV are meant to be generated or conveyed to the other party.