• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Monday, August 14, 2017

Usability of SecureString object in C#

 Abhishek Tomer     August 14, 2017     .Net, C#     2 comments   

Introduction
Hi friends! In this blog we will be discussing a very interesting as well as useful topic in C# and that is Securestring object.

Background
SecureString as the name depicts, is used in situations where we need to store some sensitive and confidential information ranging from password to credit card numbers, pins or any other kind of personal information.
If we use string object to save such information in C# and perform further processing on that data, definitely it seems to be unsafe.
Let’s find out why??

Limitation of String object for storing sensitive data
“System. String” variables are reference type and created on the heap. We know this well, that garbage collector automatically cleans heap to free memory space. The problem lies here, as we cannot predict or set the time when the garbage collector cleans the memory. This may lead to retention of string object for longer time on a server than required. So, there is a risk of lack of this information till it is not cleaned up.

Solution
.Net gives us a safe way to deal with this problem by SecureString class. This class inherits from System. Object. This helps protect sensitive information from leak due to following points.
  • SecureString data are stored in RAM and garbage collector do not create copies of this data.
  • Moreover, the value of a SecureString object is automatically encrypted. This data can be prevented from modification by making it read-only by invoking MakeReadOnly method. Thus, your application can render immutable SecureString instances.
  • SecureString has no members to perform comparison or any conversion of the value of a SecureString. This again protects the value of the instance from any deliberate or accidental leak.
  • Members of System.Runtime.InteropServices.Marshal class (like SecureStringToBSTR method) can be used to modify SecureString objects till it is editable.
  • This type implements the IDisposable interface which helps in disposing data after use. Deletion can be either direct by calling Dispose method inside try/catch block., or indirect by using a language construct such as using keyword.
  • In order to read encrypte secureString value we need to decrypt it. There are two approaches used for decryption-
      1. Using class “Marshal”
      2. Using System.Net.NetworkCredential
Below code has implementation of “SecureString” object.
namespace SecureStringExample
{
    using System;
    using System.Security;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Diagnostics;

    public 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);
            }
        }
    }
}

Output:
Enter password: ********
Encrypted SecureString value  is :System.Security.SecureString
First way: Decrypted SecureString value  is :Abhishek
Second way: Decrypted SecureString value  is :Abhishek
SecureString object program in C#
SecureString object in C#
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.

Summary:
So, Guys this is how we can handle sensitive data in C# application using “Secure.String” object.
I Hope this post will be helpful to understand the concept of Securing Strings in C#.

Please share this post with your friends and colleagues to help them.

For any queries please post a comment below.

Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

2 comments:

  1. UnknownAugust 29, 2017 at 12:52 PM

    This comment has been removed by the author.

    ReplyDelete
    Replies
      Reply
  2. UnknownAugust 29, 2017 at 2:30 PM

    Great

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • Creating and Working with Database
    Hi friends! In our last post we have seen different approaches how we can connect with SQL Server Management Studio(SSMS). Today, We are g...
  • Entity Types in Entity Framework
    In this article, I am going to discuss the Entity Types in Entity Framework in detail. Please read our previous article where we discussed...
  • Introduction to Entity Framework
    Before .NET 3.5 as a developer, we often used to write ADO.NET code to perform CRUD operation with the underlying database. For this, we ne...
  • Filters in ASP.Net MVC
    Hi friends! Today we are going to discuss about using a very important feature of MVC i.e. “Filters“ . Filters are a unique feature of Asp...
  • Data Parallelism in C#
    Introduction: Hi, in this blog we are going to discuss a very important feature of C# that is data parallelism. Data parallelism means the ...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape