title: How to secure a connection string in memory after loading it from app.config in a Winforms application
body: <p>I have a legacy application that uses a SQL Server authentication connection string to connect to a local or intranet based SQL Server instance. It currently uses the System.Configuration.ConfigurationManager to get the connection string from the app.config file. However, once that connection string is read from the app.config file, its value is loaded into memory and can be exposed using a tool like Process Hacker to view the applications memory. I currently have module with a method that returns the value of the connection string stored in a SecureString object. The connection string value is loaded into memory on the creation of the ConnectionStringSection Object. The app.config connection string xml is encrypted via instructions given from the microsoft documentation </p>
  
  <p><a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings-and-configuration-files" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings-and-configuration-files</a></p>
  
  <p>I understand that it is best practice to use Integrated Security, in this case our connection must use SQL Server Authentication. Is there a way eliminate or minimize the exposure of the connection string in the applications memory?</p>
  
  <pre><code>Public Function GetConnectionString() As SecureString
      Dim fileMap As ExeConfigurationFileMap = New ExeConfigurationFileMap
      fileMap.ExeConfigFilename = Environment.CurrentDirectory + "\app.config"
      Dim config As Configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
      Dim section As ConnectionStringsSection = TryCast(config.GetSection("connectionStrings"), ConnectionStringsSection)
  
      Dim secureString As New SecureString
  
      For Each character As Char In section.ConnectionStrings("ConString").ConnectionString.ToCharArray
          secureString.AppendChar(character)
      Next
  
      Return secureString
  End Function
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/oQOcD.png" rel="nofollow noreferrer">memory dump after first call to get connection string</a></p>