How to protect sensitive data in memory
Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen
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.
static void Main(string args)
System.Security.SecureString secstr = new System.Security.SecureString();
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.