• Register
Welcome to Kodlogs, programming questions and answer website.
0 votes

Problem :

Today I installed Java on my server user and when I try to run my application, I get the following exception.
java.security.invalidkeyexception illegal key size or default parameters
by (6.9k points)  

1 Answer

0 votes

Solution :

This bellow code is the only solution. No need to download or update configuration files.

It is a reflection based solution and tested on java 8

Please call this method once, early in your program.

import javax.crypto.Cipher; 

import java.lang.reflect.Constructor;

 import java.lang.reflect.Field; 

import java.lang.reflect.Modifier; 

import java.util.Map;

public static void fixKeyLength()


String errorString = "Failed manually overriding key-length permissions."; 

int newMaxKeyLength; 

try { if ((newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES")) < 256) 

Class c = Class.forName("javax.crypto.CryptoAllPermissionCollection"); 

Constructor con = c.getDeclaredConstructor(); con.setAccessible(true); 

Object allPermissionCollection = con.newInstance(); 

Field f = c.getDeclaredField("all_allowed"); f.setAccessible(true); 

f.setBoolean(allPermissionCollection, true); 

c = Class.forName("javax.crypto.CryptoPermissions"); 

con = c.getDeclaredConstructor(); con.setAccessible(true); Object allPermissions = con.newInstance();

 f = c.getDeclaredField("perms"); 


((Map) f.get(allPermissions)).put("*",allPermissionCollection); 

c = Class.forName("javax.crypto.JceSecurityManager"); 

f = c.getDeclaredField("defaultPolicy"); 


Field mf = Field.class.getDeclaredField("modifiers"); mf.setAccessible(true); 

mf.setInt(f, f.getModifiers() & ~Modifier.FINAL); 

f.set(null, allPermissions); 

newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES"); 



catch (Exception e) { 

throw new RuntimeException(errorString, e); 

if (newMaxKeyLength < 256) throw new RuntimeException(errorString); 


Further Readings:

by (21.9k points)  
edited by