AES解密,IV长度

时间:2012-05-29 14:09:06

标签: c# encryption aes

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

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

我一直在搜索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#中找不到一个简单易懂的例子。

任何帮助?,

谢谢!

1 个答案:

答案 0 :(得分:5)

你拥有的密钥几乎肯定是一堆十六进制值而不是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};
相关问题