【问题标题】:MD5CryptoServiceProvider and HashbytesMD5CryptoServiceProvider 和哈希字节
【发布时间】:2012-03-26 11:32:27
【问题描述】:
如何让 MD5CryptoServiceProvider 和 Hashbytes 返回相同的 MD5 值?
【问题讨论】:
-
我实际上并不理解这个问题,但是使用msdn.microsoft.com/en-us/library/… 中的示例并调用select HASHBYTES('md5', 'Hello World!') 返回相同的值,我认为这可能与转换为十六进制有关:for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); }
标签:
.net
sql-server
tsql
hash
md5
【解决方案1】:
也许这会有所帮助。
Public Function ComputeMD5Hash(ByVal strPlainText As String, Optional ByVal bytSalt() As Byte = Nothing) As String
Try
Dim bytPlainText As Byte() = Encoding.UTF8.GetBytes(strPlainText)
Dim hash As HashAlgorithm = New MD5CryptoServiceProvider()
If bytSalt Is Nothing Then
Dim rand As New Random
Dim intSaltSize As Integer = rand.Next(intMinSalt, intMaxSalt)
bytSalt = New Byte(intSaltSize - 1) {}
Dim rng As New RNGCryptoServiceProvider
rng.GetNonZeroBytes(bytSalt)
End If
Dim bytPlainTextWithSalt() As Byte = New Byte(bytPlainText.Length + bytSalt.Length - 1) {}
bytPlainTextWithSalt = ConcatBytes(bytPlainText, bytSalt)
Dim bytHash As Byte() = hash.ComputeHash(bytPlainTextWithSalt)
Dim bytHashWithSalt() As Byte = New Byte(bytHash.Length + bytSalt.Length - 1) {}
bytHashWithSalt = ConcatBytes(bytHash, bytSalt)
Return Convert.ToBase64String(bytHashWithSalt)
Catch ex As Exception
Return String.Format(strTextErrorString, ex.Message)
End Try
End Function
'Verify a string against a hash generated with the ComputeMD5Hash function above.
Public Function VerifyHash(ByVal strPlainText As String, ByVal strHashValue As String) As Boolean
Try
Dim bytWithSalt As Byte() = Convert.FromBase64String(strHashValue)
If bytWithSalt.Length < intHashSize Then Return False
Dim bytSalt() As Byte = New Byte(bytWithSalt.Length - intHashSize - 1) {}
Array.Copy(bytWithSalt, intHashSize, bytSalt, 0, bytWithSalt.Length - intHashSize)
Dim strExpectedHashString As String = ComputeMD5Hash(strPlainText, bytSalt)
Return strHashValue.Equals(strExpectedHashString)
Catch ex As Exception
Return Nothing
End Try
End Function
'Simple function to concatenate two byte arrays.
Private Function ConcatBytes(ByVal bytA() As Byte, ByVal bytB() As Byte) As Byte()
Try
Dim bytX() As Byte = New Byte(((bytA.Length + bytB.Length)) - 1) {}
Array.Copy(bytA, bytX, bytA.Length)
Array.Copy(bytB, 0, bytX, bytA.Length, bytB.Length)
Return bytX
Catch ex As Exception
Return Nothing
End Try
End Function
'A function to convert a string into a 32 byte key.
Private Function ConvertKeyToBytes(ByVal strKey As String) As Byte()
Try
Dim intLength As Integer = strKey.Length
If intLength < intKeySize Then
strKey &= Strings.StrDup(intKeySize - intLength, chrKeyFill)
Else
strKey = strKey.Substring(0, intKeySize)
End If
Return Encoding.UTF8.GetBytes(strKey)
Catch ex As Exception
Return Nothing
End Try
End Function