加密和解密错误

时间:2014-12-09 17:07:23

标签: c# encryption

我有一个相当简单的加密和解密代码。但是,当我加密然后解密时,输出不是我最初输入的。

这是加密:

static byte[] Encrypt(SymmetricAlgorithm aesAlg, string plainText)
    {
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(plainText);
                }
                return msEncrypt.ToArray();
            }
        }
    }

解密:

static string Decrypt(SymmetricAlgorithm aesAlg, byte[] cipherText)
    {
        ICryptoTransform decryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        using (MemoryStream msDecrypt = new MemoryStream(cipherText))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {
                    return srDecrypt.ReadToEnd();
                }
            }
        }
    }

主:

public static void Main()
    {
        string original = "My secret data!";

        using (SymmetricAlgorithm symmetricAlgorithm = new AesManaged())
        {
            byte[] encrypted = Encrypt(symmetricAlgorithm, original);
            string roundtrip = Decrypt(symmetricAlgorithm, encrypted);

            Console.WriteLine("Original: {0}", original);
            Console.WriteLine("RoundTrip: {0}", roundtrip);
        }
    }

输出应该是:

Original: My secret data!
RoundTrip: My secret data!

然而,它出现了:

Original: My secret data!
RoundTrip: ">�����6dB&JD䮦�L�ܹ�SKo\v*.�"

或类似的搞笑。

我在互联网上找不到任何有用的东西。非常感谢任何建议。

2 个答案:

答案 0 :(得分:1)

问题是,在Decrypt方法中,您创建了另一个加密器,而不是Decryptor

如果更改了行

aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

然后你会得到被删除的文本。

答案 1 :(得分:-1)

解密代码

static string Decrypt(SymmetricAlgorithm aesAlg, byte[] cipherText)
{
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

    using (MemoryStream msDecrypt = new MemoryStream(cipherText))
    {
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
            {
                return srDecrypt.ReadToEnd();
            }
        }
    }
}