DPAPI密码加密在C#并保存到数据库中。然后使用密钥解密它 [英] DPAPI password encryption in C# and saving into database.Then Decrypting it using a key

查看:326
本文介绍了DPAPI密码加密在C#并保存到数据库中。然后使用密钥解密它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用UTF8算法和SHA256进行密码加密,但建议不要使用它们。相反,我建议使用DPAPI。我浏览了很少的谷歌样本代码,这些代码不清楚。你可以用DPAPI算法来帮助我吗

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.

推荐答案

您可以使用 ProtectedData 类。
有两种加密模式:

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


  • CurrentUser:受保护的数据与当前用户相关联。只有在当前用户环境下运行的线程才能取消保护数据。

  • LocalMachine:受保护的数据与机器上下文相关联。在计算机上运行的任何进程都可以取消保护数据。此枚举值通常用于在不允许访问不受信任用户的服务器上运行的服务器特定应用程序。

编码字符串并返回一个可以保存在数据库中的Base64字符串:

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));
}

解码一个Base64字符串(您以前保存在数据库中):

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));
    }

您需要记住加密仅对机器有效(和用户,如果您选择 CurrentUser 加密模式),则加密/解密需要在同一台服务器上执行。

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.

如果您打算在负载平衡环境下使用DPAPI,请看到这篇文章

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

如果您需要更多信息,请通知我。

Let me know if your need more information.

这篇关于DPAPI密码加密在C#并保存到数据库中。然后使用密钥解密它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆