C# Programming > Data

C# SecureString

Secure .NET Strings

C#.NET has the common string object which can be used in many useful string functions. However when working with sensitive data, the C# SecureString class is more appropriate.

SecureString is one of the lesser known classes of the .NET Framework, but it is immensely useful.

SecureString

The SecureString .NET class is located under the System.Security namespace. A string stored in a SecureString object is kept encrypted in memory. More importantly, a SecureString object is pinned down in memory. This prevents the .NET garbage collector from creating copies of the object all over memory, keeping the data in a single place. With a regular string, the garbage collector will move the object and create various copies along the way. The various copies makes the data easier to extract from memory. When working with sensitive information, the less places it is stored, the more secure.

Creating a SecureString is not as simple as a regular string object. A SecureString is created one character at a time. The class is designed this way to encourage the data to be captured directly as the user types it into an application. However some applications will need to copy an existing string into a SecureString, at which point adding a character at a time is sufficient.

SecureString secureStr = new SecureString();
for (int i = 0; i < someString.Length; i++)
{
    secureStr.AppendChar(someString[i]);
}
secureStr.MakeReadOnly();

Notice at the end that the MakeReadOnly command prevents the SecureString to be edited any further.

Reading a SecureString is more complicated. There is no simple ToString method, which is also intended to keep the data secure. To read the data C# developers must access the data in memory directly. Luckily the .NET Framework makes it fairly simple:

IntPtr stringPointer = Marshal.SecureStringToBSTR(secureStringObj);
string normalString = Marshal.PtrToStringBSTR(stringPointer);
Marshal.ZeroFreeBSTR(stringPointer);

Purpose of SecureString

You might have noticed that a C# SecureString can only be read by converting it back into a string. So what is the point? The point is to try to minimize the number of times sensitive data is exposed in the application, even just in memory. To further minimize the data exposure, it is good pratice to have the .NET garbage collector pin down the temporary string version of the SecureString. This makes it easier to clear the sensitive data from memory without leaving traces behind.

Back to C# Article List