下面的代码抛出此错误消息:
Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
Cipher dcipher;
byte[] salt = new String("12345678").getBytes();
int iterationCount = 1024;
int keyStrength = 256;
SecretKey key;
byte[] iv;
Decrypter(String passPhrase) throws Exception {
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
System.out.println("factory +" + factory);
KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt,
iterationCount, keyStrength);
System.out.println("spec " + spec);
SecretKey tmp = factory.generateSecret(spec);
System.out.println();
key = new SecretKeySpec(tmp.getEncoded(), "AES");
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
}
public String encrypt(String data) throws Exception {
dcipher.init(Cipher.ENCRYPT_MODE, key);
AlgorithmParameters params = dcipher.getParameters();
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] utf8EncryptedData = dcipher.doFinal(data.getBytes());
String base64EncryptedData = new sun.misc.BASE64Encoder()
.encodeBuffer(utf8EncryptedData);
System.out.println("IV "
+ new sun.misc.BASE64Encoder().encodeBuffer(iv));
System.out.println("Encrypted Data " + base64EncryptedData);
return base64EncryptedData;
有人知道为什么我会收到这个错误吗?
可能您尚未安装 JCE 策略文件。
下载此文件:
-
爪哇 6
-
爪哇 7
-
爪哇 8
并在${java.home}/jre/lib/security/.
中安装该文件
${java.home}
是指您的 Java 安装目录
对于 Mac:
- 打开查找器
- 按命令 + 移位 + G
- 类型
/Library/Java/JavaVirtualMachines
- 导航到您的 JDK 版本
- 然后
Contents/Home/jre/lib/security
- 解压缩下载的文件并将所有文件放在这里
对于命令行界面
unzip downloaded_policy_file.zip -d /Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security/
mv /Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security/UnlimitedJCEPolicyJDK<VERSION>/* /Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security
rm -rf Library/Java/JavaVirtualMachines/<JDK_VERSION>/Contents/Home/jre/lib/security/UnlimitedJCEPolicyJDK<VERSION>/
从此链接下载 Java 7 版 JCEhttp://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
并打开路径C:Program FilesJavajdk1.7.0_80jrelibsecurity
并将两个罐子粘贴到此处。(即使两个罐子已经存在,也会替换这两个罐子)
对于 JAVA 7,下载链接是 jce-7-download
在 Java\jdk1.7.0_10\jre\lib\security 中复制两个下载的 jar备份旧罐子以更安全。
如果您将Mac与自制软件一起使用
brew cask install jce-unlimited-strength-policy
从 JDK 1.8u151 开始,没有必要单独下载 JCE 库。 只需编辑:
$JDK_HOME/jre/lib/security/java.security
并取消注释该行:
crypto.policy=unlimited