Search code examples
c#hashaesencryption-symmetric

generating AES 256 bit key value


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?


Solution

  • 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};