时间:2021-07-01 10:21:17 帮助过:2人阅读
// random salt
// you can also use RNGCryptoServiceProvider class
//System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
//byte[] saltBytes = new byte[36];
//rng.GetBytes(saltBytes);
//string salt = Convert.ToBase64String(saltBytes);
//string salt = ToHexString(saltBytes);
byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
byte[] hashBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);
string hashString = Convert.ToBase64String(hashBytes);
// you can also use ToHexString to convert byte[] to string
//string hashString = ToHexString(hashBytes);
var db = new TestEntities();
usercredential newRecord = usercredential.Createusercredential(username, hashString, salt);
db.usercredentials.AddObject(newRecord);
db.SaveChanges();
}
string ToHexString(byte[] bytes)
{
var hex = new StringBuilder();
foreach (byte b in bytes)
{
hex.AppendFormat("{0:x2}", b);
}
return hex.ToString();
}
下面的代码演示了如何检验登录用户的密码是否正确。首先检验用户名是否存在,如果存在,获得该用户的盐,然后用该盐和用户输入的密码来计算哈希值,并和数据库中的哈希值进行比较。
总结:单单使用哈希函数来为密码加密是不够的,需要为密码加盐来提高安全性,盐的长度不能过短,并且盐的产生应该是随机的。
Web安全--使用Salt + Hash将密码加密后再存储进数据库
标签: