代码之家  ›  专栏  ›  技术社区  ›  Mubashar

AES加密方法中的内存泄漏问题

  •  5
  • Mubashar  · 技术社区  · 16 年前

    请任何人确认以下代码中是否存在任何可能的内存泄漏。我尝试过使用.NET内存分析器,它会说“createncryptor”,而其他一些函数会留下未管理的内存泄漏,因为我已经使用性能监视器确认了这一点。

    但已经有处理,清除,关闭电话尽可能地放置,请相应地通知我。很紧急。

    public static string Encrypt(string plainText, string key)
        {
            //Set up the encryption objects
            byte[] encryptedBytes = null;
            using (AesCryptoServiceProvider acsp = GetProvider(Encoding.UTF8.GetBytes(key)))
            {
                byte[] sourceBytes = Encoding.UTF8.GetBytes(plainText);
                using (ICryptoTransform ictE = acsp.CreateEncryptor())
                {
                    //Set up stream to contain the encryption
                    using (MemoryStream msS = new MemoryStream())
                    {
                        //Perform the encrpytion, storing output into the stream
                        using (CryptoStream csS = new CryptoStream(msS, ictE, CryptoStreamMode.Write))
                        {
                            csS.Write(sourceBytes, 0, sourceBytes.Length);
                            csS.FlushFinalBlock();
    
                            //sourceBytes are now encrypted as an array of secure bytes
                            encryptedBytes = msS.ToArray(); //.ToArray() is important, don't mess with the buffer
    
                            csS.Close();
                        }
    
                        msS.Close();
                    }
                }
    
                acsp.Clear();
            }
    
            //return the encrypted bytes as a BASE64 encoded string
            return Convert.ToBase64String(encryptedBytes);
        }
        private static AesCryptoServiceProvider GetProvider(byte[] key)
        {
            AesCryptoServiceProvider result = new AesCryptoServiceProvider();
            result.BlockSize = 128;
            result.KeySize = 256;
            result.Mode = CipherMode.CBC;
            result.Padding = PaddingMode.PKCS7;
    
            result.GenerateIV();
            result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    
            byte[] RealKey = GetKey(key, result);
            result.Key = RealKey;
            // result.IV = RealKey;
            return result;
        }
    
        private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
        {
            byte[] kRaw = suggestedKey;
            List<byte> kList = new List<byte>();
    
            for (int i = 0; i < p.LegalKeySizes[0].MaxSize; i += 8)
            {
                kList.Add(kRaw[(i / 8) % kRaw.Length]);
            }
            byte[] k = kList.ToArray();
            return k;
        }
    
    2 回复  |  直到 16 年前
        1
  •  8
  •   Simon P Stevens    16 年前

    更新 :经过更多的调查,我将此作为Bug登录到 Microsoft connect . 他们已经确认了这个错误,并创建了一个 hotfix . (显然,这是一个修补程序,因此通常的免责声明适用。如果可以,升级到.NET 4.0可能是首选的解决方案)


    此代码似乎在.NET 3.5中泄漏,但在.NET 4.0中工作正常。

    我从.NET 4.0开始,将您的代码复制到一个快速测试应用程序中,并对其进行了1000000次调用,并且内存使用始终保持在22.4MB。我还跟踪了GC堆的大小和句柄计数,它们都保持不变。据我所知,代码没有泄漏。

    然后我在.NET 3.5下重新构建了这个应用程序,并重新运行测试,得到了您描述的确切泄漏。它的启动容量大约为24MB,到它发出100K调用时,内存使用量翻了一番,达到了50MB以上。有趣的是,似乎是gen2堆正在增加,这表明它是托管内存泄漏,而不是非托管句柄/内存。

    如果可能的话,我建议您尝试切换到.NET 4.0。

    我的完整代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Security.Cryptography;
    using System.IO;
    
    namespace ConsoleApplication5
    {
        class Program
        {
            static void Main(string[] args)
            {
                String encryptedString;
    
    
                for (int j = 0; j < 1000; j++)
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        encryptedString = Encrypt(String.Format("test string {0} {1}", j, i), "key");
                    }
                    Console.WriteLine("j = {0}", j);
                }
    
                Console.WriteLine("Finished");
                Console.ReadLine();
    
            }
    
            public static string Encrypt(string plainText, string key)
            {
                //Set up the encryption objects
                byte[] encryptedBytes = null;
                using (AesCryptoServiceProvider acsp = GetProvider(Encoding.UTF8.GetBytes(key)))
                {
                    byte[] sourceBytes = Encoding.UTF8.GetBytes(plainText);
                    using (ICryptoTransform ictE = acsp.CreateEncryptor())
                    {
                        //Set up stream to contain the encryption
                        using (MemoryStream msS = new MemoryStream())
                        {
                            //Perform the encrpytion, storing output into the stream
                            using (CryptoStream csS = new CryptoStream(msS, ictE, CryptoStreamMode.Write))
                            {
                                csS.Write(sourceBytes, 0, sourceBytes.Length);
                                csS.FlushFinalBlock();
    
                                //sourceBytes are now encrypted as an array of secure bytes
                                encryptedBytes = msS.ToArray(); //.ToArray() is important, don't mess with the buffer
    
                                csS.Close();
                            }
    
                            msS.Close();
                        }
                    }
    
                    acsp.Clear();
                }
    
                //return the encrypted bytes as a BASE64 encoded string
                return Convert.ToBase64String(encryptedBytes);
            }
            private static AesCryptoServiceProvider GetProvider(byte[] key)
            {
                AesCryptoServiceProvider result = new AesCryptoServiceProvider();
                result.BlockSize = 128;
                result.KeySize = 256;
                result.Mode = CipherMode.CBC;
                result.Padding = PaddingMode.PKCS7;
    
                result.GenerateIV();
                result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    
                byte[] RealKey = GetKey(key, result);
                result.Key = RealKey;
                // result.IV = RealKey;
                return result;
            }
    
            private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
            {
                byte[] kRaw = suggestedKey;
                List<byte> kList = new List<byte>();
    
                for (int i = 0; i < p.LegalKeySizes[0].MaxSize; i += 8)
                {
                    kList.Add(kRaw[(i / 8) % kRaw.Length]);
                }
                byte[] k = kList.ToArray();
                return k;
            }
    
        }
    }
    
        2
  •  0
  •   Jonathan Michaels    16 年前

    不是真的试图劫持线程,但是您的加密和这个线程的主要区别是什么?

    
    /// 
            /// Encrypts a string
            /// 
            /// Text to be encrypted
            /// Password to encrypt with
            /// Salt to encrypt with
            /// Can be either SHA1 or MD5
            /// Number of iterations to do
            /// Needs to be 16 ASCII characters long
            /// Can be 128, 192, or 256
            /// An encrypted string
            public static string Encrypt(string PlainText, string Password,
                string Salt, string HashAlgorithm,
                int PasswordIterations, string InitialVector,
                int KeySize)
            {
                try
                {
                    if (string.IsNullOrEmpty(PlainText))
                        return "";
                    byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
                    byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
                    byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
                    PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
                    byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
                    RijndaelManaged SymmetricKey = new RijndaelManaged();
                    SymmetricKey.Mode = CipherMode.CBC;
                    byte[] CipherTextBytes = null;
                    using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
                    {
                        using (MemoryStream MemStream = new MemoryStream())
                        {
                            using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                            {
                                CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                                CryptoStream.FlushFinalBlock();
                                CipherTextBytes = MemStream.ToArray();
                                MemStream.Close();
                                CryptoStream.Close();
    
                                CryptoStream.Dispose();
                                MemStream.Dispose();
                            }
                        }
                        Encryptor.Dispose();
                    }
                    SymmetricKey.Clear();
                    return Convert.ToBase64String(CipherTextBytes);
                }
                catch { throw; }
            }
    

    我在3.5下运行这个,它没有超过22MB。我的加密技术有点薄弱,但我只是想知道为什么一个比另一个更好,或者是否更好。似乎有很多方法可以做同样的事情。