generating AES 256 bit key value

bhs picture bhs · Jun 19, 2013 · Viewed 24.7k times · Source

Does anyone know of a way to get a 256 bit key value generated from a pass phrase of any length? The encryption cannot be salted as the encrypted values need to be generated again and compared in the database. So a value must generate the same encrypted string each time it is encrypted.

Currently I'm using a 32 char key working on the possibly incorrect assumption this is 256 bits?

So, I would want 'the quick brown fox' to be converted to a suitable AES 256 bit key?

Answer

User 12345678 picture User 12345678 · Jun 19, 2013

You can construct the Rfc2898DeriveBytes Class with an arbitrary sized password and then derive a key of your desired size in this case, 256 bits (32 bytes):

private static byte[] CreateKey(string password, int keyBytes = 32)
{
    const int Iterations = 300;
    var keyGenerator = new Rfc2898DeriveBytes(password, Salt, Iterations);
    return keyGenerator.GetBytes(keyBytes);
}

In order to produce a deterministic output (i.e. same input will produce the same output) you will need to hard-code the salt. The salt must be at least 8 bytes:

private static readonly byte[] Salt = 
    new byte[] { 10, 20, 30 , 40, 50, 60, 70, 80};