Store IV and Key for Rijndael

2019-09-01 11:38发布

问题:

I need to store username and password in an app.config. I want to encrypt these values using Rijndael algorithm. Where do I store the key and IV for decrypting the un and pw? I need to deploy the application to different servers with different users.

回答1:

Encrypting the web.config or app.config file is usually done with RSA or DPAPI encryption.

I'm not sure if it would suit you in your case, it's only effective if the users of the applications are restricted and not administrators.

http://msdn.microsoft.com/en-us/library/ff647398.aspx



回答2:

Definitely don't store in the assembly - a relatively simple look at the IL would probably give up the secret. Even obsfuciating it, would provide little extra security.

Easiest would be to use the OS \ file-system security locally on the different servers to control read access to the key file.



回答3:

Ideally on a text file in a location not accessible via web, only via the local filesystem with tight permissions.

If you need to distribute the app, you could use the following structure

  • C:\MyApp for the key and other private information
  • C:\MyApp\www for the virtual directory

This will prevent prying eyes (or webserver bugs) to access the data. Only physical access to the machine will potentially reveal it, and that usually can be better controlled.



回答4:

How about using machine key encryption to do it? There is (as far as I know) no easy way of doing this, but you can hack your way into the framework using reflection. The machine key is either not or only partially stored on a machine. If you configure ASP.NET to 'Generate a unique key for each application', the application's path is used to derive the key.

The code would be something like this:

private static MethodInfo _cookieEncryptMethod;
private static MethodInfo _cookieDecryptMethod;

public static string MachineKeyEncrypt(string data)
{
    if (_cookieEncryptMethod == null)
    {
        _cookieEncryptMethod = Type.GetType("System.Web.Security.CookieProtectionHelper").GetMethod("Encode", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
    }

    var dataBytes = Encoding.UTF8.GetBytes(data);

    return (string) _cookieEncryptMethod.Invoke(null, new object[] { CookieProtection.All, dataBytes, dataBytes.Length });
}

public static string MachineKeyDecrypt(string source)
{
    if (_cookieDecryptMethod == null)
    {
        _cookieDecryptMethod = Type.GetType("System.Web.Security.CookieProtectionHelper").GetMethod("Decode", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
    }

    var data = (byte[]) _cookieDecryptMethod.Invoke(null, new object[] { CookieProtection.All, source });

    return Encoding.UTF8.GetString(data);
}