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

倖福魔咒の 提交于 2019-11-29 23:32:26

问题


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.


回答1:


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.




回答2:


Arcording to MSDN, DPAPI is "using the user or machine credentials to encrypt or decrypt data". I think it use DES or AES algorithm.

But for password, you should always use 1-way hash functions (MD5, SHA1...) with salt before saving to DB. Even if the hacker can access to your server, he can never decrypt password of users.

So, just stick with your SHA256 solution. Remember to add some salt before hash it.



来源:https://stackoverflow.com/questions/34194223/dpapi-password-encryption-in-c-sharp-and-saving-into-database-then-decrypting-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!