Hei*_*cht 7 .net c# credential-manager .net-core
到目前为止,为了在 .NET 应用程序中存储和检索机密(如凭据),我成功地在 Windows 上使用了CredentialManagement包。现在我想跨平台。
因此,我需要从 .NET Core 跨平台应用程序访问Windows 凭据管理器。如果它在 Windows 上运行 - 使用凭据管理器。如果它在 Linux 上运行 - 不要崩溃(使用钥匙链或其他东西,这是下一步)。
这将如何完成?
(注意:我对 Windows 凭据管理器的替代方案持开放态度,但它们应该提供同等级别的保护。)
我最终使用 Windows 数据保护 API (DPAPI) 将机密存储在一个在登录用户范围内加密的文件中。
密码的加密存储:
try
{
var passwordBytes = Encoding.UTF8.GetBytes(password);
var protectedPasswordBytes = ProtectedData.Protect(passwordBytes, null, DataProtectionScope.CurrentUser);
var protectedPasswordBytesBase64 = Convert.ToBase64String(protectedPasswordBytes);
File.WriteAllText(passwordFilePath, protectedPasswordBytesBase64);
} catch (PlatformNotSupportedException)
{
Debug.WriteLine("Could not store credentials");
}
Run Code Online (Sandbox Code Playgroud)
解密:
if (File.Exists(passwordFilePath))
{
var protectedPasswordBytesBase64 = File.ReadAllText(passwordFilePath);
var protectedPasswordBytes = Convert.FromBase64String(protectedPasswordBytesBase64);
var passwordBytes = ProtectedData.Unprotect(protectedPasswordBytes, null, DataProtectionScope.CurrentUser);
password = Encoding.UTF8.GetString(passwordBytes);
}
Run Code Online (Sandbox Code Playgroud)
(仅适用于 Windows,对于其他操作系统,我将使用其他解决方案。)
| 归档时间: |
|
| 查看次数: |
9258 次 |
| 最近记录: |