-1

I want to encrypt a message with AES encryption techniques. When i use this code i got some error as

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

My Encryption code :

public class Encryption {

    public static class MessageEncrypt {

        public static class AES {
            private final static String ALGO = "AES";
            private String secretKey;
            private String data;

            public String encrypt(String secretKey, String data) throws Exception {
                SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
                KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 128, 256);
                SecretKey tmp = factory.generateSecret(spec);
                SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGO);
                Cipher cipher = Cipher.getInstance(ALGO);
                cipher.init(Cipher.ENCRYPT_MODE, key);
                return toHex(cipher.doFinal(data.getBytes()));
            }

            public String decrypt(String secretKey, String data) throws Exception {
                SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
                KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 128, 256);
                SecretKey tmp = factory.generateSecret(spec);
                SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGO);
                Cipher cipher = Cipher.getInstance(ALGO);
                cipher.init(Cipher.DECRYPT_MODE, key);
                return new String(cipher.doFinal(toByte(data)));
            }

            private static byte[] toByte(String hexString) {
                int len = hexString.length() / 2;
                byte[] result = new byte[len];
                for (int i = 0; i < len; i++)
                    result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
                return result;
            }

            public static String toHex(byte[] stringBytes) {
                StringBuffer result = new StringBuffer(2 * stringBytes.length);
                for (int i = 0; i < stringBytes.length; i++) {
                    result.append(HEX.charAt((stringBytes[i] >> 4) & 0x0f)).append(HEX.charAt(stringBytes[i] & 0x0f));
                }
                return result.toString();
            }

            private final static String HEX = "0123456789ABCDEF";
        }
    }

    static class DataEncrypt {

    }

}

My Testing Program :

public class Testing {

    public static void main(String[] args) throws Exception {

        AES cryptoAES = new AES();
        System.out.println(cryptoAES.encrypt("43234sfeff", "re"));

    }

}

When i run this i got this error as:

Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1021)
    at javax.crypto.Cipher.implInit(Cipher.java:796)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:859)
    at javax.crypto.Cipher.init(Cipher.java:1229)
    at javax.crypto.Cipher.init(Cipher.java:1166)
    at com.detroit.Encryption$MessageEncrypt$AES.encrypt(Encryption.java:35)
    at testing.Testing.main(Testing.java:10)

Working in Android Studio :

But the Same code working in Android (Android Studio), but when i run the same code in netbeans i got such kind of errors.
MrBhuyan
  • 151
  • 2
  • 17
  • Dupe https://stackoverflow.com/questions/46362489/try-to-understand-before-marking-duplicate-invalidkeyexception-illegal-key-siz and https://stackoverflow.com/questions/3862800/invalidkeyexception-illegal-key-size and https://stackoverflow.com/questions/33055995/java-lang-illegalargumentexception-unable-to-initialize-due-to-invalid-secret-k . Also using password (it's not really a key though you call it one) as salt is insecure, 128 iterations is not secure, and ECB is insecure in most usages -- but those are offtopic here. – dave_thompson_085 Jun 20 '18 at 07:01
  • Please don't use StringBuffer as it was replaced by StringBuilder in 2004. – Peter Lawrey Jun 22 '18 at 19:55

3 Answers3

1

You could also use the OpenJDK which doesn't have this restriction.

Anyone who has worked in cryptography knows the import/export of cryptographic code involves complicated legal issues. The JCE in OpenJDK has an open cryptographic interface, meaning it does not restrict which providers can be used.

Edit: I couldn't reply to Jens with a comment as I am too noob.

blindcant
  • 39
  • 3
0

This exception occurse if you do not have installled the JCE (Java Cryptography Extension).

For Java 8 you find the JCE package here

Jens
  • 67,715
  • 15
  • 98
  • 113
0

Easiest solution is to upgrade your jdk to jdk1.8.0_161 or later release.

As there is a good news as java packaging comes bundled with both the limited and unlimited policy jars starting from jdk1.8.0_161 and by default it uses unlimited policy settings. So, all we need to do is use upgraded java version(jdk1.8.0_161 or later releases

OR

By default, java installation packaging comes with 128-bit key size, and here you are using key of larger size it seems.

For this to work properly, we need to install java cryptography extension unlimited strength policy jars from here.

You need to update the java security policy jars with unlimited strength policy jars.


Installation

Notes:

• Unix (Solaris/Linux/Mac OS X) and Windows use different pathname separators, so please use the appropriate one ("\", "/") for your environment.

• (below) refers to the directory where the JRE was installed. It is determined based on whether you are running JCE on a JRE or a JRE contained within the Java Development Kit, or JDK(TM). The JDK contains the JRE, but at a different level in the file hierarchy. For example, if the JDK is installed in /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then is:

/home/user1/jdk1.8.0/jre [Unix] C:\jdk1.8.0\jre [Windows]

If on the other hand the JRE is installed in /home/user1/jre1.8.0 on Unix or in C:\jre1.8.0 on Windows, and the JDK is not installed, then is:

/home/user1/jre1.8.0 [Unix] C:\jre1.8.0 [Windows]

• On Windows, for each JDK installation, there may be additional JREs installed under the "Program Files" directory. Please make sure that you install the unlimited strength policy JAR files for all JREs that you plan to use.

Here are the installation instructions:

1. Download, uncompress and extract the unlimited strength JCE policy files from here .

This will create a subdirectory called UnlimitedJCEPolicyJDK8. This directory contains the following files:

local_policy.jar             Unlimited strength local policy file
US_export_policy.jar         Unlimited strength US export policy file

2. Copy the unlimited strength policy JAR files. These files will already be there, we need to replace with the attached ones.

<java-home>/lib/security           [Unix]
<java-home>\lib\security           [Windows]
beingmanish
  • 1,040
  • 8
  • 21