我需要实现256位AES加密,但我在网上找到的所有示例都使用“KeyGenerator”来生成256位密钥,但我想使用我自己的passkey。如何创建自己的密钥?我尝试将其填充到256位,但随后我得到一个错误,说键太长。我确实安装了无限管辖权补丁,所以这不是问题:)

Ie。KeyGenerator是这样的…

// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available

// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();

这里的代码

EDIT

我实际上是把密码填充到256字节,不是位,太长了。以下是我现在使用的一些代码,我有了更多的经验。

byte[] key = null; // TODO
byte[] input = null; // TODO
byte[] output = null;
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
output = cipher.doFinal(input)

你需要自己做的“TODO”部分:-)

哪一个在什么情况下更受欢迎?

我想看看各种模式的评估标准列表,也许还有每个标准的适用性的讨论。

For example, I think one of the criteria is "size of the code" for encryption and decryption, which is important for micro-code embedded systems, like 802.11 network adapters. IF the code required to implement CBC is much smaller than that required for CTR (I don't know this is true, it's just an example), then I could understand why the mode with the smaller code would be preferred. But if I am writing an app that runs on a server, and the AES library I am using implements both CBC and CTR anyway, then this criterion is irrelevant.

看到我说的“评估标准清单和每个标准的适用性”了吗??

这与编程无关,但与算法有关。