Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RandomNumberGenerator vs Aes generate key. Which should I use to get myself a key when using AES encryption (C#)

So I was checking some implementations online and I noticed that some people use the following way to generate a key:

        using (var random = RandomNumberGenerator.Create())
        {
            var key = new byte[32];
            random.GetBytes(key);
        }

While others use the generateKey method which is built in the AES class:

        using (Aes myAes = Aes.Create())
        {
            myAes.GenerateKey();
            var key = myAes.Key;
        }

Both of them are in the System.Security.Cryptography library, just wondering if there is an actual difference between them and if yes which one should I go with?

like image 832
Ali_Nass Avatar asked Mar 22 '18 11:03

Ali_Nass


2 Answers

Both versions do the same thing. Aes.GenerateKey will use the same RandomNumberGenerator.Create() as first example to generate new key.

However I'd prefer to use second version, because:

1) It expresses intent very clear. You are generating AES key, not just arbitrary random byte array.

2) AES can have different key sizes. Not only that, but some key sizes are invalid for AES. First example now generates 32-byte keys only. If you modify it to accept key size - someone can pass invalid (for AES) key size to it. So you will need to validate passed size to verify it's a valid key size for AES. But why do that if Aes class already does that for you?

Side note: there is no need to call GenerateKey, though it does not harm too. If there is no key yet - it will be generated when you first access Key property.

like image 83
Evk Avatar answered Sep 18 '22 21:09

Evk


Good question. Both use the same underlying CSPRNG. The results are equally secure.

You can view this in the .NET Reference Source

like image 37
Luke Joshua Park Avatar answered Sep 21 '22 21:09

Luke Joshua Park