C# AES 加密内存使用

标签 c# encryption memory-leaks .net-core

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

用 1000 次迭代测量的时间

  • 230 KB 的文件大约需要 2 毫秒
  • 28 MB 文件大约需要 150 毫秒
  • 92 MB 的文件大约需要 500 毫秒

问题似乎出在内存使用上。对于 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;
}

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

最佳答案

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

解密时,在一个FileStream前面创建一个CryptoStream进行读取,然后将缓冲区中的数据写入一个FileStream进行读取写作。

如果您有明文或密文的字节数组,或者您使用的是 MemoryStream,那么您就错了。

关于C# AES 加密内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743900/

相关文章:

c# - Gridview Format Field as Phone Number 但有些结果是 4 digit extension,如何处理?

c# - 当用户单击任务栏上正在运行的应用程序图标时发生的事件是什么?

php - 使用加密检查数据库

javascript - 使用 CryptoJS 加密,使用 Ruby/AES 解密

python - ipython 和引用计数

c# - 在查询中使用当前登录的用户

c - 解密时在 AES_encrypt 函数中指定输入字符串长度

c - 我的 C 程序中存在内存泄漏

asynchronous - MailboxProcessor.Dispose 不会使对象 GC 可收集

c# - 无法使用 C# 将带 [] 的索引应用于类型为 'System.Array' 的表达式