我想創建一個AES加密方法,但由於某些原因,我不斷收到AES加密的Java密鑰長度無效
java.security.InvalidKeyException: Key length not 128/192/256 bits
下面是代碼:
public static SecretKey getSecretKey(char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException{
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
// NOTE: last argument is the key length, and it is 256
KeySpec spec = new PBEKeySpec(password, salt, 1024, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
return(secret);
}
public static byte[] encrypt(char[] password, byte[] salt, String text) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
SecretKey secret = getSecretKey(password, salt);
Cipher cipher = Cipher.getInstance("AES");
// NOTE: This is where the Exception is being thrown
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] ciphertext = cipher.doFinal(text.getBytes("UTF-8"));
return(ciphertext);
}
任何人都可以看到我做錯了什麼?我認爲它可能與SecretKeyFactory算法有關,但這是我能找到的唯一一個在我正在開發的終端系統上支持的算法。任何幫助,將不勝感激。謝謝。使用任何填充機制
您能否粘貼例外? – 2010-04-02 19:59:32
在[此鏈接]的早期文章中有一個答案(http://stackoverflow.com/questions/992019/java-256bit-aes-encryption/992413#992413)。希望這可以幫助! – 2010-04-02 20:23:02
因此,似乎Java實例不支持我所需要的: '帶有消息「非法密鑰大小或默認參數」的消息java.security.InvalidKeyException' – wuntee 2010-04-02 20:42:29