使用RijndaelManaged时出现CryptographicException

时间:2012-10-22 20:16:35

标签: c# encryption aes

我正在尝试使用.NET中的RijndaelManaged类加密一串文本。但是,我不断收到CryptographicException(“要解密的数据长度无效”)。这条消息并不完全有用,尤其是当我尝试加密数据而不是解密时。以下是代码。

public static string EncryptKMSToken(string valueToEncrypt, string encryptionKey)
{
  string results = string.Empty;

  using (RijndaelManaged aes = new RijndaelManaged())
  {
    aes.BlockSize = 128;
    aes.KeySize = 128;
    aes.Padding = PaddingMode.PKCS7;
    aes.Mode = CipherMode.CBC;

    UTF8Encoding byteTransform = new UTF8Encoding();
    aes.Key = byteTransform.GetBytes(encryptionKey);
    ICryptoTransform encryptor = aes.CreateDecryptor(aes.Key, aes.IV);

    using (MemoryStream stream = new MemoryStream())
    {
      using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
      {
        using (StreamWriter writer = new StreamWriter(encryptStream))
        {
          writer.Write(valueToEncrypt);
        }

        byte[] encryptedBytes = stream.ToArray();
        results = byteTransform.GetString(encryptedBytes);
      }
    }
  }

  return results;
}

当第3个using语句关闭时发生错误(即在writer.Write(valueToEncrypt)之后的行。如果我尝试移动第三个使用块内的两行以下,我最终得到一个空字符串(和错误仍然发生。。我直接从这个网站上提取这些代码(http://stackoverflow.com/questions/273452/using-aes-encryption-in-c-sharp),但它似乎不起作用。有没有人有任何想法吗?

1 个答案:

答案 0 :(得分:3)

是的,但如果您重读代码,我认为您也会这样做:

ICryptoTransform encryptor = aes.CreateDecryptor(aes.Key, aes.IV);

这是一个名为加密器的解密器......