【发布时间】:2011-03-27 23:18:45
【问题描述】:
我想用我自己的密钥使用 AES 加密一个字符串。但是我在密钥的位长度上遇到了问题。您能否查看我的代码并查看我需要修复/更改的内容。
public static void main(String[] args) throws Exception {
String username = "bob@google.org";
String password = "Password1";
String secretID = "BlahBlahBlah";
String SALT2 = "deliciously salty";
// Get the Key
byte[] key = (SALT2 + username + password).getBytes();
System.out.println((SALT2 + username + password).getBytes().length);
// Need to pad key for AES
// TODO: Best way?
// Generate the secret key specs.
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal((secrectID).getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " + originalString + "\nOriginal string (Hex): " + asHex(original));
}
现在我收到异常“无效的 AES 密钥长度:86 字节”。我需要垫我的钥匙吗?我该怎么做?
我还需要为 ECB 或 CBC 设置什么吗?
谢谢
【问题讨论】:
-
哈哈,好笑。实际上我确实有一个随机盐,但我清理了我的代码以使我的问题更清楚。这就是变量命名为 SALT2 的原因。但对于遇到同样问题并喜欢复制/粘贴代码的其他人来说,这是一个很好的参考。