Let me start that you should store as little sensitive information as possible. But if you do, you should store it in a secure way. That’s why the .NET 2.0 introduced the SecureString class.
I won’t go into detail here, as the links below and the demo source do that much better than I can:
- Making strings more secure
- Data Protection API (DPAPI) part 1 and part 2
- Properly converting SecureString to string
- SecureStringToStringMarshaller
- How to use SecureString
- Comparing SecureString
- Credential Management
- PrepareConstrainedRegions explained
- ConstrainedExecutionRegion, SafeHandle and native handles explained
- ConstrainedExecutionRegion example
- Using Unsafe Code and Pointers
One warning: be very cautious when you convert a SecureString in a regular unsecure array of characters, string, or compare the unsecured content. To quote Fabio Pintos, everytime you do, a little village bursts on fire. When you access it in an insecure way, make sure it is pinned, clear and release the insecure memory as soon as possible.
The problem with a garbage collected environment like .NET is that strings live on the heap, and you can’t deterministically eliminate a string from memory like you could in deterministic environment like Delphi or C/C++.
Have fun with it!
–jeroen





