SecureString Class

Definition

Represents text that should be kept confidential, such as by deleting it from computer memory when no longer needed. This class cannot be inherited.

public ref class SecureString sealed : IDisposable
public sealed class SecureString : IDisposable
type SecureString = class
    interface IDisposable
Public NotInheritable Class SecureString
Implements IDisposable
Inheritance
SecureString
Implements

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.

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);
        }
        finally {
           securePwd.Dispose();
        }
    }
}
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)
        Finally
           securePwd.Dispose()
        End Try
    End Sub
End Class

Remarks

Important

We recommend that you don't use the SecureString class for new development on .NET (Core) or when you migrate existing code to .NET (Core). For more information, see SecureString shouldn't be used.

SecureString is a string type that provides a measure of security. It tries to avoid storing potentially sensitive strings in process memory as plain text. (For limitations, however, see the How secure is SecureString? section.) The value of an instance of SecureString is automatically protected using a mechanism supported by the underlying platform 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.

The maximum length of a SecureString instance is 65,536 characters.

Important

This type implements the IDisposable interface. When you have finished using an instance of 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 (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

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

In this section:

String vs. SecureString
SecureString operations
SecureString and interop
How secure is SecureString?

String versus SecureString

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. Because System.String instances are immutable, operations that appear to modify an existing instance actually create a copy of it to manipulate. 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 pinned in memory, may use a protection mechanism, such as encryption, provided by the underlying operating system, can be modified until your application marks it as read-only, and can be deleted from computer memory either by your application calling the Dispose method or by the .NET Framework garbage collector.

For a discussion of the limitations of the SecureString class, see the How secure is SecureString? section.

Back to top

SecureString operations

The SecureString class includes members that allow you to do the following:

Instantiate a SecureString object
You instantiate a SecureString object by calling its parameterless constructor.

Add characters to a SecureString object
You can add a single character at a time to a SecureString object by calling its AppendChar or InsertAt method.

Important

A SecureString object should never be constructed from a String, because the sensitive data is already subject to the memory persistence consequences of the immutable String class. The best way to construct a SecureString object is from a character-at-a-time unmanaged source, such as the Console.ReadKey method.

Remove characters from a SecureString object
You can replace an individual character by calling the SetAt method, remove an individual character by calling the RemoveAt method, or remove all characters from the SecureString instance by calling the Clear method.

Make the SecureString object read-only
Once you have defined the string that the SecureString object represents, you call its MakeReadOnly method to make the string read-only.

Get information about the SecureString object
The SecureString class has only two members that provide information about the string: its Length property, which indicates the number of UTF16-encoded code units in the string; and the IsReadOnly, method, which indicates whether the instance is read-only.

Release the memory allocated to the SecureString instance
Because SecureString implements the IDisposable interface, you release its memory by calling the Dispose method.

The SecureString class 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 .NET Framework Class Library commonly uses SecureString instances in the following ways:

Back to top

SecureString and interop

Because the operating system does not directly support SecureString, you must convert the value of the SecureString object to the required string type before passing the string to a native method. The Marshal class has five methods that do this:

Each of these methods creates a clear-text string in unmanaged memory. It is the responsibility of the developer to zero out and free that memory as soon as it is no longer needed. Each of the string conversion and memory allocation methods has a corresponding method to zero out and free the allocated memory:

Allocation and conversion method Zero and free method
Marshal.SecureStringToBSTR Marshal.ZeroFreeBSTR
Marshal.SecureStringToCoTaskMemAnsi Marshal.ZeroFreeCoTaskMemAnsi
Marshal.SecureStringToCoTaskMemUnicode Marshal.ZeroFreeCoTaskMemUnicode
Marshal.SecureStringToGlobalAllocAnsi Marshal.ZeroFreeGlobalAllocAnsi
Marshal.SecureStringToGlobalAllocUnicode Marshal.ZeroFreeGlobalAllocUnicode

Back to top

How secure is SecureString?

When created properly, a SecureString instance provides more data protection than a String. When creating a string from a character-at-a-time source, String creates multiple intermediate in memory, whereas SecureString creates just a single instance. Garbage collection of String objects is non-deterministic. In addition, because its memory is not pinned, the garbage collector will make additional copies of String values when moving and compacting memory. In contrast, the memory allocated to a SecureString object is pinned, and that memory can be freed by calling the Dispose method.

Although data stored in a SecureString instance is more secure than data stored in a String instance, there are significant limitations on how secure a SecureString instance is. These include:

Platform
On the Windows operating system, the contents of a SecureString instance's internal character array are encrypted. However, whether because of missing APIs or key management issues, encryption is not available on all platforms. Because of this platform dependency, SecureString does not encrypt the internal storage on non-Windows platform. Other techniques are used on those platforms to provide additional protection.

Duration
Even if the SecureString implementation is able to take advantage of encryption, the plain text assigned to the SecureString instance may be exposed at various times:

  • Because Windows doesn't offer a secure string implementation at the operating system level, the .NET Framework still has to convert the secure string value to its plain text representation in order to use it.

  • Whenever the value of the secure string is modified by methods such as AppendChar or RemoveAt, it must be decrypted (that is, converted back to plain text), modified, and then encrypted again.

  • If the secure string is used in an interop call, it must be converted to an ANSI string, a Unicode string, or a binary string (BSTR). For more information, see the SecureString and interop section.

The time interval for which the SecureString instance's value is exposed is merely shortened in comparison to the String class.

Storage versus usage
More generally, the SecureString class defines a storage mechanism for string values that should be protected or kept confidential. However, outside of the .NET Framework itself, no usage mechanism supports SecureString. This means that the secure string must be converted to a usable form (typically a clear text form) that can be recognized by its target, and that decryption and conversion must occur in user space.

Overall, SecureString is more secure than String because it limits the exposure of sensitive string data. However, those strings may still be exposed to any process or operation that has access to raw memory, such as a malicious process running on the host computer, a process dump, or a user-viewable swap file. Instead of using SecureString to protect passwords, the recommended alternative is to use an opaque handle to credentials that are stored outside of the process.

Back to top

Constructors

SecureString()

Initializes a new instance of the SecureString class.

SecureString(Char*, Int32)

Initializes a new instance of the SecureString class from a subarray of Char objects.

This constructor is not CLS-compliant. The CLS-compliant alternative is SecureString().

Properties

Length

Gets the number of characters in the current secure string.

Methods

AppendChar(Char)

Appends a character to the end of the current secure string.

Clear()

Deletes the value of the current secure string.

Copy()

Creates a copy of the current secure string.

Dispose()

Releases all resources used by the current SecureString object.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InsertAt(Int32, Char)

Inserts a character in this secure string at the specified index position.

IsReadOnly()

Indicates whether this secure string is marked read-only.

MakeReadOnly()

Makes the text value of this secure string read-only.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
RemoveAt(Int32)

Removes the character at the specified index position from this secure string.

SetAt(Int32, Char)

Replaces the existing character at the specified index position with another character.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

See also