Exception: java.security.InvalidKeyException: Illegal key size [How to Solve]

I encountered an exception when doing interface testing today:

 java.security.InvalidKeyException: Illegal key size.

        SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, "AES" );
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding" );
        IvParameterSpec ips = createCtrIv(nonce);
        cipher.init( 1 , secretKeySpec, ips); //When the code runs to this line, it reports an error. Broke the above exception

I felt stunned. Fortunately, the Internet is omnipotent. I found a solution by comparing it with Baidu. After testing, it was found that there was no problem.

Reason for the exception: If the key is greater than 128, java.security.InvalidKeyException: Illegal key size will be thrown. Because the key length is limited, the java runtime environment reads a restricted policy file. The file is located in ${ java_home)/jre/lib/security, this restriction is due to the control of software exports by the United States.

Solution: Go to the official to download the JCE unrestricted permission policy file.

jdk 5: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html#jce_policy-1.5.0-oth-JPR

jdk6: http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

JDK7 download address:  http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JDK8 download address:  http://www.oracle.com/technetwork/java /javase/downloads/jce8-download-2133166.html

After downloading and decompressing, you can see local_policy.jar, US_export_policy.jar and readme.txt.
If JRE is installed, put the two jar files in the %JRE_HOME%\lib\security directory to overwrite the original files.
If JDK is installed, also Put the two jar files in the %JDK_HOME%\jre\lib\security directory to overwrite the original files.

It’s ok.


Similar Posts: