dave0688
dave0688

Reputation: 5770

Spring Security: Simple Encryption / decryption not working: InvalidKeyException

I'm trying to write a very simple program to encrypt and decrypt a string:

    String password = "kdfljxcasd";
    String encodeThat = "Hello World + some special chars!^^-";
    String salt = KeyGenerators.string().generateKey();
    BytesEncryptor encryptor = Encryptors.standard(password, salt);

    // breakpoint steping doesn't reach that point - it gets stuck here for some reason... 
    byte[] encrypted = encryptor.encrypt(encodeThat.getBytes());
    byte[] decrypted = encryptor.decrypt(encrypted);

    System.out.println("Before encryption: " + encodeThat);     
    System.out.println("Encrypted: " + encrypted.toString());       
    System.out.println("After encryption: " + decrypted.toString());

But for some reason I never get an encrypted value. When I call enryptor.encrypt() it never reaches that point.

I'm getting the following exception:

'Unable to initialize due to invalid secret key' java.lang.IllegalArgumentException: Unable to initialize due to invalid secret key

What am I doing wrong?

Upvotes: 1

Views: 2189

Answers (4)

Jeremy W
Jeremy W

Reputation: 1935

Ran into this problem and fixed it by switching from JDK 1.8 to Adopt Open JDK 8

Upvotes: 0

Adir Dayan
Adir Dayan

Reputation: 1617

Try to upgrade to newer java 8 JDK version.

For me I tried 2 versions:

  • 1.8.131 - failed
  • 1.8.201 - success

Upvotes: 0

Fragalli
Fragalli

Reputation: 259

Since Java 8u151 you can resolve this with a property:

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

Upvotes: 0

dave0688
dave0688

Reputation: 5770

Ok, after hours of searching I finally found the solution:

Appearently I didn't have the correct policies for unlimited Strength installed.

That's the way I solved it:

  1. Download the policies from: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

  2. Unpack that and put local_policy.jar and US_export_policy.jar into ${jdk -path}/jre/lib/security and override the existing files. (ATTENTION: Don't put it in the JRE folder. You have to put it into jdk/jre/... ... - that took me hours :) )

  3. Restart the server and it works!

Hope that helped :)

Upvotes: 3

Related Questions