java.lang.RuntimeException: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
时间: 2023-11-17 14:03:51 浏览: 47
这个错误通常是因为在使用填充密码时,解密的输入长度不是8的倍数。这可能是因为加密时使用了错误的填充模式或未正确处理加密数据的长度。要解决此问题,可以尝试以下几种方法:
1. 确保使用相同的填充模式进行加密和解密。例如,如果使用PKCS5Padding进行加密,则应使用相同的填充模式进行解密。
2. 确保加密和解密使用相同的密钥和初始化向量(IV)。
3. 确保加密和解密使用相同的字符编码。
4. 如果使用Base64编码对加密数据进行编码,请确保正确解码数据。
以下是一个示例代码,演示如何使用AES算法进行加密和解密,以及如何处理填充错误:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String KEY = "0123456789abcdef";
private static final String IV = "fedcba9876543210";
public static void main(String[] args) throws Exception {
String plaintext = "Hello, world!";
System.out.println("Original plaintext: " + plaintext);
// Encrypt the plaintext
byte[] ciphertext = encrypt(plaintext.getBytes("UTF-8"), KEY.getBytes("UTF-8"), IV.getBytes("UTF-8"));
System.out.println("Encrypted ciphertext: " + Base64.getEncoder().encodeToString(ciphertext));
// Decrypt the ciphertext
byte[] decrypted = decrypt(ciphertext, KEY.getBytes("UTF-8"), IV.getBytes("UTF-8"));
System.out.println("Decrypted plaintext: " + new String(decrypted, "UTF-8"));
}
public static byte[] encrypt(byte[] plaintext, byte[] key, byte[] iv) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(plaintext);
}
public static byte[] decrypt(byte[] ciphertext, byte[] key, byte[] iv) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(ciphertext);
}
}
```