SecureString Class (System.Security)

Switch View :
ScriptFree
.NET Framework Class Library
SecureString Class

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. This class cannot be inherited.

Inheritance Hierarchy

System.Object
  System.Security.SecureString

Namespace:  System.Security
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic
Public NotInheritable Class SecureString _
	Implements IDisposable
C#
public sealed class SecureString : IDisposable
Visual C++
public ref class SecureString sealed : IDisposable
F#
[<Sealed>]
type SecureString =  
    class
        interface IDisposable
    end

The SecureString type exposes the following members.

Constructors

  Name Description
Public method SecureString() Initializes a new instance of the SecureString class.
Public method SecureString(Char*, Int32) Infrastructure. Initializes a new instance of the SecureString class from a subarray of System.Char objects.
Top
Properties

  Name Description
Public property Length Gets the number of characters in the current secure string.
Top
Methods

  Name Description
Public method AppendChar Appends a character to the end of the current secure string.
Public method Clear Deletes the value of the current secure string.
Public method Copy Creates a copy of the current secure string.
Public method Dispose Releases all resources used by the current SecureString object.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InsertAt Inserts a character in this secure string at the specified index position.
Public method IsReadOnly Indicates whether this secure string is marked read-only.
Public method MakeReadOnly Makes the text value of this secure string read-only.
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method RemoveAt Removes the character at the specified index position from this secure string.
Public method SetAt Replaces the existing character at the specified index position with another character.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Top
Remarks

An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.

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.

The SecureString class is derived from the CriticalFinalizerObject class and implements the IDisposable interface. For more information about implementing the IDisposable interface, see Garbage Collection.

The SecureString class and its members are not visible to COM. For more information, see ComVisibleAttribute.

Windows 2000 Platform Note: In addition to Windows 2000 Service Pack 4 and later, SecureString is supported on Windows 2000 Service Pack 3.

Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition Platform Note: The SecureString class is not supported on Windows 98 or Windows Millennium Edition.

Examples

The following example demonstrates how to use a SecureString to secure a user’s password for use as a credential to start a new process.

Visual Basic

Imports System
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Security

Public Class Example
    Public Shared Sub Main()
        ' Instantiate the secure string.
        Dim securePwd As New SecureString()
        Dim key As ConsoleKeyInfo

        Console.Write("Enter password: ")
        Do
           key = Console.ReadKey(True)

           ' Ignore any key out of range
           If CInt(key.Key) >= 65 And CInt(key.Key <= 90) Then    
              ' Append the character to the password.
              securePwd.AppendChar(key.KeyChar)
              Console.Write("*")
           End If                                    
        ' Exit if Enter key is pressed.
        Loop While key.Key <> ConsoleKey.Enter
        Console.WriteLine()

        Try
            Process.Start("Notepad.exe", "MyUser", securePwd, "MYDOMAIN")
        Catch e As Win32Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Class


C#

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;

public class Example
{
    public static void Main()
    {
        // Instantiate the secure string.
        SecureString securePwd = 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.
              securePwd.AppendChar(key.KeyChar);
              Console.Write("*");
           }   
        // Exit if Enter key is pressed.
        } while (key.Key != ConsoleKey.Enter);
        Console.WriteLine();

        try
        {
            Process.Start("Notepad.exe", "MyUser", securePwd, "MYDOMAIN");
        }
        catch (Win32Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}


Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Community Content

gdosborne
Very little advantage to using SecureString that I can see
I agree with LukePuplett

What's the point? Unless you are using WPF, whose PasswordTextBox has a SecurePassword property that is a SecureString, or you populate one character at a time directly from the keyboard or from a previously encrypted string, it doesn't seem to have any advantages because there's a copy of the original string floating around.

deo.is
How is this useful?

SecureStringToBSTR returns the original string?  That's a joke right?  No salt, no encryption provider?


LukePuplett
See also: ProtectedMemory
People interested in SecureString may also like the ProtectedMemory class :-)

http://msdn.microsoft.com/en-us/library/system.security.cryptography.protectedmemory.aspx

B White
What's the point?
The real trick to SecureString is using and populating it effectively.  The point of the SecureString being to keep the entire plain text string out of memory, you have to populate it one character at a time.  You cannot write routines to create a SecureString from a regular string without violating the point of it, because in creating a string, you just put the plain text version of the string into memory.  Unless you work with text only using character instances, there is no protection from that.   So if you are going to convert to or from any other kind of string, the only point of using SecureString
is to make you feel good that you are being more "secure".

Rudedog2
Convert to String and Back

    class SecureMethods
    {
        public static SecureString StringToSecureString(string input)
        {
            SecureString output = new SecureString();
            int l = input.Length;
            char[] s = input.ToCharArray(0, l);
            foreach (char c in s)
            {
                output.AppendChar(c);
            }
            return output;
        }

        public static String SecureStringToString(SecureString input)
        {
            string output = "";
            IntPtr ptr = SecureStringToBSTR(input);
            output = PtrToStringBSTR(ptr);
            return output;
        }

        private static IntPtr SecureStringToBSTR(SecureString ss)
        {
            IntPtr ptr = new IntPtr();
            ptr = Marshal.SecureStringToBSTR(ss);
            return ptr;
        }

        private static string PtrToStringBSTR(IntPtr ptr)
        {
            string s = Marshal.PtrToStringBSTR(ptr);
            Marshal.ZeroFreeBSTR(ptr);
            return s;
        }   

    }

Ewald Hofman
Create a new SecureString from a string
private SecureString ConvertToSecureString(string value)
{
    SecureString ret = new SecureString();
    foreach (char c in value)
    {
        ret.AppendChar(c);
    }
    ret.MakeReadOnly();
    return ret;
}