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

Fayaz shaik picture Fayaz shaik · Dec 10, 2015 · Viewed 10.5k times · Source

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 from google which were not clear. Can you help me with the DPAPI Algorithm.

Answer

Thomas picture Thomas · Dec 10, 2015

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.