java - Java AES 解密异常:javax.crypto.BadPaddingException:
问题描述
public static String encrypt(String strToEncrypt) {
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
if (strToEncrypt != null) {
try {
IvParameterSpec ivspec = new IvParameterSpec(key);
SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8), Constants.AES);
Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception ex) {
LOGGER.error(CommonUtil.exceptionErrorPrefixSuffix("Encryption Exception in DoEncryption::encrypt", ex));
}
}
return null;
}
public static String decrypt(String id) throws UnsupportedEncodingException {
String decryptedId = null;
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8),Constants.AES);
byte[] decodedCiphertext = Base64.getDecoder().decode(id);
try {
IvParameterSpec ivspec = new IvParameterSpec(key);
Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
cipher.init(Cipher.DECRYPT_MODE, keySpec , ivspec);
byte[] original = cipher.doFinal(decodedCiphertext);
decryptedId = new String(original);
return decryptedId;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
加密工作正常。但是在解密时会引发异常。
javax.crypto.BadPaddingException:给定最终块未正确填充。如果在解密期间使用了错误的密钥,则可能会出现此类问题。在 cipher.doFinal(decodedCiphertext);
提前致谢。
解决方案
这里的问题是您在加密和解密方法中随机生成密钥。但由于您使用的是 AES 算法(对称算法),因此加密和解密的密钥应保持相同。
推荐阅读
- twitter-bootstrap-3 - Bootstrap Accordion:subcollapse 应在关闭 supercollapse 时关闭
- windows - 在编辑器打开文件夹之前,Unity 不会通过脚本创建 apk
- javascript - 只有在我选择了范围之后才在范围滑块观察程序中执行代码,而不是在我滑动滑块时一直执行?
- java - 带有返回语句的奇怪警告
- laravel - Laravel 迁移创建用户“意外'使用'(T_USE)”SQLite
- teradata - 根据各种条件寻找天数
- javascript - 打字稿定义 - 嵌套函数
- javascript - IE setData 拖放
- java - 如何在 Spring Boot 2 应用程序中使用实体继承?
- php - PHP这是什么数据格式