Sco*_*ain 8 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是正确的做法还是有更好的方法?
编辑 - 这是一个基于每个人的建议的更新版本
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;
}
}
Run Code Online (Sandbox Code Playgroud)
new System.Text.ASCIIEncoding()你不应该写作,而应该写作System.Text.Encoding.ASCII。
另外,我建议使用 UTF8 代替。
除此之外,你的代码看起来相当不错。
| 归档时间: |
|
| 查看次数: |
897 次 |
| 最近记录: |