Usability of SecureString object in C#

In this blog, I am going to explain you the Advantage and usability of “SecureString” object in C# .Net framework. 


Most of the time, we come to a scenario where we need to store confidential/Sensitive information such as a password, credit card number, server configuration or personal data into C# application for further processing to perform different actions, and for this, we preferably go with  “System.String” data Type object instance to hold such data.

But do we think this is safe? especially when performing an operation for further processing?

Limitation of String Object for Storing Sensitive Data
As we know “System.String” variables are reference type and created in the heap. These object from heap are get cleaned up by the Garbage Collector automatically to reclaim the memory as needed. It’s difficult to predict when memory get clean, there might be possibility that this value may not be cleaned up for long time on the servers. So, there is a risk of the information being revealed after use because our application can’t delete the data from computer memory.

Solution:
.Net provides a secure way of managing such sensitive data. It provides the SecureString class that inherits from System.Object. SecureString data is stored in RAM, so the Garbage Collector doesn’t move it around or make copies of it.
A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.


The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.
Note that SecureString has no members that inspect, compare, or convert the value of a SecureString. The absence of such members helps protect the value of the instance from accidental or malicious exposure. Use appropriate members of the System.Runtime.InteropServices.Marshal class, such as the SecureStringToBSTR method, to manipulate the value of a SecureString object.


This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using keyword.

Below code has an implementation of “SecureString” object.

namespace SecureStringExample
{
    using System;
    using System.Security;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate the secure string.
            SecureString secureString = new SecureString();
            ConsoleKeyInfo key;
            Console.Write("Enter password: ");
            do
            {
                key = Console.ReadKey(true);
                // Ignore any key out of range. 
                if (((int)key.Key) >= 65 && ((int)key.Key <= 90))
                {
                    // Append the character to the password.
                    secureString.AppendChar(key.KeyChar);
                    Console.Write("*");
                }
                // Exit if Enter key is pressed.
            } while (key.Key != ConsoleKey.Enter);
            Console.WriteLine();
            try
            {
                Console.WriteLine("Encrypted SecureString value  is :" + secureString.ToString());
                // Get the original value.
                string password = new System.Net.NetworkCredential(string.Empty, secureString).Password;
                Console.WriteLine("First way: Decrypted SecureString value  is :" + password);
                Console.WriteLine("Second way: Decrypted SecureString value  is :" + SecureStringToString(secureString));
            }
            catch (Win32Exception e)
            {
                Console.WriteLine(e.Message);
            }
            key = Console.ReadKey(true);
        }
       
        public static String SecureStringToString(SecureString value)
        {
            IntPtr valuePtr = IntPtr.Zero;
            try
            {
                valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
                return Marshal.PtrToStringUni(valuePtr);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
            }
        }
    }
}

 

Here we can see variable “secureString” is an instance of SecureString. While getting string/password from user inputs on console, we are appending char into “secureString” variable. As by default, we cannot read value from “SecureString” since it’s encrypted. We can decrypt the value /to get original value using below 2 approaches


  1. Using class “Marshal”
  2. Using System.Net.NetworkCredential

This is how we can handle sensitive data in C# application using “Secure.String” object.


Write a comment
Cancel Reply
  • Alex May 26, 2017, 7:19 am
    excellent one !
    reply
  • Rameshkumar March 30, 2016, 10:01 am
    Nice one Expecting much more interesting topics
    reply
  • amazon gift card generator free November 2, 2015, 5:34 pm
    Nice post. I learn something more challenging on different websites daily. It'll often be exciting to see material from different writers and training a little from their store.
    reply
  • darkness reborn hack tool October 31, 2015, 8:33 pm
    You should take part in a contest for one of the finest blog on the net. I will recommend this blog!
    reply