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?
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.
Good question. Both use the same underlying CSPRNG. The results are equally secure.
You can view this in the .NET Reference Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With