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

11,765

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.

Share:
11,765
Fayaz shaik
Author by

Fayaz shaik

Updated on June 12, 2022

Comments

  • Fayaz shaik
    Fayaz shaik almost 2 years

    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.

  • Dan
    Dan over 6 years
    You don't want to use MD5 or SHA-1 because they're far too fast and can be brute forced with ease on modern hardware. You'll want something like bcrypt or another hard password function. Additionally, the question doesn't imply that the user has control over the password verification, merely that they want to store a password.