Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

How to store and retrieve credentials on Windows using C#

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.

Can that be done?

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...