我想用我自己的密钥使用AES加密字符串。但是我在密钥的位长上遇到了问题。你可以检查我的代码,看看我需要修复/更改。Java AES和使用我自己的密钥
public static void main(String[] args) throws Exception {
String username = "[email protected]";
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设置任何东西吗?
感谢
[我觉得你缺乏随机盐的干扰(http://d37nnnqwv9amwr.cloudfront.net/photos/images/newsfeed/000/065/003/Darth-Vader-I-FIND-你缺-OF-诚信DISTURBING.jpg)。现在认真:在密码学的背景下[SALT应该是随机的](http://en.wikipedia.org/wiki/Salt_(cryptography)) – 2012-01-02 15:40:10
哈哈,好笑。我其实有一个随机盐,但我清理了我的代码,使我的问题更清楚。这就是为什么变量名为SALT2。但对于遇到同样问题并喜欢复制/粘贴代码的其他人来说,这是很好的参考。 – 2012-03-23 18:40:53