大部分我已经在这个节目密码散列/盐渍密码比较感兴趣的课题。这不是我的用例。我需要从xml文件中读取散列/盐渍密码,然后使用它登录到Sql数据库。我需要从Windows服务中执行此操作。我首先不确定如何阅读XML文件中的条目,然后如何“解密”它?提取/解密散列/盐渍密码了XML文件的
的GenerateSaltForPassword和ComputePasswordHash功能直接来自This SO post:
private int GenerateSaltForPassword()
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] saltBytes = new byte[4];
rng.GetNonZeroBytes(saltBytes);
return (((int) saltBytes[0]) << 24) + (((int) saltBytes[1]) << 16) + (((int) saltBytes[2]) << 8) +
((int) saltBytes[3]);
}
private byte[] ComputePasswordHash(string password, int salt)
{
byte[] saltBytes = new byte[4];
saltBytes[0] = (byte) (salt >> 24);
saltBytes[1] = (byte) (salt >> 16);
saltBytes[2] = (byte) (salt >> 8);
saltBytes[3] = (byte) (salt);
byte[] passwordBytes = UTF8Encoding.UTF8.GetBytes(password);
Byte[] preHashed = new Byte[saltBytes.Length + passwordBytes.Length];
System.Buffer.BlockCopy(passwordBytes, 0, preHashed, 0, passwordBytes.Length);
System.Buffer.BlockCopy(saltBytes, 0, preHashed, passwordBytes.Length, saltBytes.Length);
SHA1 sha1 = SHA1.Create();
return sha1.ComputeHash(preHashed);
}
,并通过生成的XML文件:
private void btnSave_Click(object sender, System.EventArgs e)
{
int salt = GenerateSaltForPassword();
string fileName = System.IO.Path.Combine(Application.StartupPath, "alphaService.xml");
XDocument doc = new XDocument();
XElement xml = new XElement("Info",
new XElement("DatabaseServerName", txtServerName.Text),
new XElement("DatabaseUserName", txtDatabaseUserName.Text),
new XElement("DatabasePassword", ComputePasswordHash(txtDatabasePassword.Text, salt)),
new XElement("ServiceAccount", txtAccount.Text),
new XElement("ServicePassword", ComputePasswordHash(txtServicePassword.Text, salt)));
doc.Add(xml);
doc.Save(fileName);
}
如果我理解正确,您的要求,你不能。哈希是一种单向过程,意味着您不能(以编程方式)恢复(或解密)原始值。这就是它用于存储密码的原因。 –
我不明白。如果它用于存储密码,则必须有一种方法来使用该密码。我应该做什么?无论如何,我怎样才能从XML中提取这个值呢? – user2471435
读它很简单,但最终的结果是没用的。你最终会得到一个你不能用来连接的密码。读它,这样做:'的XDocument DOC = XDocument.Load(pathToXml “);字符串密码= doc.Descendants(” DatabasePassword“)FirstOrDefault()值;' –