如何在OpenJDK 11中配置Java加密扩展(JCE)



在Java 8之前,必须在JDK中下载并安装JCE才能使用它。我找不到Java 11的可下载扩展。有没有办法检查它是否默认配置?或者我应该通过配置手动激活它?

在OpenJDK 11中,无限制加密策略由默认安装。你可以在我的电脑上用这个输出的小程序来检查:

Check for unlimited crypto policies
Java version: 11.0.6+8-b520.43
restricted cryptography: false Notice: 'false' means unlimited policies
Security properties: unlimited
Max AES key length = 2147483647

代码:

import javax.crypto.Cipher;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
public class UnlimitedCryptoPoliciesCheck {
public static void main(String[] args) throws NoSuchAlgorithmException {
// Security.setProperty("crypto.policy", "limited"); // uncomment to switch to limited crypto policies
System.out.println("Check for unlimited crypto policies");
System.out.println("Java version: " + Runtime.version());
//Security.setProperty("crypto.policy", "limited"); // muss ganz am anfang gesetzt werden !
System.out.println("restricted cryptography: " + restrictedCryptography() + " Notice: 'false' means unlimited policies"); // false mean unlimited crypto
System.out.println("Security properties: " + Security.getProperty("crypto.policy"));
int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("Max AES key length = " + maxKeyLen);
}
/**
* Determines if cryptography restrictions apply.
* Restrictions apply if the value of {@link Cipher#getMaxAllowedKeyLength(String)} returns a value smaller than {@link Integer#MAX_VALUE} if there are any restrictions according to the JavaDoc of the method.
* This method is used with the transform <code>"AES/CBC/PKCS5Padding"</code> as this is an often used algorithm that is <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#impl">an implementation requirement for Java SE</a>.
*
* @return <code>true</code> if restrictions apply, <code>false</code> otherwise
* https://stackoverflow.com/posts/33849265/edit, author Maarten Bodewes
*/
public static boolean restrictedCryptography() {
try {
return Cipher.getMaxAllowedKeyLength("AES/CBC/PKCS5Padding") < Integer.MAX_VALUE;
} catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException("The transform "AES/CBC/PKCS5Padding" is not available (the availability of this algorithm is mandatory for Java SE implementations)", e);
}
}
}

如果你想(或必须(从无限加密策略切换到有限加密策略,你可以用放在第一位的一行代码来完成(这意味着这行代码应该在程序启动后直接执行,否则它将不起作用-只需删除注释标记(:

Security.setProperty("crypto.policy", "limited");

这是当切换到"0"时的结果;"有限":

Check for unlimited crypto policies
Java version: 11.0.6+8-b520.43
restricted cryptography: true Notice: 'false' means unlimited policies
Security properties: limited
Max AES key length = 128

最新更新