1

I am now trying to develop a AES 256 CFB encryption program in Java.

I wish to use my own secret key (Hex). However, it returned that there is something wrong with the key length.

Here is the code

class encryption_different {
private static String SECRET_KEY = "afd7a42b34f4875e05d210ea1252e02d5305becdb752f3553d657bab1236f733";

public static String encrypt(String strToEncrypt) {
    try {

        //IV handling
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        //convert custom key string to Secret key format
        byte[] decodedKey = Base64.getDecoder().decode(SECRET_KEY);
        SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, originalKey, 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;
}
public static void main(String[] args){
    encrypt("password1");
}
}

The error message I got:

Error while encrypting: java.security.InvalidKeyException: Invalid AES key length: 48 bytes

And therefore, I would like to know why I am getting this error message and how to fix it.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
littlesam
  • 45
  • 5
  • Why? A newly generated key is (a) correct and (b) more secure. NB You have just compromised the one you want to use. – user207421 Apr 26 '22 at 10:15
  • coz the key is provided and required to use. – littlesam Apr 26 '22 at 10:29
  • Does this answer your question? [How to fix Invalid AES key length?](https://stackoverflow.com/questions/29354133/how-to-fix-invalid-aes-key-length) – Tasos P. Apr 26 '22 at 10:43
  • 3
    You say your secret key is hex, yet you try to decode it with base64. You need to use `java.util.HexFormat` (Java 17 or higher) or another hex decoder, not a base64 decoder. A 64 character hex string decoded as hex is 32 bytes, but when decode as base64, it is 48 bytes. – Mark Rotteveel Apr 26 '22 at 10:51
  • it works after using hex decoder, thanks for that! – littlesam Apr 28 '22 at 02:41

0 Answers0