AES加密获得不正确的结果

时间:2012-11-10 08:53:28

标签: c# encryption aes

我尝试对某些文本使用AES加密,但解密的文本与原始文本不同。

  • 原文:abcd
  • 解密文字:?9T?o??G???x;*

这是我的代码:

public static void Main(string[] args)
{
    byte[] original = { 97, 98, 99, 100 }; //"abcd"
    byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    byte[] encrypt = Encrypt(original, key, iv);
    byte[] decrypt = Decrypt(encrypt, key, iv);
    Console.WriteLine(Encoding.UTF8.GetString(original));
    Console.WriteLine(Encoding.UTF8.GetString(decrypt));
    Console.ReadKey();
}

public static byte[] Encrypt(byte[] original, byte[] key, byte[] iv)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var aes = new AesManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC })
        {
            using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cryptoStream.Write(original, 0, original.Length);
            }
        }
        return memoryStream.ToArray();
    }
}

public static byte[] Decrypt(byte[] encrypt, byte[] key, byte[] iv)
{
    using (var memoryStream = new MemoryStream(encrypt))
    {
        using (var aes = new AesManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC })
        {
            using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Read))
            {
                byte[] decrypt = new byte[encrypt.Length];
                cryptoStream.Read(decrypt, 0, decrypt.Length);
                return decrypt;
            }
        }
    }
}

怎么了?提前谢谢。

2 个答案:

答案 0 :(得分:4)

你的解密代码中已经有了这个:

using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(),
                                           CryptoStreamMode.Read))

将其更改为调用aes.CreateDecryptor(),它可以正常工作。

答案 1 :(得分:0)

您的解密方法有问题,请使用以下内容:

public string Decrypt(byte[] EncryptedValue)
        {
            #region Write the encrypted value to the decryption stream
            MemoryStream encryptedStream = new MemoryStream();
            CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
            decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
            decryptStream.FlushFinalBlock();
            #endregion

            #region Read the decrypted value from the stream.
            encryptedStream.Position = 0;
            Byte[] decryptedBytes = new Byte[encryptedStream.Length];
            encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
            encryptedStream.Close();
            #endregion
            return UTFEncoder.GetString(decryptedBytes);
        }