Click here to Skip to main content
Click here to Skip to main content

Who knows of the .NET Secure Strings?

, 25 Jan 2010
Rate this:
Please Sign up or sign in to vote.
While SecureString is certainly not a new kid on the block, it is often overlooked by .Net programmers that are programming applications that deal with sensitive data (think PCI, KeyManagement, Passwords, Credit cards, etc.)...

[Warning this is not new stuff - but shouldn't be overlooked if you need to secure sensitive data in your application.]

Isn't “Secure String” an oxymoron for .NET? So if we are thinking about securing some sensitive data in say C or C++, it's relatively simple- load it into a char array memory and encrypt it, wiping the memory out after the information has been loaded.

Now try that with .NET! From the Microsoft site:

A String is called immutable because its value cannot be modified once it has been created.

So how can you destroy one? Set it to empty? Well simply put, you can't :-). Once your string is no longer referenced, or worse yet your object containing the string, it's time for the Garbage Collector to come and do its work. The problem is if your object has been around long enough to get into Generation 1 or 2, then it is going to take a bit longer.

Hmmm, so in translation if you keep a password, Credit Card, encryption key or some other sensitive text in memory as a string you can't destroy it (think memset for us oldies!). Only the GC can free the memory for you, and you are dependent on HOW it frees that memory. I personally don't know for a fact if it memsets it to blank, or just dereferences the pointer. However I would be willing to bet it is the option that requires the least amount of work and that doesn't bode well for controlling the exposure of our sensitive data.

Plainly that proverbially sucks!

Enter the “SecureString” class, from the Microsoft site it says:

“Represents text that should be kept confidential. The text is encrypted for privacy when being used, and deleted from computer memory when no longer needed.”

Wow doesn't that just sound like the ticket we need! Secure, Encryption, delete from memory – how fantastic! Uh oh, keep reading the remarks:

“Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.

Use appropriate members of the System.Runtime.InteropServices..::.Marshal class, such as the SecureStringToBSTR method, to manipulate the value of a SecureString object.”

BSTR – oh I feel the COM headache coming back!

Actually, it's really not that bad, but it's definitely not a straight swap for a System.String. See some example code below:

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security;

namespace CSharpHacker.Utilities
{
   /// <span class="code-SummaryComment"><summary>
</span>   /// Demo helper class for <span class="code-SummaryComment"><see cref="SecureString"/>
</span>   /// <span class="code-SummaryComment"></summary>
</span>   public class SensitiveDataHelper
   {
      private SecureString sensitiveData;

      /// <span class="code-SummaryComment"><summary>
</span>      /// Gets or sets the sensitive data class from helper
      /// <span class="code-SummaryComment"></summary>
</span>      /// <span class="code-SummaryComment"><value>The sensitive data container.</value>
</span>      public SecureString SensitiveData
      {
         get { return sensitiveData; }
         set { sensitiveData = value; }
      }

      /// <span class="code-SummaryComment"><summary>
</span>      /// UNSECURE: Converts the secured sensitive data into an unsecured string.
      /// <span class="code-SummaryComment"></summary>
</span>      /// <span class="code-SummaryComment"><remarks>
</span>      /// This is a dangerous function that converts secured information into
      /// unsecured data.
      /// <span class="code-SummaryComment"></remarks>
</span>      /// <span class="code-SummaryComment"><returns>String representing the secured data</returns>
</span>      public string SensitiveDataToString()
      {
         IntPtr ptr = Marshal.SecureStringToGlobalAllocUnicode(this.sensitiveData);
         try
         {
             // Unsecure managed string
             return Marshal.PtrToStringUni(ptr);
         }
         finally
         {
             Marshal.ZeroFreeGlobalAllocUnicode(ptr);
         }
      }

      /// <span class="code-SummaryComment"><summary>
</span>      /// UNSECURE: Base64s encodes a SHA512 has of the sensitive data
      /// <span class="code-SummaryComment"></summary>
</span>      /// <span class="code-SummaryComment"><returns>SHA512 hash value</returns>
</span>      public string Base64SensitiveDataHash()
      {
         IntPtr bstr = Marshal.SecureStringToBSTR(sensitiveData);
         try
         {
            // Pretend simple hash function that returns a string - 
            // this is fake just for readability!!
            string output = Marshal.PtrToStringBSTR(bstr);

            Marshal.FreeBSTR(bstr);

            SHA512 sha = new SHA512Managed();
            byte[] result = sha.ComputeHash(Encoding.UTF8.GetBytes(output));
            return Convert.ToBase64String(result);
         }
         finally
         {
            Marshal.ZeroFreeBSTR(bstr);
         }
      }

      /// <span class="code-SummaryComment"><summary>
</span>      /// Loads the sensitive data into a <span class="code-SummaryComment"><see cref="SecureString"/>
</span>      /// <span class="code-SummaryComment"></summary>
</span>      /// <span class="code-SummaryComment"><param name="sensitiveInformation">The sensitive information to protect.</param>
</span>      public void LoadSensitiveData(char[] sensitiveInformation)
      {
         try
         {
            using (SecureString securePassword = new SecureString())
            {
               foreach (char c in sensitiveInformation)
               {
                  securePassword.AppendChar(c);
               }
               securePassword.MakeReadOnly();
               this.sensitiveData = securePassword.Copy();
            }
         }
         finally
         {
            // discard the char array
            Array.Clear(sensitiveInformation, 0, sensitiveInformation.Length);
         }
      }

      /// <span class="code-SummaryComment"><summary>
</span>      /// Loads the sensitive data into a <span class="code-SummaryComment"><see cref="SecureString"/>
</span>      /// <span class="code-SummaryComment"></summary>
</span>      /// <span class="code-SummaryComment"><param name="sensitiveInformation">The sensitive information to protect.</param>
</span>      public void LoadSensitiveData(string sensitiveInformation)
      {
         char[] sensitive = new char[sensitiveInformation.Length];
         sensitiveInformation.CopyTo(0, sensitive, 0, sensitive.Length);

         LoadSensitiveData(sensitive);
      }

      /// <span class="code-SummaryComment"><summary>
</span>      /// Loads the sensitive data into a <span class="code-SummaryComment"><see cref="SecureString"/>
</span>      /// <span class="code-SummaryComment"></summary>
</span>      /// <span class="code-SummaryComment"><param name="sensitiveInformation">The sensitive information to protect.</param>
</span>      public void LoadSensitiveData(StringBuilder sensitiveInformation)
      {
         char[] sensitive = new char[sensitiveInformation.Length];
         sensitiveInformation.CopyTo(0, sensitive, 0, sensitive.Length);

         LoadSensitiveData(sensitive);
      }

      /// <span class="code-SummaryComment"><summary>
</span>      /// Creates the secure string from string.
      /// <span class="code-SummaryComment"></summary>
</span>      /// <span class="code-SummaryComment"><param name="unprotectedSensitiveInformation">
</span>      /// The unprotected sensitive information.<span class="code-SummaryComment"></param>
</span>      /// <span class="code-SummaryComment"><returns></returns>
</span>      public static SecureString CreateSecureStringFromString
			(string unprotectedSensitiveInformation)
      {
         char[] unprotectedSensitive = unprotectedSensitiveInformation.ToCharArray();
         SecureString secureInformation = new SecureString();
         try
         {
            foreach (char c in unprotectedSensitive)
            {
               secureInformation.AppendChar(c);
            }
            secureInformation.MakeReadOnly();
            return secureInformation;
         }
         finally
         {
            // discard the char array
            Array.Clear(unprotectedSensitive, 0, unprotectedSensitive.Length);
         }
      }
   }
}

A word of caution to the above code:

  • SensitiveDataToString – is considered insecure as it returns a string of the encrypted data. The same data we are trying to encrypt! However it is a commonly requested function, and so there is the implementation.
  • Base64SensitiveDataHash – is considered insecure as it currently uses a temporary string (Frown | :-( ), at this time I don't have a way to converts a BSTR into an array without going through a string first. One way would be to process it prior to being made ReadOnly, or alternatively someone can write a comment on how to convert a C# BSTR into a byte array!

So even with all those disclaimers running a program that takes input will still a ‘leak information’ for the System.String. Specifically the tricky area is how do you get them into your program in the first place? Read them from a database, WinForm user input, or a web page? Kinda tricky :-) ! If you search the web, there are implementations of  secure login controls that build it up character by character, but certainly something to think about.

So how Secure is “SecureString”? The answer is “it depends”, but reasonably secure and a heck of a lot better than System.String. A while ago, there was a big storm about tools that can connect to the process and decrypt your SecureStrings. The best rebuttal to this I've seen can be read about in [SecureString Redux]. I definitely recommend reading this.

Now I have to say I've been meaning to write this for some time now! Hopefully this helped raise awareness of the string leakage risks in the .NET language and ways to help minimize the string information leak scenario.

Potential enhancements to the helper class would be:

  • Make the Hashing really secure, and allow a “HashAlgorithm” to be passed in
  • Allow external encryption
  • Allow secure serialization of data (via the encryption)

Gareth

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

GarethI

United States United States
I'm Gareth and am a guy who loves software! My day job is working for a retail company and am involved in a large scale C# project that process large amounts of data into up stream data repositories.
 
My work rule of thumb is that everyone spends much more time working than not, so you better enjoy what you do!
 
Needless to say - I'm having a blast.
 
Have fun,
 
Gareth

Comments and Discussions

 
QuestionMight stringbuilders be helpful? Pinmembersupercat925-Jan-10 7:32 
AnswerRe: Might stringbuilders be helpful? PinmemberGarethI25-Jan-10 8:36 
GeneralRe: Might stringbuilders be helpful? Pinmembersupercat925-Jan-10 11:45 
AnswerRe: Might stringbuilders be helpful? PinmemberDruuler25-Jan-10 13:46 
GeneralRe: Might stringbuilders be helpful? Pinmembersupercat926-Jan-10 5:56 
JokeRe: Might stringbuilders be helpful? PinmemberGarethI26-Jan-10 7:29 
Smile | :) I was only going to say the "unsafe" keyword is fairly descriptive! Its not something you really want to mess about with!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 25 Jan 2010
Article Copyright 2010 by GarethI
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid