We are using ASP.NET Core with TripleDesImplementation algorithm encryption.

The decryption code is as below:

public static string Encrypt(string p_szStrValue)
{
    string vszEncryptedString = string.Empty;
    if (!p_szStrValue.Trim().Equals(string.Empty))
    {
        TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_192, IV_192), CryptoStreamMode.Write);
        StreamWriter sw = new StreamWriter(cs);
        sw.Write(p_szStrValue);
        sw.Flush();
        cs.FlushFinalBlock();
        ms.Flush();
        vszEncryptedString = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
    }
    return vszEncryptedString;
}

public static string Decrypt(string p_szStrValue)
{
    string vszDecryptedString = string.Empty;
    if (!p_szStrValue.Trim().Equals(string.Empty))
    {
        try
        {
            TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
            byte[] v_Buffer = Convert.FromBase64String(p_szStrValue);
            MemoryStream ms = new MemoryStream(v_Buffer);
            CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_192, IV_192), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            vszDecryptedString = sr.ReadToEnd();
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
    return vszDecryptedString;
}

But while decrypting, it throws the error as below:

Specified initialization vector (IV) does not match the block size for this algorithm.
Parameter name: rgbIV

It was working in a normal Asp.Net website, but now it's throwing an error.

1

There are 1 best solutions below

0
On

Could be too late, .Net Core doesn't do automatic truncation of the initialization vector, as .Net Framework does. This is why you are getting the error. You can use the first 8 bytes from your IV to decrypt, it should work and properly decrypt existing encrypted information.

The gist is the initialization vector on TripleDESCryptoServiceProvider (either the IV property or the rbgIV parameter on CreateEncryptor and CreateDecryptor methods) accepts a byte array. In .NET Core, that byte array for IV must be equal to a valid block size of the algorithm. For 3DES, that's 64-bits (8 bytes).

In .NET Framework, it would silently just use the first 8 bytes, even if you gave it 9, or 20.

When migrating from the .NET Framework to .NET Core, users that were erroneously passing in more than 8 bytes started getting exceptions. The fix for this is to just change your code during the migration to pass in just the first 8 bytes.

More information on GitHub issue https://github.com/dotnet/docs/issues/8184