Most of the topics I have read on this show comparing a password to a hashed/salted password. That is not my use case. I need to read a hashed/salted password out of an xml file and then use that to log into a Sql database. I will need to do this from a Windows Service. I am first unsure how to read that entry in the XML file and then how to "decrypt" it?
The GenerateSaltForPassword and ComputePasswordHash functions come directly from 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);
}
And the XML file is generated by:
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);
}