SecureString : Storing Sensitive Data

July 11, 2008

Hello ,

Today , I’m going to elaborate on a great feature called System.Security.SecureString class which was introduced in .Net Framework 2.0. This class provides you with a secure way to store┬ásensitive data and prevent them from being revealed by hackers. Implementing standard System.String class is not a secure way for keeping sensitive information and also swap file is in danger of being disclosed. Let’s take a look at some disadvantages of putting System.String class into work :

  1. As it’s not encrypted , anyone with access to swap file or process memory is able to read unencrypted data easily.
  2. When modifying this class , old value is not removed from the memory , so both old and new versions are kept in memory.
  3. There is not a certain way to dispose it from memory when finishing with it.

SecureString class uses DAPI to encrypt data. Information ecrypted in this way by CLR is only decrypted when accessing it and in contrast with standard System.String class , this class implements IDisposable interface so that it can be cleared out from memory and its allocated memory will be zeroed out when disposing it.

Now , let’s see an example :

using System.Security;
using System.Runtime.InteropServices;
using System;
using System.Windows.Forms;

namespace SecureStringProject
{
public class SecureStringExample
{
public void ImplementSecureString()
{
SecureString secureString = new SecureString();
///Implementing AppendChar method to add
///characters to SecureString Object.
secureString.AppendChar(‘A’);
secureString.AppendChar(‘C’);
secureString.AppendChar(‘G’);
secureString.AppendChar(‘E’);
secureString.AppendChar(‘F’);

///Implementing InsertAt method to insert a character
///at specified index.
secureString.InsertAt(1, ‘B’);

///Implementing SetAt method to replace character
///at specified index with new character.
secureString.SetAt(3, ‘D’);

///Implementing RemoveAt method to
///remove a character at specified index.
secureString.RemoveAt(5);

///Reading SecureStrinng content.
IntPtr pointer = Marshal.SecureStringToBSTR(secureString);
MessageBox.Show(Marshal.PtrToStringUni(pointer));

///Clearing SecureString Object.
secureString.Clear();

///Disposing SecureString Object.
secureString.Dispose();

///Free BSTR pointer allocated using
///SecureStringToBSTR method.
Marshal.ZeroFreeBSTR(pointer);
}
}
}

Advertisements