SecureString 類別


代表應該將文字保密,例如於不再使用時將它從電腦記憶體刪除。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


下列範例示範如何使用SecureString來保護使用者的密碼, 以做為認證以啟動新的進程。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.
        // Exit if Enter key is pressed.
        } while (key.Key != ConsoleKey.Enter);
        try {
            Process.Start("Notepad.exe", "MyUser", securePwd, "MYDOMAIN");
        catch (Win32Exception e) {
        finally {
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: ")
           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.
           End If                                    
        ' Exit if Enter key is pressed.
        Loop While key.Key <> ConsoleKey.Enter
            Process.Start("Notepad.exe", "MyUser", securePwd, "MYDOMAIN")
        Catch e As Win32Exception
        End Try
    End Sub
End Class



我們不建議您將類別用於SecureString新的開發。We don't recommend that you use the SecureString class for new development. 如需詳細資訊, 請參閱SecureString 不應在 GitHub 上使用。For more information, see SecureString shouldn't be used on GitHub.

SecureString是提供安全性量值的字串類型。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. (不過, 如需限制, 請參閱 如何 SecureString?一節)。實例SecureString的值會在初始化實例或修改值時, 使用基礎平臺所支援的機制自動受到保護。(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. 您的應用程式可以將實例轉譯為不可變, 並藉MakeReadOnly由叫用方法來防止進一步修改。Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.

SecureString實例的最大長度是65536個字元。The maximum length of a SecureString instance is 65,536 characters.


此型別代表 IDisposable 介面。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. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

COM 看不到類別及其成員。SecureStringThe SecureString class and its members are not visible to COM. 如需詳細資訊,請參閱ComVisibleAttributeFor more information, see ComVisibleAttribute.

本節內容:In this section:

字串與SecureString String vs. SecureString
SecureString 作業 SecureString operations
SecureString 和 interop SecureString and interop
SecureString 有多安全?How secure is SecureString?

字串與 SecureStringString versus SecureString

System.String類別的實例是不可變的, 而且不再需要時, 也無法以程式設計方式排程進行垃圾收集; 也就是說, 實例在建立之後是唯讀的, 而且無法預測實例何時會已從電腦記憶體中刪除。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. 因為System.String實例是不可變的, 所以看似修改現有實例的作業實際上會建立它的複本來操作。Because System.String instances are immutable, operations that appear to modify an existing instance actually create a copy of it to manipulate. 因此, 如果String物件包含機密資訊 (例如密碼、信用卡號碼或個人資料), 就會有風險, 因為您的應用程式無法從電腦記憶體中刪除資料, 因此在使用該資訊之後, 可能會發生此問題.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.

物件與String物件相似之處在于, 它具有文字值。 SecureStringA SecureString object is similar to a String object in that it has a text value. 不過, SecureString物件的值會釘選在記憶體中, 可能會使用基礎作業系統所提供的保護機制 (例如加密), 直到您的應用程式將其標示為唯讀, 並可從電腦記憶體中刪除為止, 都可以加以修改。由您的應用程式呼叫Dispose方法或 .NET Framework 垃圾收集行程。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.

如需SecureString類別限制的討論, 請參閱 < secure is SecureString?一節。For a discussion of the limitations of the SecureString class, see the How secure is SecureString? section.

回到頁首Back to top

SecureString 作業SecureString operations

SecureString類別包含可讓您執行下列工作的成員:The SecureString class includes members that allow you to do the following:

SecureString物件具現化Instantiate a SecureString object
您可以藉SecureString由呼叫其無參數的函式來具現化物件。You instantiate a SecureString object by calling its parameterless constructor.

將字元新增至SecureString物件Add characters to a SecureString object
您可以藉由呼叫其SecureString AppendCharInsertAt方法, 一次將單一字元加入至物件。You can add a single character at a time to a SecureString object by calling its AppendChar or InsertAt method.


物件絕對不應從建立String, 因為機密資料已受到不可變String類別的記憶體持續性結果所影響。 SecureStringA 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. 若要建立SecureString物件, 最好的方式是從非時間的非受控來源, 例如Console.ReadKey方法。The best way to construct a SecureString object is from a character-at-a-time unmanaged source, such as the Console.ReadKey method.

移除SecureString物件中的字元Remove characters from a SecureString object
您可以藉SetAt由呼叫方法來取代個別字元、藉由RemoveAt呼叫方法來移除個別字元, 或藉由呼叫Clear方法來SecureString移除實例中的所有字元。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.

將物件SecureString設為唯讀Make the SecureString object read-only
定義SecureString物件所代表的字串之後, 您可以呼叫其MakeReadOnly方法, 讓字串變成隻讀。Once you have defined the string that the SecureString object represents, you call its MakeReadOnly method to make the string read-only.

取得物件的SecureString相關資訊Get information about the SecureString object
類別只有兩個提供字串相關資訊的成員: 其Length屬性, 表示字串中的 UTF16 編碼的程式碼單位數目; 以及IsReadOnly方法, 指出實例是否為SecureString唯讀。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.

釋放配置給SecureString實例的記憶體Release the memory allocated to the SecureString instance
因為SecureString會執行Dispose介面, 所以您可以藉由呼叫方法來釋放其記憶體。 IDisposableBecause SecureString implements the IDisposable interface, you release its memory by calling the Dispose method.

類別沒有任何成員可檢查、比較或轉換的值SecureStringSecureStringThe 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. 使用System.Runtime.InteropServices.Marshal類別的適當成員 (例如SecureStringToBSTR方法) 來SecureString操作物件的值。Use appropriate members of the System.Runtime.InteropServices.Marshal class, such as the SecureStringToBSTR method, to manipulate the value of a SecureString object.

.NET Framework 類別庫通常會以SecureString下列方式使用實例:The .NET Framework Class Library commonly uses SecureString instances in the following ways:

回到頁首Back to top

SecureString 和 interopSecureString and interop

由於作業系統不直接支援SecureString, 因此您必須先將SecureString物件的值轉換成所需的字串類型, 然後再將字串傳遞至原生方法。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. Marshal類別有五個執行此動作的方法: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 零和 free 方法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

SecureString 有多安全?How secure is SecureString?

當正確建立時, SecureString實例會提供比更多的String資料保護。When created properly, a SecureString instance provides more data protection than a String. 從逐字元來源建立字串時, String會在記憶體中建立多個中繼, 而SecureString只會建立單一實例。When creating a string from a character-at-a-time source, String creates multiple intermediate in memory, whereas SecureString creates just a single instance. 垃圾收集物件String是不具決定性的。Garbage collection of String objects is non-deterministic. 此外, 因為它的記憶體未固定, 垃圾收集行程會在移動和壓縮記憶體String時, 產生額外的值複本。In addition, because its memory is not pinned, the garbage collector will make additional copies of String values when moving and compacting memory. 相反地, 配置給SecureString物件的記憶體會固定, 而且可以藉由Dispose呼叫方法來釋放記憶體。In contrast, the memory allocated to a SecureString object is pinned, and that memory can be freed by calling the Dispose method.

雖然儲存在SecureString實例中的資料比儲存String在實例中的資料更安全, 但SecureString實例的保護方式有很大的限制。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:

在 Windows 作業系統上, SecureString實例內部字元陣列的內容會經過加密。On the Windows operating system, the contents of a SecureString instance's internal character array are encrypted. 不過, 不論缺少 Api 或金鑰管理問題, 都無法在所有平臺上使用加密。However, whether because of missing APIs or key management issues, encryption is not available on all platforms. 由於此平臺相依性, SecureString不會加密非 Windows 平臺上的內部儲存區。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.

即使執行可以利用加密, 指派SecureString給實例的純文字也可能會在不同的時間公開: SecureStringEven 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:

  • 因為 Windows 不會在作業系統層級提供安全字串實作為, 所以 .NET Framework 仍然必須將安全字串值轉換成純文字表示, 才能使用它。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.

  • 每當安全字串的值是由AppendCharRemoveAt之類的方法修改時, 就必須將其解密 (也就是轉換回純文字)、修改, 然後再加密一次。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.

  • 如果在 interop 呼叫中使用安全字串, 則必須將它轉換成 ANSI 字串、Unicode 字串或二進位字串 (BSTR)。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). 如需詳細資訊, 請參閱SecureString 和 interop一節。For more information, see the SecureString and interop section.

SecureStringString于類別, 只會縮短實例的值所公開的時間間隔。The time interval for which the SecureString instance's value is exposed is merely shortened in comparison to the String class.

儲存體與使用方式Storage versus usage
更常見的SecureString情況是, 類別會針對應該受到保護或保密的字串值定義儲存機制。More generally, the SecureString class defines a storage mechanism for string values that should be protected or kept confidential. 不過, 在 .NET Framework 本身以外, 沒有任何使用機制支援SecureStringHowever, 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.

整體來說SecureString , 比較String安全, 因為它會限制敏感字串資料的暴露。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. 建議的替代SecureString方法是針對儲存在進程外的認證使用不透明的控制碼, 而不是使用來保護密碼。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



初始化 SecureString 類別的新執行個體。Initializes a new instance of the SecureString class.

SecureString(Char*, Int32)

Char 物件的子陣列,初始化 SecureString 類別的新執行個體。Initializes a new instance of the SecureString class from a subarray of Char objects.

這個建構函式不符合 CLS 標準。This constructor is not CLS-compliant. 符合 CLS 標準的替代項目為 SecureString()The CLS-compliant alternative is SecureString().



取得目前安全字串中的字元數。Gets the number of characters in the current secure string.



將字元附加至目前安全字串的結尾。Appends a character to the end of the current secure string.


刪除目前安全字串的值。Deletes the value of the current secure string.


建立目前安全字串的複本。Creates a copy of the current secure string.


釋放由 SecureString 物件使用的所有資源。Releases all resources used by the current SecureString object.


判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InsertAt(Int32, Char)

將這個安全字串中的字元插入指定索引位置。Inserts a character in this secure string at the specified index position.


指示這個安全字串是否標示為唯讀。Indicates whether this secure string is marked read-only.


使這個安全字串的文字值成為唯讀。Makes the text value of this secure string read-only.


建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)

從這個安全字串移除位在指定索引位置的字元。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.


傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)