// 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();
}
下面的代码演示了如何检验登录用户的密码是否正确。首先检验用户名是否存在,如果存在,获得该用户的盐,然后用该盐和用户输入的密码来计算哈希值,并和数据库中的哈希值进行比较。
复制代码 代码如下:
protected void ButtonSignIn_Click(object sender, EventArgs e)
{
string username = TextBoxUserName.Text;
string password = TextBoxPassword.Text;
var db = new TestEntities();
usercredential record = db.usercredentials.Where(x => string.Compare(x.UserName, username, true) == 0).FirstOrDefault();
if (record == default(usercredential))
{
throw new ApplicationException("invalid user name and password");
}
string salt = record.Salt;
byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
byte[] hashBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);
string hashString = Convert.ToBase64String(hashBytes);
if (hashString == record.PasswordHash)
{
// user login successfully
}
else
{
throw new ApplicationException("invalid user name and password");
}
}
总结:单单使用哈希函数来为密码加密是不够的,需要为密码加盐来提高安全性,盐的长度不能过短,并且盐的产生应该是随机的。
您可能感兴趣的文章: