Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 720
bhs Avatar asked Jun 19 '13 16:06

bhs


2 Answers

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};
like image 91
User 12345678 Avatar answered Oct 03 '22 21:10

User 12345678


Probably the best way is to use PBKDF2 using SHA256 (which will generate 256 bit output) and a application specific salt & iteration count. You should be aware that using an application specific salt removed quite a lot of the protection from PBKDF2, so you may require additional protection to alleviate this issue. One method would be to make sure that the database is safe, and that a maximum amount of tries can be used.

You are correct in stipulating that a 32 char passphrase is not a 256 bit key. It does not contain enough entropy, and some bytes may not even have valid character representations.

like image 30
Maarten Bodewes Avatar answered Oct 03 '22 21:10

Maarten Bodewes