Generate AES key without password using BouncyCast

2019-04-02 04:31发布

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

3条回答
祖国的老花朵
2楼-- · 2019-04-02 04:51

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
查看更多
【Aperson】
3楼-- · 2019-04-02 04:59

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.

查看更多
混吃等死
4楼-- · 2019-04-02 05:12

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.

查看更多
登录 后发表回答