c# - 无法将密码另存为哈希时该怎么办

标签 c# encryption passwords

我有一个程序使用 System.DirectoryServices.AccountManagement.PrincipalContext 验证用户在设置屏幕中输入的信息是否是域中的有效用户(计算机本身不在域)并对域的用户做一些操作。问题是我不希望用户每次运行程序时都需要输入他或她的密码,所以我想保存它,但我不希望将密码以纯文本形式存储在他们的 app.config 文件中。 PrincipalContext 需要一个纯文本密码,所以我不能像每个人都建议的那样进行加盐哈希来存储密码。

这是我做的

const byte[] mySalt = //It's a secret to everybody.
[global::System.Configuration.UserScopedSettingAttribute()]
public global::System.Net.NetworkCredential ServerLogin
{
    get
    {
        var tmp = ((global::System.Net.NetworkCredential)(this["ServerLogin"]));
        if(tmp != null)
            tmp.Password = new System.Text.ASCIIEncoding().GetString(ProtectedData.Unprotect(Convert.FromBase64String(tmp.Password), mySalt, DataProtectionScope.CurrentUser));
        return tmp;
    }
    set
    {
        var tmp = value;
        tmp.Password = Convert.ToBase64String(ProtectedData.Protect(new System.Text.ASCIIEncoding().GetBytes(tmp.Password), mySalt, DataProtectionScope.CurrentUser));
        this["ServerLogin"] = value;
    }
}

这是正确的做法还是有更好的方法?

编辑—— 这是根据大家的建议更新的版本

private MD5 md5 = MD5.Create();

[global::System.Configuration.UserScopedSettingAttribute()]
public global::System.Net.NetworkCredential ServerLogin
{
    get
    {
        var tmp = ((global::System.Net.NetworkCredential)(this["ServerLogin"]));
        if(tmp != null)
            tmp.Password = System.Text.Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(tmp.Password), md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(tmp.UserName.ToUpper())), DataProtectionScope.CurrentUser));
        return tmp;
    }
    set
    {
        var tmp = value;
        tmp.Password = Convert.ToBase64String(ProtectedData.Protect(System.Text.Encoding.UTF8.GetBytes(tmp.Password), md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(tmp.UserName.ToUpper())), DataProtectionScope.CurrentUser));
        this["ServerLogin"] = tmp;
    }
}

最佳答案

对于盐,我会对用户名进行转换(散列)而不是为所有人共享相同的盐。

对于这样的事情,我还会寻找一种方法来使现有 session 保持更长时间,而不是保存密码以创建新 session 。

关于c# - 无法将密码另存为哈希时该怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2273496/

相关文章:

c# - Asp.Net MVC 加密查询字符串

python - 将整数(最多 2^48)安全加密为最短的 URL 安全字符串

Django 密码生成器

java - 是否可以在地址栏中隐藏密码字段?

c# - 在 C# wpf 中的 slider 上添加直方图

c# - 无效的对象名称错误 - EntityFrameworkCore 2.0

c# - 将文件拖入富文本框以读取文件中的文本

c# - 在 .NET 中合并两个数组

node.js - Nodejs createDecipher,可以用两个不同的 key 解密相同的密文

java - 在 Android 中使用可绘制图标显示和隐藏密码