【JAVA使用Aes加密报错:Illegal key size or default parameters,如何解决?】
JAVA使用Aes加密报错:Illegal key size or default parameters,如何解决?
遇到“Illegal key size or default parameters”这个错误通常与Java环境中使用的加密算法有关,特别是当你尝试使用较高级别的加密密钥长度(例如AES-256)时。这个问题的根本原因通常是由于Java运行时环境(JRE)默认的安全策略文件限制了加密强度,这主要是出于出口控制法规的历史原因。
重点:key和位数的限制必须要匹配,均为128位。
jdk1.8版本不能超过128位数。
这个报错是由于JDK1.8的版本导致的。网上提供的方法都是通过升级版本,或者修改对应的包来实现加密,如果不想升级JDK1.8版本,那么怎么解决这个问题呢?
只需要将默认key的位数改为128位的字符串即可。
报错信息记录:
jdk1.8版本使用cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM));,报错Illegal key size or default parameters,如何解决?
Invalid AES key length: 12 bytes
Given final block not properly padded:不匹配
上代码
package com.mxpt.common.security.utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesUtils{
public static String aesKey = "9D7E445B58C6A275777DRR";
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
public static void main(String[] args) throws Exception {
String key = "9D7E445B58C6A275A78164";
byte[] keyBytes = Base64.getDecoder().decode(key);
// 检查输出是否为期望位数128位
System.out.println("Key length: " + keyBytes.length * 8 + " bits");
}
/**
* 根据给定的密钥解密文本
*/
public static String decrypt(String encryptedData, String key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
byte[] keyBytes = Base64.getDecoder().decode(key);
System.out.println("Key length: " + keyBytes.length * 8 + " bits"); // 检查输出是否为期望位数
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM));
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedData)));
}
/**
* 使用给定的密钥加密文本
*/
public static String encrypt(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM));
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
}
/**
* 生成一个新的密钥
*/
public static String generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(KEY_SIZE);
SecretKey secretKey = keyGen.generateKey();
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
}
}
重点:key和位数的限制必须要匹配,均为128位。jdk1.8版本不能超过128位数。