繁体   English   中英

RijndaelManaged CreateEncryptor在VB.NET中有效,但在C#中出错

[英]RijndaelManaged CreateEncryptor works in VB.NET but errors in C#

我试图将加密类从VB.NET Framework转换为C#.Net Standard,由于某些原因,在C#中的RijndaelManaged实例上调用CreateEncryptor方法时,出现如下错误。

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

这是有效的VB.NET代码

Dim password As PasswordDeriveBytes = New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

#Disable Warning BC40000 ' Type or member is obsolete
    Dim keyBytes() As Byte = password.GetBytes(keySize / 8)
#Enable Warning BC40000 ' Type or member is obsolete

Dim symmetricKey As RijndaelManaged = New RijndaelManaged

If (initVectorBytes.Length = 0) Then
    symmetricKey.Mode = CipherMode.ECB
Else
    symmetricKey.Mode = CipherMode.CBC
End If

encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

这是失败的C#代码

PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);

byte[] keyBytes = password.GetBytes((int)(keySize / (double)8));

RijndaelManaged symmetricKey = new RijndaelManaged();

if ((initVectorBytes.Length == 0))
    symmetricKey.Mode = CipherMode.ECB;
else
    symmetricKey.Mode = CipherMode.CBC;

encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

在C#中,keyBytes的值显示为“ byte [32]”,initVectorBytes的显示为“ byte [0]”

在VB中,keyBytes值显示为“ Length = 32”,而initVectorBytes显示为“ Length = 0”

在这两个版本中都遍历了代码之后,我可以看到的唯一区别是数据与对称密钥对象中似乎缺少了IVValue和KeyValue。

在此处输入图片说明

我需要做什么来解决这个问题?

看来您正在尝试使用'keySize'参数的类型和大小创建错误的keyBytes。 您能不能尝试以下操作:

PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);

byte[] keyBytes = password.GetBytes(keySize/8);

RijndaelManaged symmetricKey = new RijndaelManaged();

if ((initVectorBytes.Length == 0))
    symmetricKey.Mode = CipherMode.ECB;
else
    symmetricKey.Mode = CipherMode.CBC;

encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM