我想创建一个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