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?