C#无法生成初始化向量IV

发布于 2024-09-08 09:03:02 字数 581 浏览 13 评论 0原文

当我尝试为 TripleDES 加密器创建 IV 初始化向量时,出现以下错误。

请看代码示例:

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;

这是我从VS得到的异常。

指定的初始化向量 (IV) 与该算法的块大小不匹配。

我哪里出错了?

谢谢

I get the following error when I try to create a IV initialization vector for TripleDES encryptor.

Please see the code example:

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 that I get from the VS.

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

Where am I going wrong?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

雪化雨蝶 2024-09-15 09:03:02

MSDN 明确声明

...IV 属性的大小必须与 BlockSize 属性相同。

对于 Triple DES,它是 64 位。

MSDN explicitly states that:

...The size of the IV property must be the same as the BlockSize property.

For Triple DES it is 64 bits.

难忘№最初的完美 2024-09-15 09:03:02

初始化向量的大小必须与块大小匹配 - 在 TripleDES 的情况下为 64 位。您的初始化向量比八个字节长得多。

此外,您应该真正使用密钥派生函数,例如 PBKDF2 从密码短语创建强密钥和初始化向量。

The size of the initialization vector must match the block size - 64 bit in case of TripleDES. Your initialization vector is much longer than eight bytes.

Further you should really use a key derivation function like PBKDF2 to create strong keys and initialization vectors from password phrases.

揽月 2024-09-15 09:03:02

Key 应为 24 字节,IV 应为 8 字节。

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

Key should be 24 bytes and IV should be 8 bytes.

tripDES.Key = Encoding.ASCII.GetBytes("123456789012345678901234");
tripDES.IV = Encoding.ASCII.GetBytes("12345678");
遮云壑 2024-09-15 09:03:02

IV 的长度(以位为单位)必须与 tripDES.BlockSize 相同。对于 TripleDES,这将是 8 个字节(64 位)。

The IV must be the same length (in bits) as tripDES.BlockSize. This will be 8 bytes (64 bits) for TripleDES.

猥琐帝 2024-09-15 09:03:02

我在这里对每个答案都投了赞成票(以及在我之前的答案!),因为它们都是正确的。

然而,你犯了一个更大的错误(我早期也犯过这个错误)——不要使用绳子来播种 IV 或钥匙!

编译时字符串文字是一个 unicode 字符串,尽管事实上您不会获得随机或足够广泛的字节值(因为即使是随机字符串也包含大量重复字节,因为字节范围很窄)可打印字符),很容易得到一个实际上需要 2 个字节而不是 1 个字节的字符 - 尝试在键盘上使用 8 个更奇特的字符,你就会明白我的意思 - 当转换为字节时,你最终可以得到超过8个字节。

好的 - 所以你正在使用 ASCII 编码 - 但这并不能解决非随机问题。

相反,您应该使用 RNGCryptoServiceProvider 来初始化您的 IV 和 Key,如果您需要为此捕获一个常量值以供将来使用,那么您仍然应该使用该类 - 但将结果捕获为 hex 字符串或 Base-64 编码值(不过我更喜欢十六进制)。

为了简单地实现这一点,我编写了一个在 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;
}

可能有更好的方法来做到这一点 - 但它对我有用。

I've upvoted every answer (well the ones that are here before mine!) here as they're all correct.

However there's a bigger mistake you're making (one which I also made v.early on) - DO NOT USE A STRING TO SEED THE IV OR KEY!!!

A compile-time string literal is a unicode string and, despite the fact that you will not be getting either a random or wide-enough spread of byte values (because even a random string contains lots of repeating bytes due to the narrow byte range of printable characters), it's very easy to get a character which actually requires 2 bytes instead of 1 - try using 8 of some of the more exotic characters on the keyboard and you'll see what I mean - when converted to bytes you can end up with more than 8 bytes.

Okay - so you're using ASCII Encoding - but that doesn't solve the non-random problem.

Instead you should use RNGCryptoServiceProvider to initialise your IV and Key and, if you need to capture a constant value for this for future use, then you should still use that class - but capture the result as a hex string or Base-64 encoded value (I prefer hex, though).

To achieve this simply, I've written a macro that I use in VS (bound to the keyboard shortcut CTRL+SHIFT+G, CTRL+SHIFT+H) which uses the .Net PRNG to produce a hex string:

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

Now all you need to do is to turn your hex string literal into a byte array - I do this with a helpful extension method:

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;
}

There are probably better ways of doing that bit - but it works for me.

半透明的墙 2024-09-15 09:03:02

我这样做是这样的:

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

IV 使用算法本身通过 LegalBlockSizes 属性描述的块大小从派生字节“smusher”获取字节。

I do it like this:

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

The IV gets bytes from the derive bytes 'smusher' using the block size as described by the algorithm itself via the LegalBlockSizes property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文