JDK8的加密策略存在限制版本和无限制版本,随着越来越多的第三方工具只支持 JDK8,业务环境中,发现有些方法会报异常:
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class Test {
public static void main(String[] args) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("jasypt");
config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
System.out.println(encryptor.encrypt("1111"));
System.out.println(encryptor.decrypt("12313131"));
}
}
在上述代码和依赖包都是存在且正确的情况下,总是会出现报错:
org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an exception. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files in this Java Virtual Machine
查询后来发现我使用的jdk是152的。我使用的算法是PBEWITHHMACSHA512ANDAES_256。
但从Java 1.8.0_151和1.8.0_152开始,为JVM启用无限制强度管辖策略 有了一种新的更简单的方法。如果不启用此功能,则不能使用AES-256:
在 jre/lib/security 文件夹中查找文件 java.security,现在用文本编辑器打开java.security,并找到定义java安全性属性crypto.policy的行,它可以有两个值limited或unlimited - 默认值是limited。将其设置为:
crypto.policy=unlimited
这样子,就可以了。