我有一个程序使用 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/