Rajasingh Madhialagan
Rajasingh Madhialagan

Reputation: 23

Invalid AES Key length:39bytes

I am new to java. I am doing encryption and decryption of video files. When I provide a key of small length it works fine without any error. If I gave key of greater length it throws error.

private static void doCrypto(int cipherMode, String key, File inputFile,
        File outputFile) throws CryptoException {
    try {    
        Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(cipherMode, secretKey);         
        FileInputStream inputStream = new FileInputStream(inputFile);

        byte[] inputBytes = new byte[(int) inputFile.length()];
        inputStream.read(inputBytes);

        byte[] outputBytes = cipher.doFinal(inputBytes);

        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(outputBytes);            
        inputStream.close();
        outputStream.close();

    } catch(NoSuchPaddingException|NoSuchAlgorithmException|InvalidKeyException | BadPaddingException| IllegalBlockSizeException | IOException ex) {
        throw new CryptoException("Error encrypting/decrypting file",ex);
    }

I am getting the error caused by: java.security.InvalidKeyException: Invalid AES key length: 39 bytes

Please help me to fix the error in the below code

Upvotes: 2

Views: 4997

Answers (1)

jAC
jAC

Reputation: 5325

You need to use a specific key with a supported length, which means your key has to be either

  • 128 bit
  • 192 bit
  • 256 bit
  • ...

long. Yours is (see the error message) only 39 byte long.

So you need to convert the String (key) (or better hash the key before) into an array of byte and take the first n (where n is one of the values above) byte out of it.

import java.security.*;

byte[] bytesOfMessage = key.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] b = md.digest(bytesOfMessage); //Returns the SHA 256 hash and converts it into byte
// Continue with your code
Key secretKey = new SecretKeySpec(b , "AES");
...

Upvotes: 1

Related Questions