asp.net-core - 指定的初始化向量 (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 网站上工作,但现在它抛出了一个错误。
解决方案
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
推荐阅读
- ios - 委托给另一个视图控制器不起作用
- scala - Spark Structured Streaming MemoryStream + Row + Encoders 问题
- java - 通过 gremlin java 客户端将数据远程推送到 Azure Cosmos db 时出错
- android - 对不同的按钮使用相同的活动,但使用 xml 资源执行不同的操作
- javascript - 为什么滚动时我的粘性导航栏的高度会消失?
- javascript - 在对象属性中拆分字符串并创建新数据集
- python - 一堆立方体的体积
- sabre - 调用 Sabre BargainFinderMax REST API 时出错 — ERR.2SG.PROVIDER_TIMEOUT
- python - url 未定义,在 python 和 selenium 中
- android - PopupMenu - 如何?