How to Protect Sensitive Data in Memory

- J.D. Meier, Carlos Farre, Jason Taylor, Prashant Bansode, Steve Gregersen, Madhu Sundararajan, Rob Boucher

To minimize the exposure of secrets in memory, consider the following measures:
  • Avoid creating multiple copies of the secret. Having multiple copies of the secret data increases your attack surface. Pass references to secret data instead of making copies of the data. Also realize that if you store secrets in immutable objects such as System.String, after each object manipulation, a new copy is created.
  • Keep the secret encrypted for as long as possible. Decrypt the data at the last possible moment before you need to use the secret.
  • Clean the clear text version of the secret as soon as you are done using it.

You can use SecureString method to implement the above measures. The value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.

The following C# code creates an instance of the SecureString class and stores a data value in it.
using System;
using System.Collections.Generic;
using System.Text;

namespace TestSecureString 
{
  class Program 
  {
	static void Main(string[] args) 
	{
	System.Security.SecureString secstr = new System.Security.SecureString();
	secstr.AppendChar('W');
	secstr.AppendChar('C');
	secstr.AppendChar('F');
	secstr.MakeReadOnly();
	Console.WriteLine(secstr);
	} 
  } 
}

An exception is thrown if you attempt to alter the data because the code locks the string value with the MakeReadOnly method once the final character has been added. So this string value may not be altered.

Additional Resources

Last edited Jun 13, 2008 at 8:30 PM by prashantbansode, version 1

Comments

No comments yet.