C#AES加密内存使用情况

时间:2019-04-18 10:15:39

标签: 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;
}

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

1 个答案:

答案 0 :(得分:0)

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

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

如果您有用于明文或密文的字节数组,或者您使用的是MemoryStream,则说明这样做是错误的。