具有基本安全性的密码存储过程非常简单:
- 用盐散列密码
- 为每个用户/密码使用不同的盐
- 将带有哈希密码的盐存储在数据库中
- 当他们尝试登录时,请通过相同的方法运行尝试的PW。比较结果。
如果他们输入了正确的密码,则散列的PW将匹配。散列可以保护用户免受攻击,也可以保护看门人
members在显示表格的屏幕旁走动。
撒盐和散列PW
' salt size is 32 (0-31Private Const SaltSize As Integer = 31...Dim dbPW As String = TextBox1.TextDim dbSalt = CreateNewSalt(SaltSize)' eg: "dsEGWpJpwfAOvdRZyUo9rA=="Dim SaltedPWHash As String = GetSaltedHash(dbPW, dbSalt)' examples:' using SHA256: bbKN8wYYgoZmNaG3IsQ2DPS2ZPIOnenl6i5NwUmrGmo=' using SHA512: ' 0vqZWBIbOlyzL25l9iWk51CxxJTiEM6QUZEH1ph+/aNp+lk4Yf8NYv8RLhYtbqCNpOqO3y8BmM+0YWtbAhE+RA=="
将PW哈希和盐存储为用户记录的一部分。盐不是秘密的,但是当用户更改密码时可以更改盐。
比较登录尝试
' check if PW entered equals DBDim pwTry = TextBox2.Text' hash the login attempt using the salt stored in the DBDim pwLogin = GetSaltedHash(pwTry, dbSalt)' compare the hash of what they entered to whats in the DB:If String.Compare(SaltedPWHash, pwLogin, False) = 0 Then ' okay! Console.Beep()End If
如果用户输入相同的PW,则应产生相同的哈希,就这么简单。哈希码并不那么复杂:
哈希方法
Private Function GetSaltedHash(pw As String, salt As String) As String Dim tmp As String = pw & salt ' or SHA512Managed Using hash As HashAlgorithm = New SHA256Managed() ' convert pw+salt to bytes: Dim saltyPW = Encoding.UTF8.GetBytes(tmp) ' hash the pw+salt bytes: Dim hBytes = hash.ComputeHash(saltyPW) ' return a B64 string so it can be saved as text Return Convert.Tobase64String(hBytes) End UsingEnd FunctionPrivate Function CreateNewSalt(size As Integer) As String ' use the crypto random number generator to create ' a new random salt Using rng As New RNGCryptoServiceProvider ' dont allow very small salt Dim data(If(size < 7, 7, size)) As Byte ' fill the array rng.GetBytes(data) ' convert to B64 for saving as text Return Convert.Tobase64String(data) End UsingEnd Function
- 使用诸如GUID(
System.Guid.NewGuid.ToString
)之类的东西作为引诱对象是很诱人的,但是使用密码随机数生成器并不难。 - 与哈希密码一样,由于编码,返回字符串更长。
- 每次用户更改密码时都要创建一个新的盐。不要使用全局盐,它会达到目的。
- 您还可以多次对PW进行哈希处理。关键部分是要在被攻击时花很长时间才能尝试所有各种组合。
- 这些功能是
Shared
/static
类成员的理想人选。
还要注意,肯尼斯(Kenneth)链接的文章值得一读。
请注意,本文提到的 The salt shouldbe stored in the user account table alongside the hash
这并不意味着您必须
Salt在数据库中有一列。您可以在链接的文章中看到以下内容:
Dim dbPW As String = TextBox1.TextDim dbSalt = CreateNewSalt(SaltSize)' get the salted PW hashDim SaltedPWHash As String = GetSaltedHash(dbPW, dbSalt)' store salt with the hash:SaltedPWHash = String.Format("{0}:{1}", dbSalt, dbPW)' salt + ":" + hashed PW now ready to store in the db要从哈希密码中分离出盐:
Dim SaltAndPWHash = rdr.Item("PWHash").ToString()Dim split = SaltAndPWHash.Split(":"c) ' split on ":"Dim Salt = split(0)' element(0) == saltDim StoredPWHash = split(1) ' element(1) == hashed PW您需要两个部分:在对PW中的尝试登录进行哈希处理之后,将其与进行比较
split(1)。



