DPAPI password encryption in C# and saving into database.Then Decrypting it using a key

后端 未结 2 1011
长发绾君心
长发绾君心 2020-12-10 08:08

I have tried Password encryption using UTF8 Algorithm and SHA256, but was adviced not to use them. Instead , I was suggested to use DPAPI .I have browsed few sample codes fr

2条回答
  •  天命终不由人
    2020-12-10 08:17

    You can access DPAPI using the ProtectedData class. There are two modes of encryption:

    • CurrentUser: The protected data is associated with the current user. Only threads running under the current user context can unprotect the data.
    • LocalMachine: The protected data is associated with the machine context. Any process running on the computer can unprotect data. This enumeration value is usually used in server-specific applications that run on a server where untrusted users are not allowed access.

    Encode a string and return a Base64 string that you can save in your database:

    public static string Protect(string stringToEncrypt, string optionalEntropy, DataProtectionScope scope)
    {
        return Convert.ToBase64String(
            ProtectedData.Protect(
                Encoding.UTF8.GetBytes(stringToEncrypt)
                , optionalEntropy != null ? Encoding.UTF8.GetBytes(optionalEntropy) : null
                , scope));
    }
    

    Decode a Base64 string (that you have previously saved in your database):

    public static string Unprotect(string encryptedString, string optionalEntropy, DataProtectionScope scope)
        {
            return Encoding.UTF8.GetString(
                ProtectedData.Unprotect(
                    Convert.FromBase64String(encryptedString)
                    , optionalEntropy != null ? Encoding.UTF8.GetBytes(optionalEntropy) : null
                    , scope));
        }
    

    You need to remember that the encryption is valid only for a machine (and a user, if you choose the CurrentUser encryption mode) so the encryption/decryption needs to be perform on the same server.

    If you plan to use DPAPI under a load balance environment see this article.

    Let me know if your need more information.

提交回复
热议问题