SecureString Class

SecureString Class

 

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

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

System.Object
  System.Security.SecureString

public sealed class SecureString : IDisposable

NameDescription
System_CAPS_pubmethodSecureString()

Initializes a new instance of the SecureString class.

System_CAPS_pubmethodSecureString(Char*, Int32)

This API supports the product infrastructure and is not intended to be used directly from your code. Initializes a new instance of the SecureString class from a subarray of System.Char objects.

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

NameDescription
System_CAPS_pubpropertyLength

Gets the number of characters in the current secure string.

NameDescription
System_CAPS_pubmethodAppendChar(Char)

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

System_CAPS_pubmethodClear()

Deletes the value of the current secure string.

System_CAPS_pubmethodCopy()

Creates a copy of the current secure string.

System_CAPS_pubmethodDispose()

Releases all resources used by the current SecureString object.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodInsertAt(Int32, Char)

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

System_CAPS_pubmethodIsReadOnly()

Indicates whether this secure string is marked read-only.

System_CAPS_pubmethodMakeReadOnly()

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

System_CAPS_pubmethodRemoveAt(Int32)

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

System_CAPS_pubmethodSetAt(Int32, Char)

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

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

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.

System_CAPS_importantImportant

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?

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

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 type to a SecureString object by calling its AppendChar or InsertAt method.

System_CAPS_importantImportant

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

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.SecureStringToCoTaskMemUnicode

Marshal.ZeroFreeGlobalAllocUnicode

Back to top

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 is encrypted. However, whether because of missing APIs or key management issues, encryption is not available on all platforms. Because of this, SecureString is available on Desktop (Windows only), and not on .NET Core.

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 (i.e., 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

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

.NET Framework
Available since 2.0

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

Return to top
Show:
© 2016 Microsoft