java如何解决以下报错:Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
时间: 2024-01-16 15:18:29 浏览: 973
解决"Given final block not properly padded. Such issues can arise if a bad key is used during decryption."报错的方法有两种:
1. 使用原来加密的密钥进行解密:这个报错是由于解密的密钥和加密的密钥不一致导致的。所以,如果你有加密时使用的密钥,可以尝试使用相同的密钥进行解密操作。
2. 使用新的密钥进行加密解密操作:如果你无法获取原来加密时使用的密钥,或者不确定密钥是否正确,可以尝试使用新的密钥进行加密和解密操作。确保在加密和解密过程中使用相同的密钥。
以下是使用Java解决该报错的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtils {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(cipherText);
}
public static String decrypt(String cipherText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(plainText, StandardCharsets.UTF_8);
}
public static void main(String[] args) {
try {
String originalText = "Hello, world!";
String key = "1234567890123456";
String encryptedText = encrypt(originalText, key);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```