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

时间:2016-05-17 02:18:58

标签: c# cryptography encryption-symmetric

我尝试使用此代码在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文件中的密码等值。

1 个答案:

答案 0 :(得分:1)

将您的流放入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();
        }
    }
}