0

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.

enter image description here

What do I need to do to fix this?

fosbie
  • 852
  • 1
  • 11
  • 21

1 Answers1

0

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);
Ayberk
  • 536
  • 2
  • 12
  • Thanks for the suggestion and that is tidier, but it didn't make any difference I'm afraid. – fosbie Dec 05 '18 at 16:12