I want to generate an Initialization Vector (IV) for my AES encryption method. I have defined the key size as 256 (since I am using AES) so my IV needs to 32 bytes in length (256 / 8). I wish to store the IV as a string representation so using UTF-8, this would equate to a 16 character string.
Here is the code I am using to generate and return the IV ...
using (var aesProv = new AesCryptoServiceProvider())
{
aesProv.GenerateIV();
return System.Text.Encoding.Default.GetString(aesProv.IV);
}
How do I go about making sure that the IV is 16 characters in length? Can I count on a 16 character length being generated because I am using an AES library? AesCryptoServiceProvider
I wish to store the IV as a string representation so using UTF-8, this would equate to a 16 character string.
No. Just don't do this. Yes, you could interpret the 32 bytes as a UCS-2 sequence, but it's a really bad idea. This isn't naturally text - it's arbitrary binary data, basically. You could very easily end up with an invalid sequence of UTF-16 code units, due to surrogate pairs etc.
Assuming you want a string representation that you're likely to be able to transport safely etc, I'd suggest just using base64:
return Convert.ToBase64String(aesProv.IV);
Or you could use hex, of course. Both of these will be considerably longer than 16 characters of course, but that's the "price" of dealing with data appropriately.
See more on this question at Stackoverflow