Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
C# Cookbook

C# Cookbook

Joe Mayo
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata