首页 > 解决方案 > C# AES 加密内存使用情况

问题描述

我对 RSA 和 AES 加密算法的混合实现的内存使用有疑问。我编写了一个简单的控制台程序(.net core 和 C# 8.0 beta),它生成一个随机证书并加密/解密一个文件。执行时间似乎很好。

用 1000 次迭代测量的时间

问题似乎是内存使用情况。对于 230 KB 的文件,程序使用约 20 MB。对于 28 MB 的文件,该程序使用 ~490 MB。92 MB 文件最高可达 2 GB,并使用约 1.8 GB 内存。

这些数字是否被视为“正常”使用,还是我的代码有问题?

这是我对 AES 加密的实现

static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
    // Salt not modified for sample
    byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    using MemoryStream ms = new MemoryStream();
    using RijndaelManaged AES = new RijndaelManaged();
    AES.KeySize = 256;
    AES.BlockSize = 128;

    Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
    AES.Key = key.GetBytes(AES.KeySize / 8);
    AES.IV = key.GetBytes(AES.BlockSize / 8);

    AES.Mode = CipherMode.CBC;
    using ICryptoTransform csTf = AES.CreateEncryptor();
    using CryptoStream cs = new CryptoStream(ms, csTf, CryptoStreamMode.Write);
    cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
    cs.Close();
    return ms.ToArray();
}

static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
    // Salt not modified for sample
    byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    using MemoryStream ms = new MemoryStream();
    using RijndaelManaged AES = new RijndaelManaged();
    AES.KeySize = 256;
    AES.BlockSize = 128;

    Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
    AES.Key = key.GetBytes(AES.KeySize / 8);
    AES.IV = key.GetBytes(AES.BlockSize / 8);

    AES.Mode = CipherMode.CBC;

    using ICryptoTransform csTf = AES.CreateDecryptor();
    using CryptoStream cs = new CryptoStream(ms, csTf, CryptoStreamMode.Write);
    cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
    cs.Close();
    return ms.ToArray();
}

static string EncryptString(string text, string password)
{
    byte[] baEncrypted = new byte[GetSaltLength() + Encoding.UTF8.GetByteCount(text)];

    Array.Copy(GetRandomBytes(), 0, baEncrypted, 0, GetSaltLength());
    Array.Copy(Encoding.UTF8.GetBytes(text), 0, baEncrypted, GetSaltLength(), Encoding.UTF8.GetByteCount(text));

    return Convert.ToBase64String(AES_Encrypt(baEncrypted, SHA256Managed.Create().ComputeHash(Encoding.UTF8.GetBytes(password))));
}

static string DecryptString(string text, string password)
{
    byte[] baDecrypted = AES_Decrypt(Convert.FromBase64String(text), SHA256Managed.Create().ComputeHash(Encoding.UTF8.GetBytes(password)));

    byte[] baResult = new byte[baDecrypted.Length - GetSaltLength()];

    Array.Copy(baDecrypted, GetSaltLength(), baResult, 0, baResult.Length);

    return Encoding.UTF8.GetString(baResult);
}

static byte[] GetRandomBytes()
{
    byte[] ba = new byte[GetSaltLength()];
    RNGCryptoServiceProvider.Create().GetBytes(ba);
    return ba;
}

static int GetSaltLength()
{
    return 8;
}

调用方法并迭代调用

static void Main(string[] args)
{
    CertificateRequest certificateRequest = new CertificateRequest("cn=random_cert", RSA.Create(4096), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

    X509Certificate2 certificate = certificateRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(2));

    String data = File.ReadAllText(@"PATH TO FILE");

    Int64 AESenc, RSAenc, AESdec, RSAdec;

    List<Int64> aesEncTime = new List<Int64>();
    List<Int64> aesDecTime = new List<Int64>();
    List<Int64> rsaEncTime = new List<Int64>();
    List<Int64> rsaDecTime = new List<Int64>();

    for (int i = 0; i < 1000; i++)
    {
        encryptData(ref certificate, ref data, out AESenc, out RSAenc, out AESdec, out RSAdec);
        aesEncTime.Add(AESenc);
        aesDecTime.Add(AESdec);
        rsaEncTime.Add(RSAenc);
        rsaDecTime.Add(RSAdec);

        Console.Clear();

        Console.WriteLine($"data.Length:\t{data.Length:n0} b");
        Console.WriteLine($"UTF8 Bytes:\t{Encoding.UTF8.GetByteCount(data):n0} b");

        Console.WriteLine($"Loop:\t\t{i + 1}");

        Console.WriteLine("---------------------------------------------------------");
        Console.WriteLine($"|AES Enc|Avg: {aesEncTime.Average():0000.00} ms|Max: {aesEncTime.Max():0000.00} ms|Min: {aesEncTime.Min():0000.00} ms|");
        Console.WriteLine("|-------|---------------|---------------|---------------|");
        Console.WriteLine($"|AES Dec|Avg: {aesDecTime.Average():0000.00} ms|Max: {aesDecTime.Max():0000.00} ms|Min: {aesDecTime.Min():0000.00} ms|");
        Console.WriteLine("|-------|---------------|---------------|---------------|");
        Console.WriteLine($"|RSA Enc|Avg: {rsaEncTime.Average():0000.00} ms|Max: {rsaEncTime.Max():0000.00} ms|Min: {rsaEncTime.Min():0000.00} ms|");
        Console.WriteLine("|-------|---------------|---------------|---------------|");
        Console.WriteLine($"|RSA Dec|Avg: {rsaDecTime.Average():0000.00} ms|Max: {rsaDecTime.Max():0000.00} ms|Min: {rsaDecTime.Min():0000.00} ms|");
        Console.WriteLine("---------------------------------------------------------");
        // Moving GC.Collect outside of the for-loop increases the memory usage
        GC.Collect();
    }

    Console.ReadKey();
}

static void encryptData(ref X509Certificate2 certificate, ref String data, out Int64 AESenc, out Int64 RSAenc, out Int64 AESdec, out Int64 RSAdec)
{
    Stopwatch stopwatch = new Stopwatch();

    String hash = getSha256(ref data);

    stopwatch.Start();

    String encryptedData = EncryptString(data, hash);

    stopwatch.Stop();

    AESenc = stopwatch.ElapsedMilliseconds;

    stopwatch.Restart();

    String encryptedKey = Convert.ToBase64String(certificate.GetRSAPublicKey().Encrypt(Encoding.UTF8.GetBytes(hash), RSAEncryptionPadding.Pkcs1));

    stopwatch.Stop();

    RSAenc = stopwatch.ElapsedMilliseconds;

    stopwatch.Restart();

    String decryptedKey = Encoding.UTF8.GetString(certificate.GetRSAPrivateKey().Decrypt(Convert.FromBase64String(encryptedKey), RSAEncryptionPadding.Pkcs1));

    stopwatch.Stop();

    RSAdec = stopwatch.ElapsedMilliseconds;

    stopwatch.Restart();

    String decryptedData = DecryptString(encryptedData, decryptedKey);

    stopwatch.Stop();

    encryptedData = null;
    decryptedData = null;

    AESdec = stopwatch.ElapsedMilliseconds;
}

static String getSha256(ref String value)
{
    String hash = String.Empty;
    Byte[] data = Encoding.UTF8.GetBytes(value);
    using SHA256Managed sHA256Managed = new SHA256Managed();
    Byte[] hashData = sHA256Managed.ComputeHash(data);
    foreach (Byte item in hashData)
    {
        hash += $"{item:x2}";
    }
    return hash;
}

该代码可以在没有任何外部资源(不包括要加密的文件)的情况下执行。

标签: c#encryptionmemory-leaks.net-core

解决方案


您可以通过从 a 读取数据将数据简单地流式传输到固定大小的缓冲区FileStream,然后使用 aCryptoStream在文件中创建密文,方法是放入 aFileStream而不是 aMemoryStream输出。

要解密,CryptoStream在a前面创建aFileStream用于读取,然后将缓冲区中的数据写入aFileStream用于写入。

如果你有一个用于明文或密文的字节数组,或者如果你使用的是 aMemoryStream那么你做错了。


推荐阅读