Caused by: java.security.InvalidKeyException: Illegal key size or default parameters

How to remove the key size restriction in Java JDK?

Are you developing your beautiful application using the Java Cryptography Extension, and using a key length of more than 128 bits you encounter the following error?


Caused by: java.security.InvalidKeyException: Illegal key size or default parameters

There is nothing wrong that you are doing: JDK has a deliberate key size restriction by default, so you cannot use an encryption with key more than 128 bits.

From Oracle’s documentation:

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files shipped with the JDK 5.0 from Sun Microsystems specify that “strong” but limited cryptography may be used.

Some countries have restrictions on the permitted key strength used in encryption algorithms:

An “unlimited strength” version of these files indicating no restrictions on cryptographic strengths is available for those living in eligible countries (which is most countries). But only the “strong” version can be imported into those countries whose governments mandate restrictions. The JCE framework will enforce the restrictions specified in the installed jurisdiction policy files.


How to remove the key size restriction?

You can remove the maximum key restriction by replacing the existing JCE jars with unlimited strength policy jars.

Copy local_policy.jar and US_export_policy.jar extracted from above zip file to the $JAVA_HOME/jre/lib/security

Then simply restart you java application and the Exception should be gone.

 

from:https://www.andreafortuna.org/java/java-tips-how-to-fix-the-invalidkeyexception-illegal-key-size-or-default-parameters-runtime/

 

如果不方便覆盖文件,可以在代码中通过反射修改,在main中调用一下方法就Ok了:

/**
     * 去除JCE限制
     */
    private static void removeJceLimit() { //去除JCE加密限制,只限于Java1.8 try { Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, false); LOGGER.info("============= remove the key size restriction Success ============="); } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { ex.printStackTrace(System.err); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值