我想用我自己的密鑰使用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