1

I wrote this class using the new JDK 9 release.

public class Encrypters {
    public static byte[] AESEncrypt(Key key, byte[] data) throws GeneralSecurityException {
        Cipher cipher=Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] encryptedData=cipher.doFinal(data);
        return encryptedData;
    }
}

I also wrote this helper class

public class Hashes {
    public static byte[] sha256Hash(byte[] input) {
        return hash(input, "SHA-256");
    }

    private static byte[] hash(byte[] input, String algorithm) {
        MessageDigest md=null;
        try {
            md=MessageDigest.getInstance(algorithm);
        } 
        catch (NoSuchAlgorithmException e) {}
        return md.digest(input);
    }
}

This is the usage to encrypt a String:

String password=...;
String data=...;
Key key=new SecretKeySpec(Hashes.sha256Hash(password.getBytes(), "AES"));
Encrypters.AESEncrypt(key, data.getBytes());

This code runs with both JDK 9 and JDK 7, but not with JDK 8. If I try to run with JDK 8 I get this error:

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

Why do I get this error? Is AES-256 not supported by Java 8?

NickL
  • 4,258
  • 2
  • 21
  • 38
Vin
  • 701
  • 1
  • 9
  • 30
  • It may not be relevant, but you should always define all aspects of your cipher. Don't just use "AES". You should also not be using ECB mode. Use "AES/CBC/PKCS5Padding" instead. – Luke Joshua Park Oct 28 '17 at 11:32

1 Answers1

4

It is supported, you just need to update your Java 8 JRE (link), or include the JCE policy file (link) The strong encryption was never included in the JRE by default, in the latest distributions it is. The reason why it works for Java 7 in your case, is probably because it is 7u171 or later. See JDK-8170157 for details on when this was backported to different versions.

NickL
  • 4,258
  • 2
  • 21
  • 38