Skip to content
Advertisement

Invalid AES key length: 20 bytes (Java 11)

I am trying to generate a key using Java. To be honest I am not that experienced with keys, password, ciphers and encryption.

And from whatever I have searched from this site, I see it as a very common problem. I did some reading and came up with this code that I wrote:

JavaScript

This is modified from an answer that I saw on another post. But I still get the “invalid length” error.

The error that I get is:

JavaScript

Trial.java:47 being the line: cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

Is there a one-size fits all solution to this? Or is it just my lack of understanding?

Any help would be appreciated.

Advertisement

Answer

Your key is 20 bytes long because secretKeyFactory.generateSecret(keySpec).getEncoded() returns the password some_random_password.

An easy way to fix the code is to use the key derivation PBKDF2WithHmacSHA512 instead of PBEWITHHMACSHA512ANDAES_256. This generates a key of the specified length based on the password and salt:

JavaScript

However, PBEWITHHMACSHA512ANDAES_256 can also be applied. This algorithm specifies a key derivation with PBKDF2WithHmacSHA512 and subsequent AES encryption. The implementation is functionally identical to yours, but requires a few more changes to the code:

JavaScript

Two other issues are:

  • You are using a 256 bytes salt, but only storing 16 bytes when concatenating. To be consistent with the concatenation, apply a 16 bytes salt: byte[] salt = new byte[16].
  • The output finalCiphertext.toString() returns only class and hex hashcode of the object, s. here. For a meaningful output use a Base64 or hex encoding of the byte[] instead, e.g. Base64.getEncoder().encodeToString(finalCiphertext).
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement