Search code examples
c#sql-serversecuritysecurestring

Convert string from database to SecureString


How I can limit (memory) exposure of a unencrypted string stored in a database when transfered from the database to a local SecureString variable?

Is the string after it arrives from the database, but before it gets converted, just as vulnerable as just moving it to a string variable and then convert it? And is there some other way to go about this?

Here is code getting data from MSSQL database where it is stored as unencrypted varchar:

SecureString str = ((string)command.Parameters["@ssn"].Value).ConvertToSecureString();

Where ConvertToSecureString() is this extension method:

public static SecureString ConvertToSecureString(this string str)
{
   var secureStr = new SecureString();
   if (str.Length > 0)
   {
       foreach (var c in str.ToCharArray()) secureStr.AppendChar(c);
   }
   secureStr.MakeReadOnly();
   return secureStr;
}

I'm trying to avert the expose of data to some memory profiling virus/hacks/dumps etc. E.g. Walmart memory hack and just be as secure as possible overall.


Solution

  • If the strings are stored unencrypted in the database, they are vulnerable to theft anyway.

    And if they are read in memory using a DataReader, they will also be in memory unencrypted even if only a short while while you loop through the reader.

    My advice would be, if the strings are so sensitive, to store them encrypted in the DB, read the encrypted strings into SecureString using a DataReader, and then decrypt them as necessary; this will not expose them in-memory.