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#.
Specified initialization vector (IV) does not match the block size for this algorithm. Parameter name: rgbIV
This is the working VB.NET code
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
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]"
In VB keyBytes value shows as "Length=32" and initVectorBytes as "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.
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. 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.