IV for encryption conversion. Expected IV length of 16 but was 24

5k views Asked by At

Can someone please tell me why I am getting this error message? Obviously it is some kind of conversion that I am missing

expected IV length of 16 but was 24

To call it I use

String encrypted = "E5ADDEB05D9D7B3925B7DE16B560D87C";
String sKey = "3985661DD71D591665BD39476636486B";
String sIv = "75E5FBB56AA78D05D246078A782553E1";
String decrypted = decrypt2(encrypted, sKey, sIv);
Log.i("--------------------------------> ", decrypted);

this is the procedure

public static String decrypt2(final String EncryptedMessageBase64,
                              final String symKeyHex,
                              final String sIvHex) {

    final byte[] symKeyData = Base64.decode((symKeyHex),Base64.DEFAULT);
    final byte[] byIvData = Base64.decode((sIvHex), Base64.DEFAULT);
    final byte[] EncryptedMessage = Base64.decode(EncryptedMessageBase64, Base64.DEFAULT);

    try
    {

        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        final int blockSize = cipher.getBlockSize();

        final SecretKeySpec symKey = new SecretKeySpec(symKeyData, "AES");
        Log.i("### iv size -------->", String.valueOf(blockSize));
        Log.i("### symKeyHex -------->", symKeyHex);
        Log.i("### sIvHex -------->", sIvHex);
        Log.i("### blockSize -------->", String.valueOf(blockSize));

        final IvParameterSpec iv = new IvParameterSpec(byIvData);

        final byte[] encryptedMessage = new byte[EncryptedMessage.length];

        cipher.init(Cipher.DECRYPT_MODE, symKey, iv);

This is the output

### iv size -------->: 16
### symKeyHex -------->: 3985661DD71D591665BD39476636486B
### sIvHex -------->: 75E5FBB56AA78D05D246078A782553E1
### blockSize -------->: 16
error: expected IV length of 16 but was 24
1

There are 1 answers

5
zaph On BEST ANSWER

You are doing Base64 decoding on the key and IV but they are hex encoded, you need to do hex decoding to binary.

symKeyHex and sIvHex are very clearly hex encoded values and EncryptedMessageBase64 is clearly Base64 encoded.

Depending on the libraries you have included in your project one possibility is:

final byte[] symKeyData = (byte[]) new Hex().decode(symKeyHex);
final byte[] byIvData   = (byte[]) new Hex().decode(sIvHex);

More: Base64 encoding represents 3 binary bytes as 4 ASCII characters. Hexadecimal encoding represents 1 binary byte as 2 ASCII characters.