盐(Salt)是什么?就是一个随机生成的字符串。我们将盐与原始密码连接(concat)在一起(放在前面或后面都可以),然后将concat后的字符串加密。采用这种方式加密密码,查表法就不灵了(因为盐是随机生成的)。

(四) 在.NET中的实现
在.NET中,生成盐可以使用RNGCryptoServiceProvider类,当然也可以使用GUID。哈希函数的算法我们可以使用SHA(Secure Hash Algorithm)家族算法,当然哈希函数的算法有很多,比如你也可以采用MD5。这里顺便提一下,美国政府以前广泛采用SHA-1算法,在2005年被我国山东大学的王小云教授发现了安全漏洞,所以现在比较常用SHA-1加长的变种,比如SHA-256。在.NET中,可以使用SHA256Managed类。
下面来看一段代码演示如何在.NET中实现给密码加盐加密。加密后的密码保存在MySQL数据库中。

下面的代码演示如何注册一个新帐户。盐的生成可以使用新Guid,也可以使用RNGCryptoServiceProvider 类。将byte[]转换为string,可以使用Base64String,也可以使用下面的ToHexString方法。
protected void ButtonRegister_Click(object sender, EventArgs e)
{
string username = TextBoxUserName.Text;
string password = TextBoxPassword.Text;
// random salt
string salt = Guid.NewGuid().ToString();
// 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();
}
下面的代码演示了如何检验登录用户的密码是否正确。首先检验用户名是否存在,如果存在,获得该用户的盐,然后用该盐和用户输入的密码来计算哈希值,并和数据库中的哈希值进行比较。










