使用BouncyCastle生成无密码的AES密钥 [英] Generate AES key without password using BouncyCastle

查看:1024
本文介绍了使用BouncyCastle生成无密码的AES密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用AES256 / CBC对称加密文件时,我需要生成一个密钥

I need to generate a key to use when encrypting a file symmetrically using AES256/CBC

密钥本身将使用RSA public / private加密,需要输入密码。

The key itself will be encrypted with RSA public/private so I don't need a password applied.

在Java中,这似乎是

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");

但是,未定义 SecretKeySpec C#BouncyCastle库通过NuGet提供。

However, SecretKeySpec isn't defined in the C# BouncyCastle library available via NuGet.

C#是什么?由于我没有使用密码,只需抓取 SecureRandom (确实存在)中的下一个 n 个随机字节即可;

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

推荐答案

只要你只是使用AES,你可以直接构建一个KeyParameter类。然而,存在具有已知弱密钥的类的对称算法和/或关于什么是有效密钥的其他限制,例如, DESEDE。

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.

如果您的代码需要一般处理多个算法(或模式),那么您将更好地使用Org.BouncyCastle.Security.GeneratorUtilites获取一个合适的键发生器的算法。同样,ParameterUtilities在一般情况下是优选的。添加一个IV。

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.

同样,你给出的Java代码对AES也可以正常工作,但是如果你想跨密码和模式推广,你应该使用KeyGenerator和AlgorithmParameterGenerator API。

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.

这篇关于使用BouncyCastle生成无密码的AES密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆