我正在尝试创建 AES 加密方法,但由于某种原因我不断收到
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 算法有关,但这是我能找到的唯一一种在我正在开发的终端系统上受支持的算法。任何帮助,将不胜感激。谢谢。