使用 System.Security.Cryptography 的空数组或空数组

Empty or null array using System.Security.Cryptography

我正在尝试使用以下代码在 C# 中使用 AES 加密方法:

public static byte[] encryptData(string plaintext)
    {
        Aes myAes = Aes.Create();
        byte[] encrypted = EncryptStringToBytes_Aes(plaintext,myAes.Key, myAes.IV);
        return encrypted;
    }

static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;
        Aes aesAlg = Aes.Create();
        aesAlg.Key = Key;
        aesAlg.Key = IV;
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        MemoryStream msEncrypt = new MemoryStream();
        CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
        StreamWriter swEncrypt = new StreamWriter(csEncrypt);
        swEncrypt.Write(plainText);
        encrypted = msEncrypt.ToArray();
        return encrypted;
    }

并像这样调用函数:

byte[] encrypt = Security.encryptData("Hi, how are you?");

但是返回的字节数组总是空的。

我正在尝试使用它来加密我的 app.config 文件中的密码等值。

将流放入 using 或使用 Close 方法处理它们。

static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
    // your code
    byte[]  plainBytes = Encoding.UTF8.GetBytes(plainText);
    byte[] encrypted;
    Aes aesAlg = Aes.Create();
    aesAlg.Key = Key;
    aesAlg.Key = IV;
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
    using(MemoryStream ms = new MemoryStream())
    {
        using(CryptoStream csEncrypt = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            csEncrypt.Write(plainBytes,0, plainBytes.Length );
            csEncrypt.FlushFinalBlock();
            return msEncrypt.ToArray();
        }
    }
}