.NET Core:如果在 Windows 上运行,如何访问 Windows Credential Manager(否则忽略)? [英] .NET Core: How to access Windows Credential Manager if running on Windows (otherwise ignore)?
问题描述
到目前为止,为了在 .NET 应用程序中存储和检索机密(如凭据),我成功地使用了 CredentialManagement 包.现在我想跨平台.
So far, to store and retrieve secrets (like credentials) in .NET applications, I successfully used the CredentialManagement package on Windows. Now I'd like to go cross-platform.
所以我需要访问 Windows 凭据管理器 来自 .NET Core 跨平台应用程序.如果它在 Windows 上运行 - 使用凭据管理器.如果它在 Linux 上运行 - 不要崩溃(使用钥匙链或其他方式,这是下一步).
So I need to access the Windows Credential Manager from a .NET Core cross-platform application. If it's running on Windows - use the Credential Manager. If it's running on Linux - don't crash (use key chain or whatever, that is the next step).
这将如何完成?
(注意:我对 Windows 凭据管理器的替代品持开放态度,但它们应该提供同等级别的保护.)
推荐答案
我最终使用 Windows 数据保护 API (DPAPI) 将机密存储在已在登录用户范围内加密的文件中.
I ended up using the Data Protection API for Windows (DPAPI) to store secrets in a file that is encrypted within the scope of the logged in user.
密码的加密存储:
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");
}
解密:
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);
}
(仅适用于 Windows,对于其他操作系统,我将使用其他解决方案.)
(Only works on Windows, for other OSes I'll use other solutions.)
这篇关于.NET Core:如果在 Windows 上运行,如何访问 Windows Credential Manager(否则忽略)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!