Caused by: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
时间: 2023-11-18 16:57:18 浏览: 296
Tess, if broken it is fix it you should
这个错误是由于在使用AES解密时,解密的字符串的数组长度不是16的倍数导致的。解决这个问题的方法是在加密时,将加密的字符串长度补齐到16的倍数,可以使用PKCS5Padding或者PKCS7Padding进行填充。具体的实现方法可以参考以下代码示例:
```java
public static String encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return Base64.encodeBase64String(result); // 加密
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result); // 解密
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
```
阅读全文