
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
994
|
Chapter 17: Security
17.15 Protecting String Data with Secure Strings
Problem
You need to store sensitive information, such as a Social Security number, in a string.
However, you do not want prying eyes to be able to view this data in memory.
Solution
Use the SecureString object. To place text from a stream object within a
SecureString object, use the following method:
public static SecureString CreateSecureString(StreamReader secretStream)
{
SecureString secretStr = new SecureString( );
char buf;
while (secretStream.Peek( ) >= 0)
{
buf = (char)secretStream.Read( );
secretStr.AppendChar(buf);
}
// Make the secretStr object read-only.
secretStr.MakeReadOnly( );
return (secretStr);
}
To pull the text out of a SecureString object, use the following method:
public static void ReadSecureString(SecureString secretStr)
{
// In order to read back the string, you need to use some special methods.
IntPtr secretStrPtr = Marshal.SecureStringToBSTR(secretStr);
string nonSecureStr = Marshal.PtrToStringBSTR(secretStrPtr);
// Use the unprotected string.
Console.WriteLine("nonSecureStr = {0}", nonSecureStr);
Marshal.ZeroFreeBSTR(secretStrPtr);
if (!secretStr.IsReadOnly( ))
{
secretStr.Clear( );
}
}
Discussion
A SecureString object is designed specifically to contain string data that you want to