0

I'm trying to encrypt a file using AES in Java, but it's not working. I put in some prints to see where it failed, the first two are printing but not the third. I checked that the key and IV are the right sizes, 256 bits and 128 bits respectively. If they are both valid I don't know what else could be going wrong. Are there any glaring mistakes in my code? I haven't done this before. Any help is greatly appreciated!

public static String encryptAES(byte[] data, byte[] key, byte[] iv) throws Exception {
    Key k = new SecretKeySpec(key, "AES");
    System.out.println("key set");

    Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    System.out.println("cipher created");

    c.init(Cipher.ENCRYPT_MODE, k, new IvParameterSpec(iv));
    System.out.println("cipher initialised");

    byte[] encryptedDataBytes = c.doFinal(data);
    String encryptedData = Base64.getEncoder().encodeToString(encryptedDataBytes);
    return encryptedData;
}
Jack Finan
  • 99
  • 1
  • 8
  • 1
    Do you have any stacktrace? – Tolga Okur Nov 02 '17 at 13:14
  • 1
    See [illegal-key-size](https://stackoverflow.com/questions/24907530/java-security-invalidkeyexception-illegal-key-size-or-default-parameters-in-and/24907555#24907555) – t.m.adam Nov 02 '17 at 13:21
  • 1
    If your code works with 128 bit AES key, you may want to check : https://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters – Tolga Okur Nov 02 '17 at 13:32
  • Thanks guys, it was the key size. I installed the unlimited strength policy files and it's working now. Thank you! – Jack Finan Nov 02 '17 at 13:34
  • Please consider posting the stacktrace as well in the future, or else we will have to guess what the problem is. – NickL Nov 02 '17 at 13:39

0 Answers0