加密和解密c# Rijndael内存管理



我目前正在编写像WinRAR这样的小软件。当我加密或解密对应于我的文件的字节数组时,我有一个大的内存泄漏(或高RAM消耗),有时当我想加密一个500MB的文件时,它会抛出OutOfMemoryException

这是我的代码:

internal static class ResourceSecurity
{
    #region STATIC FIELDS
    private static readonly String PASSWORD_HASH = "ceýº–h­Þ6Ü+rdÚ‡AÃÎ^oð#Èh";
    private static readonly String SALT_KEY = "žÀÚÔceýº–h­•e:÷KÚ‡AÃÎ^oð#ÈhÀÍÄ";
    private static readonly String IV_KEY = "ª<±kéÞ6Ü+f¥Ÿ„’²";
    #endregion
    #region STATIC METHODS
    private static RijndaelManaged CreateAlgo()
    {
        Byte[] _keyBytes = new Rfc2898DeriveBytes(PASSWORD_HASH, Encoding.ASCII.GetBytes(SALT_KEY)).GetBytes(256 / 8);
        RijndaelManaged _rijndael = new RijndaelManaged();
        _rijndael.Mode = CipherMode.CBC;
        _rijndael.Padding = PaddingMode.Zeros;
        _rijndael.Key = _keyBytes;
        _rijndael.IV = Encoding.ASCII.GetBytes(IV_KEY);
        return _rijndael;
    }

    private static Byte[] ConvertBuffer(Byte[] buffer, ICryptoTransform transformation)
    {
        Byte[] _newBuffer = null;
        MemoryStream _memoryStream = new MemoryStream();
        using (CryptoStream _crypto = new CryptoStream(_memoryStream, transformation, CryptoStreamMode.Write))
        {
            _crypto.Write(buffer, 0, buffer.Length);
            _newBuffer = _memoryStream.ToArray();
        }
        return _newBuffer;
    }
    internal static Byte[] Encrypt(Byte[] bufferToEncrypt)
    {
        return ConvertBuffer(bufferToEncrypt, CreateAlgo().CreateEncryptor());
    }
    internal static Byte[] Decrypt(Byte[] encryptedBuffer)
    {
        return ConvertBuffer(encryptedBuffer, CreateAlgo().CreateDecryptor());
    }
    #endregion
}

谢谢!

很可能您的进程在x86模式下运行,遇到了较低的内存限制。有关Windows进程的内存限制,请参阅此处。确保以x64格式运行进程作为解决方案。作为一个明确的解决方案,尽量不要在内存中保存那么多的数据。仅在您的示例中,明文和密码数据增加到1GB。尝试在针对非内存流(可能是文件流或网络流?)的输入流上执行加密。这样,您的应用程序不会给系统内存带来太多压力,并且可以更好地扩展。

相关内容

  • 没有找到相关文章

最新更新