首页 > 解决方案 > 指定的初始化向量 (IV) 与在 asp.net 核心中使用 TripleDesImplementation 的算法的块大小不匹配

问题描述

我们正在使用带有TripleDesImplementation算法加密的 ASP.NET Core。

解密代码如下:

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;
}

但是在解密时,它会抛出如下错误:

指定的初始化向量 (IV) 与此算法的块大小不匹配。
参数名称:rgbIV

它在一个普通的 Asp.Net 网站上工作,但现在它抛出了一个错误。

标签: asp.net-corecryptographicexception

解决方案


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


推荐阅读