如何使用C#在Windows上存储和检索凭据 [英] How to store and retrieve credentials on Windows using C#

查看:219
本文介绍了如何使用C#在Windows上存储和检索凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个C#程序,该程序将在Windows 10上运行.我只想按一个按钮就可以从该程序发送电子邮件(计算结果).我在C#属性中放置了from:电子邮件地址和subject:等,但是我不想在程序中的任何位置放置明文密码,并且我也不希望用户键入每次发送邮件时,请在服务器的密码中输入密码.

I build a C# program, to be run on Windows 10. I want to send emails from this program (calculation results) by just pressing a button. I put the from: e-mail address and the subject:, etc. in C# properties, but I do not want to put a clear text password anywhere in the program, AND I don't want the user to have to type in the password for the server each time a mail is sent.

可以做到吗?

如果是这样,(通常)如何?

If so, how (generally)?

我当时正在考虑将所有电子邮件信息(包括服务器的加密密码)放入程序启动期间要读取的数据文件中.

I was thinking of putting all that e-mail information, including an encrypted password for the server in a data file to be read during startup of the program.

也许Windows 10为此提供了便利...

Or maybe Windows 10 has a facility for that...

推荐答案

您可以使用Windows凭据管理API.这样,您将只要求用户输入一次密码,然后将密码存储在Windows Credentials Manager中.

You can use the Windows Credential Management API. This way you will ask the user for the password only once and then store the password in Windows Credentials Manager.

下次您的应用程序启动并且需要使用密码时,它将从Windows Credentials Manager中读取该密码.可以直接通过 P/调用( )或通过C#包装器 CredentialManagement .

Next time your application starts and it needs to use the password it will read it from Windows Credentials Manager. One can use the Windows Credential Management API directly using P/Invoke (credwrite, CredRead, example here) or via a C# wrapper CredentialManagement.

使用NuGet CredentialManagement软件包的示例用法:

Sample usage using the NuGet CredentialManagement package:

public class PasswordRepository
{
    private const string PasswordName = "ServerPassword";

    public void SavePassword(string password)
    {
        using (var cred = new Credential())
        {
            cred.Password = password;
            cred.Target = PasswordName;
            cred.Type = CredentialType.Generic;
            cred.PersistanceType = PersistanceType.LocalComputer;
            cred.Save();
        }
    }

    public string GetPassword()
    {
        using (var cred = new Credential())
        {
            cred.Target = PasswordName;
            cred.Load();
            return cred.Password;
        }
    }
}

我不建议将密码存储在客户端计算机上的文件中.即使您加密了密码,也可能会将解密密钥嵌入到应用程序代码中,这不是一个好主意.

I don't recommend storing passwords in files on client machines. Even if you encrypt the password, you will probably embed the decryption key in the application code which is not a good idea.

这篇关于如何使用C#在Windows上存储和检索凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆