2

我尝试对某些文本使用 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;
            }
        }
    }
}

怎么了?提前致谢。

4

2 回答 2

4

你的解密代码中有这个:

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

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

于 2012-11-10T09:01:09.140 回答
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);
        }
于 2012-11-10T09:06:20.903 回答