MD5CryptoServiceProvider和Hashbytes

时间:2012-03-08 23:48:58

标签: .net sql-server tsql hash md5

如何让MD5CryptoServiceProvider和Hashbytes返回相同的MD5值?

1 个答案:

答案 0 :(得分: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