AES encryptor not working

和自甴很熟 提交于 2019-12-02 19:17:52

问题


I am attempting to get this AES sample code working. However I am not getting anything returned to my cipherText variable. I am not getting errors, just nothing returned. What am I doing wrong here?

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:


Three options, all of which do the same thing,

Either call csEncrypt.Close() or use csEncrypt.FlushFinalBlock() to flush the encrypted data to the memory stream - call it before cipertext = msEncrypt.ToArray().

Or, move cipher = msEncrypt.ToArray(); return cipertext; outside the using block where you're writing to the crypto stream.

Note csEncrypt.Flush() which might be the first guess does nothing..

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;
}


来源:https://stackoverflow.com/questions/27334981/aes-encryptor-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!