SecureString

I am trying to compile a list of new and useful security related features in whidbey. i you want to contribute – feel free so :)

The first thing i want to mention is the addition of the new SecureString class.

Strings in .NET:

  • are not pinned – the gc can move them around in memory leaving several copies in memory
  • while not pinned, can be swapped out to a pagefile
  • are not mutable – so whenever you change them you will have the old and new version in memory
  • cannot be cleared from memory
  • are not encrypted

SecureString will provide all these features – read more about that on this highly recommended blog.

Actually you can have this behaviour in .NET 1.1, too. For everything mentioned above (besides encryption) you can use thes ErasableData class (from Michael HowardWriting Secure Code 2). Encryption can be established through the unmanaged CryptProtectMemory API.

public class ErasableData : IDisposable {

  private byte[] _rbSecret;
  private GCHandle _ph;
  public ErasableData(int size)
  {
    _rbSecret = new byte[size];
  }
  public byte[] Data {
    set {
      _ph = GCHandle.Alloc(_rbSecret, GCHandleType.Pinned);
      byte[] Data = value;
      Array.Copy(Data, _rbSecret, Data.Length);
    }
    get { return _rbSecret; }
  }
  public void Dispose() {

    Array.Clear(_rbSecret, 0, _rbSecret.Length);
    _ph.Free();

  }
}
 
and use it like:
 

using (ErasableData key = new ErasableData(16))
{
  key.Data = getPassword();
  //Do Encryption
}

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s