gautham
gautham

Reputation: 87

Exception in thread "main" java.security.InvalidKeyException: Illegal key size. char length of key is 44

Exception in thread "main" java.security.InvalidKeyException: Illegal key size for below code

Char length of the key is 44. I tried with char length 24 am able to encrypt. Please help how to resolve this issue.


public static void main(String args[]) throws Exception {
    String plainText = "Hello world!";
    String encryptionKeyBase64 = "DWIzFkO22qfVMgx2fIsxOXnwz10pRuZfFJBvf4RS3eY=";
    System.out.println(encryptionKeyBase64.length());
    String ivBase64 = "AcynMwikMkW4c7+mHtwtfw==";
    EncDec encDec = new EncDec();
    String cipherText = encDec.encrypt(plainText, encryptionKeyBase64, ivBase64);
}

 public String encrypt(String plainText, String keyBase64, String ivBase64) throws Exception
    {
        byte[] plainTextArray = plainText.getBytes(StandardCharsets.UTF_8);
        byte[] keyArray = DatatypeConverter.parseBase64Binary(keyBase64);
        byte[] iv = DatatypeConverter.parseBase64Binary(ivBase64);

        SecretKeySpec secretKey = new SecretKeySpec(keyArray, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");   
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
        return new String(DatatypeConverter.printBase64Binary(cipher.doFinal(plainTextArray)));
    }

    public String decrypt(String messageBase64, String keyBase64, String ivBase64) throws Exception {

        byte[] messageArray = DatatypeConverter.parseBase64Binary(messageBase64);
        byte[] keyArray = DatatypeConverter.parseBase64Binary(keyBase64);
        byte[] iv = DatatypeConverter.parseBase64Binary(ivBase64);

        SecretKey secretKey = new SecretKeySpec(keyArray, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
        return new String(cipher.doFinal(messageArray));
    }
}```

Upvotes: 0

Views: 431

Answers (1)

Michael Fehr
Michael Fehr

Reputation: 6414

As you are using "AES" as encryption-scheme the key lengths must be 16, 24 or 32 bytes in the input of SecretKeySpec.

So you should check the length of the byte[] keyArray and not the length of your String "encryptionKeyBase64" and make sure it's of 16/24/32 byte length.

You can add the line

System.out.println("keyArray.length: " + 
DatatypeConverter.parseBase64Binary(encryptionKeyBase64).length);

before you're using it in your encryption-/decryption method.

Btw.: the initialisation vector "iv" has to be of 16 bytes length (fixed, regardless of key length). You can check that easily with

System.out.println("iv.length:       " + DatatypeConverter.parseBase64Binary(ivBase64).length);

Upvotes: 2

Related Questions