Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 805769
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T00:08:01+00:00 2026-05-15T00:08:01+00:00

Can anyone please identify is there any possible memory leaks in following code. I

  • 0

Can anyone please identify is there any possible memory leaks in following code. I have tried with .Net Memory Profiler and it says “CreateEncryptor” and some other functions are leaving unmanaged memory leaks as I have confirmed this using Performance Monitors.

but there are already dispose, clear, close calls are placed wherever possible please advise me accordingly. its a been urgent.

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;
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T00:08:02+00:00Added an answer on May 15, 2026 at 12:08 am

    Update: After some more investigation I logged this as a bug on Microsoft connect. They have acknowledged the bug and have created a hotfix. (Obviously, this is a hotfix so the usual disclaimers apply. If you can, upgrading to .net 4.0 would probably be the preferred solution)


    It seems that this code leaks in .net 3.5, but is works fine in .net 4.0.

    I started in .net 4.0 and copied your code into a quick test app and called it 1,000,000 times, and the memory usage stayed constant at 22.4mb the whole time. I also tracked the GC heap sizes and handle counts, and they all stayed constant. As far as I can tell that code isn’t leaking.

    I then rebuilt the app under .net 3.5 and re-run the test and I got the exact leak you are describing. It started at around 24mb, and by the time it had made 100k calls, memory usage had doubled to over 50mb. Interestingly, it seemed to be the Gen2 heap that was increasing which suggests it is a managed memory leak rather than unmanaged handles/memory.

    If possibly I would suggest you try to switch to .net 4.0.

    My complete code:

    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;
            }
    
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can anyone please advice how can I have value of i in the following
Can anyone please help me on the following: I have created a SQL Server
Can anyone please suggest me a good .net code coverage plugin for Visual Studio
Can anyone please help me in writing rspec for the following method The write_entry_to_xml
Can anyone please let me know if it is possible to handle events like
Can anyone please help me to identify the exact are of problem. Is it
Can any one please help me how to identify a given a website is
Can anyone please point out the cause of this error in the C# code
Can anyone please help me with the code as how to read multiple lines
Can anyone please help me read this shorthand code? datain = $this.hasClass('up')?+1:($this.hasClass('down')?-1:null); sorry for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.