I am getting Invalid Key Size error when I try to use 256 bits key in AES encryption. I know I have to use JCE unlimited policy. I am using Jre1.8.0_181. So, I have set crypto.policy=unlimited in java.security file. I have also checked that I am using the correct jvm.
Even I am getting "unlimited" value whenever I use this code.
String value = System.getProperties("crypto.policy"); //getting value = "unlimited"
But after this, I am getting key size to 128 bits.
Cipher.getMaxAllowedKeyLength("AES");
I have followed this code from the following site: https://howtodoinjava.com/java/java-security/aes-256-encryption-decryption/
Code Added
public static void main(String[] args) {
String originalString = "howtodoinjava.com";
String encryptedString = AES256.encrypt(originalString);
String decryptedString = AES256.decrypt(encryptedString);
System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}
public class AES256 {
private static final String SECRET_KEY = "my_super_secret_key_ho_ho_ho";
private static final String SALT = "ssshhhhhhhhhhh!!!!";
public static String decrypt(String strToDecrypt) {
try {
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static String encrypt(String strToEncrypt) {
try {
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
return Base64.getEncoder()
.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
}