Generate AES key without password using BouncyCastle

旧巷老猫 提交于 2019-12-21 06:08:22

问题


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


回答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.




回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/29596954/generate-aes-key-without-password-using-bouncycastle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!