在 Windows 中可以把網站、網路資源、登入憑證安全的儲存在認證管理員(Credential Manager),在 C# 中我們也可以使用這樣的方式來儲存機密資訊,就可以避免將資料以明文的方式儲存在設定檔中,是個非常好的儲存機密資訊的方式,缺點是只能在 Windows, Windows Server 中使用。
讀取憑證的帳號密碼:
刪除憑證:
開啟「認證管理員」, 在 PowerShell 中可以使用以下指令開啟「認證管理員」:
就可以找到剛剛建立的憑證了:
文章撰寫中...請稍後...
安裝套件
先使用 NuGet 安裝 Meziantou.Framework.Win32.CredentialManager 套件,或是使用 .NET CLI 執行以下指令安裝
dotnet add package Meziantou.Framework.Win32.CredentialManager
程式碼示範
建立憑證:
// using Meziantou.Framework.Win32;
CredentialManager.WriteCredential(
applicationName: "CredentialManagerTests",
userName: "Ruyut",
secret: "mypwd",
comment: "Test",
persistence: CredentialPersistence.LocalMachine
);
讀取憑證的帳號密碼:
var cred = CredentialManager.ReadCredential(applicationName: "CredentialManagerTests");
Console.WriteLine(cred.UserName);
Console.WriteLine(cred.Password);
刪除憑證:
CredentialManager.DeleteCredential(applicationName: "CredentialManagerTests");
開啟「認證管理員」, 在 PowerShell 中可以使用以下指令開啟「認證管理員」:
control /name Microsoft.CredentialManager
就可以找到剛剛建立的憑證了:
文章撰寫中...請稍後...
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com