Mainly I'm trying to understand how to correctly create the Key and IV for use with the .NET Implementation of AES (AesManaged class).
This encryption code will be used in conjunction with existing customer records in a database.
Here is the process that I've come up with. First, get the key from an encrypted web.config and get a byte array using the Rfc2898DeriveBytes class. The salt is a constant.
public static byte[] GetKey(string key)
{
var deriveBytes = new Rfc2898DeriveBytes(key, _salt);
return deriveBytes.GetBytes(32);
}
Next, generate another byte array for the IV given the User's ID and the same salt from above. This method is essentially the same, but returns an array with 16 bytes instead of 32 (and the input is the User ID, not the key).
public static byte[] GetKey(string text)
{
var deriveBytes = new Rfc2898DeriveBytes(text, _salt);
return deriveBytes.GetBytes(16);
}
Given the Key and the IV I use a CryptoStream to encrypt the data:
var aesAlg = new AesManaged();
// Create an encryptor to perform the stream transform.
var encryptor = aesAlg.CreateEncryptor(key, iv);
// ... Code that uses the Crypto Stream
Main question(s):
- Is there a better/different class that I should be using instead of
Rfc2898DeriveBytes
? It seems funny that the class name references an RFC. - Is the use of a constant salt bad? I'm doing this so that I don't need to store any additional information on the User record. Other examples I've seen use a constant IV, but a random Salt. Are those 2 scenarios essentially the same?
Rfc2898DeriveBytes
generates your key byte array and itself takes a salt - for generating the salt you'd need a CSPRNG - like this: http://stackoverflow.com/questions/1668353/how-can-i-generate-a-cryptographically-secure-pseudorandom-number-in-c. You can use the same CSPRNG to generate your IV bytes - they simply need to be random - we might have a question already about deriving IV and keys from the output of PBKDF2 but that's stretching my personal expertise a bit. – Feb 01 '12 at 14:33Rfc2898DeriveBytes
constructor for the salt length, which I assumes mean that it will generate the salt for you. I think that should suffice for what I'm doing. FYI, I this project Encryptamajig that I'm building to act as a reference for encryption in C#. Right now it's pretty basic, but if you check out the Dev branch you can see what I'm doing. Hopefully I'll push some changes and merge into master later today with what I've learned here :) – John B Feb 01 '12 at 15:25