c# - AES 解密,IV 长度

标签 c# encryption aes

我正在尝试解密字符串,但我得到了

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

我已经在 SO 和网络上搜索了一段时间,我知道我的 IV 是 32 字节,应该是 16 字节,但我不知道如何实现它。要获取的字符串已使用 AES/CBC/PKCS5Padding 加密,我的代码(好吧,实际上我在网络上的某个地方找到了它)是

var btKey = Encoding.ASCII.GetBytes("7c6e1257d0e81ff55bda80cc904365ae");
var btIV = Encoding.ASCII.GetBytes("cf5e4620455cd7190fcb53ede874f1a8");

aesAlg.Key = btKey;
aesAlg.IV = btIV;

aesAlg.Padding = PaddingMode.PKCS7;

// Create a decrytor to perform the stream transform.
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(encodedTicketAsBytes))
  {
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)){
      using (StreamReader srDecrypt = new StreamReader(csDecrypt))
      {
        // Read the decrypted bytes from the decrypting stream
        // and place them in a string.
        plainText = srDecrypt.ReadToEnd();
      }
    }
  }

我不明白的是 aesAlg.Padding 的用法,说实话,据我所知,我在 C# 中还找不到一个简单的示例。

有什么帮助吗?

谢谢!!

最佳答案

您拥有的 key 几乎可以肯定是一堆十六进制值而不是 ASCII 字符。你正在做:

var btIV = Encoding.ASCII.GetBytes("cf5e4620455cd7190fcb53ede874f1a8");

它将像对待任何其他字符串一样对待它并将其转换为其二进制 ascii 字节。这些对我来说看起来像十六进制数字。每 2 个字符是一个单字节值。您可能想要类似的东西

var btIV = new byte[] {0xcf,0x5e,0x46,0x20,0x45,0x5c,0xd7,0x19,0x0f,0xcb,0x53,0xed,0xe8,0x74,0xf1,0xa8};

关于c# - AES 解密,IV 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10800857/

相关文章:

audio - 通过android加密音频文件,并通过后端Sails js对其解密

c# - 运行两次而不是一次时出现意外结果

c# - IPN模拟器错误

c# - 在 C# 中使用 DLL 导入很困难

AES 加密的 C# UTF8 编码问题

java - AESCipher(安卓)与 CCCrypt(ios)

php - 简单的 PHP 加密/解密(Mcrypt、AES)

javascript - 在 Node js 中加速 AES 解密

c# - HTML敏捷包: how to create indented HTML?

c# - 存储/设置 C# 应用程序配置设置的最佳方式是什么?