Create a key and initialization vector from a password with C#
Posted: (EET/GMT+2)
The .NET base class library has extensive support for cryptography, and you might for example need to encrypt a file with, say, the Rijndael (AES) algortihm. For that purpose, .NET supports the RijndaelManaged class, for instance. But, this and many other security classes require you to pass in a byte array for a key and the initialization vector (IV). How could you come up with this data in code? Hard-coded values are of course no good, and that's why there's for example a helper class called Rfc2898DeriveBytes. This class uses RFC 2898 to create a key and IV from a set of bytes, which -- you guessed it -- can be the user's password. Here's how to do it:
using System.Security.Cryptography;
...
public static void GetKeyAndIvFromPassword(string password, out byte[] key, out byte[] iv)
{
const int keyBytes = 256 / 8;
const int ivBytes = 128 / 8;
//TODO: Change salt value to something else
byte[] salt = { 34, 234, 192, 19, 98, 214, 201, 84, 175, 74, 163, 132 };
Rfc2898DeriveBytes keyGen = new Rfc2898DeriveBytes(password, salt);
key = keyGen.GetBytes(keyBytes);
iv = keyGen.GetBytes(ivBytes);
}
This little function should solve many of your needs. Just remember to change your salt value to something different, or better yet, use truly random data.