AES C# Encryption Decryption FIPS

1.7k views Asked by At

I'm trying to do the following test to return results that should return a specific cipher. They provide the Key, IV and Plaintext string as seen below.

But I am getting "Specified initialization vector (IV) does not match the block size for this algorithm."

I been stuck on this for a while and can't find a good simple example and tried a combination of things.

Below is my C# code. I tried to keep it very simple.

 string AesPlainText = "1654001d3e1e9bbd036a2f26d9a77b7f"; 
        string AesKey = "3ccb6039c354c9de72adc9ffe9f719c2c8257446c1eb4b86f2a5b981713cf998";
        string AesIV = "ce7d4f9679dfc3930bc79aab81e11723";

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.KeySize = 256;
        aes.IV = HexToByteArray(AesIV);
        aes.Key = HexToByteArray(AesKey);
        aes.Mode = CipherMode.CBC;

        // Convert string to byte array
        byte[] src = Encoding.Unicode.GetBytes(AesPlainText);

        // encryption
        using (ICryptoTransform encrypt = aes.CreateEncryptor())
        {
            byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

            // Convert byte array to Base64 strings
            Console.WriteLine(Convert.ToBase64String(dest));
        }

UPDATED PER ANSWER:

Thanks, great observation. I changed Encoding.UTF8.GetBytes to use HexToByteArray in the above example and it works now.

public static byte[] HexToByteArray(String hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}
1

There are 1 answers

0
Maarten Bodewes On BEST ANSWER

Your plaintext, key and IV seem to be specified in hexadecimals, so you need to decode the hexadecimals to get to the underlying bytes instead of performing UTF8 encoding.

You can get a byte array from hex here. Note that the name of the method should have something with hex in in, don't call it StringToByteArray or atoi or something stupid like that.