Ways around putting a password in code

后端 未结 3 579
梦毁少年i
梦毁少年i 2020-12-31 18:16

I have a bit of code that needs to run with elevated privileges (more that I want the rest of my code running at).

I have my code that sets up the Impersonation work

相关标签:
3条回答
  • 2020-12-31 18:41

    You have multiple options here.

    1. You can hash the password the very first time and store the hash to a file. Now the next time, you want to execute the code with elevated privileges, you need to accept/retype the password and re-compute the hash and match it with the stored hash. Only if it matches will you execute your code in elevation modes. You could hash using SHA. Please look at System.Crytography namespace for examples on hashing.

    2. Second option is to encrypt the password using algorithms like AES. However you will need to have a key to do this and you will have to worry about securing this key.

    3. Third option is to use DPAPI and encrypt the password but not worry about securing the keys - much easier option than 2.

    I would recommend 1 if you do not mind re-entering the password every time the application starts. If that is not a possibility, I would suggest going with 3 and use DPAPI.

    Here are some links to get you started.

    1.http://www.obviex.com/samples/dpapi.aspx 2. http://www.obviex.com/samples/Encryption.aspx

    0 讨论(0)
  • 2020-12-31 18:48

    Vaccano,

    I would recommend investigating the data protection API (DPAPI) for what you're attempting to achieve. It is considered part of the solution in many best practice approaches to reversibly storing passwords needed by applications.

    A good article discussing the DPAPI (and other techniques + concerns) can be found here:

    http://msdn.microsoft.com/en-us/magazine/cc164054.aspx

    With C# 2.0, P/Invoking isn't even required; managed wrappers exist:

    http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=41ca5a99-ddc0-4d0a-9919-2ce10bf50c7e

    I hope this helps!

    0 讨论(0)
  • 2020-12-31 18:51

    You can use safe-config nuget package. Internally it uses data protection api to encrypt and decrypt data.

    //Save some configuration data at folder data\temp\
    var configManager = new ConfigManager()
        .WithOptions(DataProtectionScope.CurrentUser)
        .Set("password", "my-massword")
        .AtFolder(@"data\temp\")
        .Save();
    
        ...
    
    //Load configuration data
    var loadedValue = new ConfigManager()
        .AtFolder(@"data\temp\")
        .Load()
        .Get<string>("password");
    
    0 讨论(0)
提交回复
热议问题