【发布时间】:2017-02-12 16:44:55
【问题描述】:
为了生成 256 位的 AES 密钥,我编写了以下代码:
KeyGenerator keyGen;
try {
keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
return secretKey;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
我的加密方式是:
private byte[] aes256Encode(SecretKey key, IvParameterSpec iv, String message) throws InvalidKeyException,
InvalidAlgorithmParameterException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException
{
Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encrypted = cipher.doFinal(message.getBytes());
return encrypted;
}
而IV生成方法是:
private IvParameterSpec generateAESIV() {
// build the initialization vector (randomly).
SecureRandom random = new SecureRandom();
byte iv[] = new byte[16];//generate random 16 byte long
random.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
return ivspec;
}
但在加密时,它会抛出以下错误:
Exception in thread "main" java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
at javax.crypto.Cipher.implInit(Cipher.java:805)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1396)
at javax.crypto.Cipher.init(Cipher.java:1327)
谁能指出我在这里犯的错误?
【问题讨论】:
-
下次搜索异常消息时,在发布重复问题之前,好吗?
-
感谢@Tom 的建议。它对我有用!
标签: java encryption aes