[英]RijndaelManaged CreateEncryptor works in VB.NET but errors in C#
I'm trying to convert an encryption class from VB.NET Framework to C# .Net Standard and for some reason I get an error as below when calling the CreateEncryptor method on an instance of RijndaelManaged in C#. 我试图将加密类从VB.NET Framework转换为C#.Net Standard,由于某些原因,在C#中的RijndaelManaged实例上调用CreateEncryptor方法时,出现如下错误。
Specified initialization vector (IV) does not match the block size for this algorithm.
指定的初始化向量(IV)与该算法的块大小不匹配。 Parameter name: rgbIV
参数名称:rgbIV
This is the working VB.NET code 这是有效的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)
And this is the failing C# code 这是失败的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);
In C# keyBytes value shows as "byte[32]" and initVectorBytes as "byte[0]" 在C#中,keyBytes的值显示为“ byte [32]”,initVectorBytes的显示为“ byte [0]”
In VB keyBytes value shows as "Length=32" and initVectorBytes as "Length=0" 在VB中,keyBytes值显示为“ Length = 32”,而initVectorBytes显示为“ Length = 0”
Having stepped through the code in both versions the only difference I can see with the data is that the IVValue and KeyValue seem to be missing in the symmetricKey object. 在这两个版本中都遍历了代码之后,我可以看到的唯一区别是数据与对称密钥对象中似乎缺少了IVValue和KeyValue。
What do I need to do to fix this? 我需要做什么来解决这个问题?
It looks like you are trying to create keyBytes with the wrong type and size of 'keySize' parameter. 看来您正在尝试使用'keySize'参数的类型和大小创建错误的keyBytes。 Can you please try following:
您能不能尝试以下操作:
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.