December 2007
Intermediate to advanced
896 pages
19h 57m
English
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.
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();
}
}A SecureString object is designed specifically to contain string data that you want to keep secret. Some of the data you may want to store in a SecureString object would be a social security number, a credit card number, a PIN number, a password, an employee ID, or any other type of sensitive information.
This string data ...
Read now
Unlock full access