I need to generate a key to use when encrypting a file symmetrically using AES256/CBC
The key itself will be encrypted with RSA public/private so I don't need a password applied.
In Java, this seems to be done as follows:
SecureRandom random = new SecureRandom();
byte[] keyBytes = new byte[32]; //32 Bytes = 256 Bits
random.nextBytes(keyBytes);
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
However, SecretKeySpec
isn't defined in the C# BouncyCastle library available via NuGet.
What's the C# equivalent? Since I'm not using a password, is it sufficient to just grab the next n random bytes from SecureRandom
(which does exist)?
As long as you are just using AES, you can get away with just building a KeyParameter class directly. However, there are symmetric algorithms with classes of known weak keys and/or other restrictions on what is a valid key, e.g. DESEDE.
If your code needs to handle multiple algorithms (or modes) generically, then you will be better off using Org.BouncyCastle.Security.GeneratorUtilites to get an appropriate key generator for the algorithm. Likewise, ParameterUtilities is preferred in the general case e.g. for adding an IV.
Likewise the Java code you gave will work OK for AES, but if you want to generalise across ciphers and modes, you ought to be using the KeyGenerator and AlgorithmParameterGenerator APIs.
You can certainly just use the Bouncy Castle KeyParameter
class using any well seeded PRNG, yes. The KeyParameter
class handles more or less the same as SecretKeySpec
although you don't have to specify the algorithm.
Here's a solution you can try:
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
CipherKeyGenerator gen = new CipherKeyGenerator();
gen = GeneratorUtilities.GetKeyGenerator("AES"); // using ASE algo
byte[] k = gen.GenerateKey(); // 256 bit key