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 :
- As it’s not encrypted , anyone with access to swap file or process memory is able to read unencrypted data easily.
- When modifying this class , old value is not removed from the memory , so both old and new versions are kept in memory.
- 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 :
public class SecureStringExample
public void ImplementSecureString()
SecureString secureString = new SecureString();
///Implementing AppendChar method to add
///characters to SecureString Object.
///Implementing InsertAt method to insert a character
///at specified index.
///Implementing SetAt method to replace character
///at specified index with new character.
///Implementing RemoveAt method to
///remove a character at specified index.
///Reading SecureStrinng content.
IntPtr pointer = Marshal.SecureStringToBSTR(secureString);
///Clearing SecureString Object.
///Disposing SecureString Object.
///Free BSTR pointer allocated using