2

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)?

Community
  • 1
  • 1
Basic
  • 26,321
  • 24
  • 115
  • 201

3 Answers3

2

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
1

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.

Peter Dettman
  • 3,867
  • 20
  • 34
  • I have gotten thus far: var cipher = new GcmBlockCipher(new AesFastEngine()); KeyParameter keyParameter = ParameterUtilities.CreateKeyParameter("AES", key); ICipherParameters cipherParameters = new ParametersWithIV(keyParameter, IV); cipher.Init(false, cipherParameters); When I watch the properties of cipher, the Algorithm name is AES/GCM but I'm still lost on how to set a padding – Sudhanshu Mishra Jul 14 '15 at 05:54
  • I'm so sorry but for some reason, I never saw this answer. My apologies. Accepting as you provide the Right™ way to do it. – Basic Jan 12 '17 at 22:17
0

Here's a solution you can try:

using Org.BouncyCastle.Crypto;  
using Org.BouncyCastle.Security; 


CipherKeyGenerator gen = new CipherKeyGenerator();

gen = GeneratorUtilities.GetKeyGenerator("AES256"); // using AES

byte[] k = gen.GenerateKey(); // 256 bit key

Note: The parameter for GetKeyGenerator initiates currently a 192bit key for AES, if you just pass it "AES". To get different key sizes you need to modify your parameter as shown in the code example. To get an overview for additional variances take a look at the GetKeyGenerator-Method in the sourceCode.

Smittie
  • 489
  • 6
  • 11