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
實作

範例

下列範例示範如何使用 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.
              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

備註

重要

我們不建議您使用 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 看不到 SecureString 類別及其成員。The 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.

SecureString 物件類似于 String 物件,因為它具有文字值。A 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 類別限制的討論,請參閱 如何 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
您可以藉由呼叫其 AppendCharInsertAt 方法,一次將單一字元加入至 SecureString 物件。You can add a single character at a time to a SecureString object by calling its AppendChar or InsertAt method.

重要

SecureString 物件絕對不應從 String進行結構化,因為機密資料已受不可變 String 類別的記憶體持續性結果所影響。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. 建立 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
SecureString 類別只有兩個提供字串相關資訊的成員:它的 Length 屬性,表示字串中的 UTF16 編碼的程式碼單位數目;和 IsReadOnly的方法,指出實例是否為唯讀。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 會執行 IDisposable 介面,所以您可以藉由呼叫 Dispose 方法來釋放其記憶體。Because SecureString implements the IDisposable interface, you release its memory by calling the Dispose method.

SecureString 類別沒有可檢查、比較或轉換 SecureString值的成員。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. 使用 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:

PlatformPlatform
在 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.

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

  • 因為 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.

相較于 String 類別,只會縮短 SecureString 實例的值所公開的時間間隔。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.

整體來說,SecureStringString 更安全,因為它會限制敏感字串資料的暴露。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()

初始化 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().

屬性

Length

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

方法

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

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

Equals(Object)

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

(繼承來源 Object)
GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetType()

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

(繼承來源 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()

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

(繼承來源 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.

(繼承來源 Object)

適用於

另請參閱