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

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

问题描述

我曾尝试使用 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.

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

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