AES加密器无法正常工作

时间:2014-12-06 18:29:58

标签: c# encryption aes aescryptoserviceprovider

我试图让这个AES示例代码正常工作。但是我没有得到任何返回我的cipherText变量的东西。我没有得到错误,只是没有回复。我在这里做错了什么?

public byte[] key { get; set; }
public byte[] IV { get; set; }
public byte[] ciphertext { get; set; }
public string plainText { get; set; }


public byte[] Encrypt(string InputPlaintext)
{
    InputPlaintext = "attack at dawn";
    using (AesCryptoServiceProvider AESEncryptor = new AesCryptoServiceProvider())
    {

        ////using the AesCryptoServiceProvider to generate the IV and Key

        key = AESEncryptor.Key;

        IV = AESEncryptor.IV;

        ICryptoTransform encryptor = AESEncryptor.CreateEncryptor(key, IV);

        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {

                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(InputPlaintext);
                    ciphertext = msEncrypt.ToArray();
                    return ciphertext;
                }
            }
        }
    };


}

1 个答案:

答案 0 :(得分:3)

三个选项,所有这些选项都做同样的事情,

调用csEncrypt.Close()或使用csEncrypt.FlushFinalBlock()将加密数据刷新到内存流 - 在cipertext = msEncrypt.ToArray()之前调用它。

或者,将cipher = msEncrypt.ToArray(); return cipertext;移到您正在写入加密流的使用区之外。

注意csEncrypt.Flush()这可能是第一个猜测什么都没做..

http://reflector.webtropy.com/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/clr/src/BCL/System/Security/Cryptography/CryptoStream@cs/1/CryptoStream@cs

public override void Flush() 
{
     return;
}