C # Cannot create initialization vector IV

I get the following error when I try to create an IV initialization vector for TripleDES encryption.

See sample code:

TripleDESCryptoServiceProvider tripDES = new TripleDESCryptoServiceProvider();

byte[] key = Encoding.ASCII.GetBytes("SomeKey132123ABC");
byte[] v4 = key;
byte[] connectionString = Encoding.ASCII.GetBytes("SomeConnectionStringValue");
byte[] encryptedConnectionString = Encoding.ASCII.GetBytes("");

// Read the key and convert it to byte stream
tripDES.Key = key; 
tripDES.IV = v4;

This is the exception I get from VS.

The specified initialization vector (IV) does not match the block size for this algorithm.

Where am I going wrong?

thank

+1
source share
6 answers

I supported every answer (well, those here before mine!) Here, as they are all correct.

However, there is a big mistake you make (which I also made v.early on) - DO NOT USE A LINE TO MAKE IV OR KEY !!!

unicode , , , ( - ), , 2 1 - 8 , , - , 8 .

- ASCII, .

RNGCryptoServiceProvider IV Key, , , hex string Base-64 ( hex, ).

, , VS ( CTRL + SHIFT + G, CTRL + SHIFT + H), .Net PRNG :

Public Sub GenerateHexKey()
  Dim result As String = InputBox("How many bits?", "Key Generator", 128)

  Dim len As Int32 = 128

  If String.IsNullOrEmpty(result) Then Return

  If System.Int32.TryParse(result, len) = False Then
      Return
  End If

  Dim oldCursor As Cursor = Cursor.Current

  Cursor.Current = Cursors.WaitCursor

  Dim buff((len / 8) - 1) As Byte
  Dim rng As New System.Security.Cryptography.RNGCryptoServiceProvider()

  rng.GetBytes(buff)

  Dim sb As New StringBuilder(CType((len / 8) * 2, Integer))
  For Each b In buff
      sb.AppendFormat("{0:X2}", b)
  Next

  Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
  Dim editPoint As EnvDTE.EditPoint

  selection.Insert(sb.ToString())
  Cursor.Current = oldCursor
End Sub

, , - - :

public static byte[] FromHexString(this string str)
{
  //null check a good idea
  int NumberChars = str.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(str.Substring(i, 2), 16);
  return bytes;
}

, , , .

+4

MSDN , :

... IV , BlockSize.

Triple DES 64 .

+10

- 64 TripleDES. .

, PBKDF2, .

+6

IV ( ) tripDES.BlockSize. 8 (64 ) TripleDES.

+5

24 , IV 8 .

tripDES.Key = Encoding.ASCII.GetBytes("123456789012345678901234");
tripDES.IV = Encoding.ASCII.GetBytes("12345678");
+5

:

var derivedForIv = new Rfc2898DeriveBytes(passwordBytes, _saltBytes, 3);
_encryptionAlgorithm.IV = derivedForIv.GetBytes(_encryptionAlgorithm.LegalBlockSizes[0].MaxSize / 8);

IV "smusher" , , LegalBlockSizes.

0
source

All Articles