Geeks With Blogs
Blog Moved to Blog Moved to
With many secure applications, we must be cognizant of the memory usage and the secure storage of our data.  In the C++ world, there have been functions specifically defined to secure memory, such as SecureZeroMemory iin Winbase.h. 
For example, we can use the SecureZeroMemory function to place zeros over the memory for a user name and password once we are finished with them.  Here is an example of how to do this:
Sometimes, we need the same level of control that C++ has to offer with memory management and security.  With .NET 2.0, the System.Security namespace offers the SecureString class.  As we note with the constructor, it takes either no parameters, or an unsafe char array pointer and the number of characters in the character array.  The latter constructor is more used for C++/CLI.  Below is an example of how that would be used:
wchar_t* pPassword = new wchar_t[8];
... // Fill out password info
SecureString^ securePassword = gcnew SecureString(pPassword, 8);
That's all well and good, but most of the time we need to work in the C# world.  So, the SecureString class provides us with the capability of capturing the secure information character by character.  This can be done is several fashions. 
One of the easiest of course is the Console.ReadKey method which reads the next key from the console.  This returns a ConsoleKeyInfo structure which contains the KeyChar property.  The KeyChar property has the character to append to the SecureString.  Below is a quick example of how to do this:
SecureString securePassword = new SecureString();
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while(keyInfo != ConsoleKey.Enter)
     keyInfo = Console.ReadKey(true);
As noted from other blogs, one of the classes that takes a SecureString is the ProcessStartInfo class in the System.Diagnostics namespace as a password.
For interop purposes, this value can be used by the Marshal class which supports the following methods:
*  SecureStringToBSTR
*  SecureStringToCoTaskMemAnsi
*  SecureStringToCoTaskMemUnicode
*  SecureStringToGlobalAllocAnsi
*  SecureStringToGlobalAllocUnicode
This can be used in unsafe code to pass SecureStrings as managed pointers to other classes as need be.  When you are done with the memory, call the Dispose method which zeros out the memory.  Using the using statement would be perfect in that regard.  Most of the time this class is not needed, but it's good to know that it is there and it does exist.
Posted on Tuesday, May 23, 2006 3:22 PM Microsoft , .NET , C# | Back to top

Comments on this post: .NET Code Access Security - SecureString

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Matthew Podwysocki | Powered by: