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.