0

我正在尝试使此 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;
                }
            }
        }
    };


}
4

1 回答 1

3

三个选项,它们都做同样的事情,

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

或者,移出cipher = msEncrypt.ToArray(); return cipertext;您正在写入加密流的 using 块。

请注意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;
}
于 2014-12-06T20:12:03.157 回答