CryptoJS和VB的不同HMAC

时间:2018-03-13 15:53:16

标签: javascript cryptography hmac basic

我必须在Visual Basic中生成HMACSHA256。问题是,我没有收到正确的HMAC并得到不同的HMACS

InputData = Test \ nTest \ n \ nTest
secret = c39ff802b43a01c08ea759750c41d7d4bac6b1b884b3864d640b577cf1dca21a

HMACa = 330c55857e5ff197a407a9dcd41bbf03a2e8de0b351aba9a405139919b3cae57
HMACb = f701ea7028f20df11a52bee297a336de212655a8bad01d848eeaa87d0f76ee5e

JS(CryptoJS) - > HMACa(直接测试)
PY - > HMACa(直接测试)

JS(jsSHA) - > HMACb(测试时间:liavaag.org/English/SHA-Generator/HMAC/)
C#/ VB - > HMACb(直接测试)

为什么我会得到不同的HMAC,我该怎么做才能在VB / C中获得HMACa?

这是我的VB代码:

Sub Main()
    Dim sToHash As String = "Test\nTest\n\nTest"
    Dim sKey As String = "c39ff802b43a01c08ea759750c41d7d4bac6b1b884b3864d640b577cf1dca21a"
    Console.WriteLine(getHMAC(sToHash, sKey))
End Sub

Function getHMAC(ToHash As String, SecretKey As String) As String
    Dim aoText() As Byte = System.Text.Encoding.UTF8.GetBytes(ToHash)
    Dim aoKey() As Byte = System.Text.Encoding.UTF8.GetBytes(SecretKey)

    Using oHmac As New System.Security.Cryptography.HMACSHA256(aoKey)
        Dim sHash As Byte() = oHmac.ComputeHash(aoText)
        Return ByteToString(sHash)
    End Using
End Function

Function ByteToString(buff As Byte()) As String
    Dim getbinary As String = ""
    For i As Integer = 0 To buff.Length - 1
        getbinary += buff(i).ToString("X2")
    Next
    Return (getbinary).ToLower
End Function

1 个答案:

答案 0 :(得分:0)

比预期容易得多。 VB / C#无法将'\ n'编码为NewLine。在World of VisualBasic中,您必须编写vbLf来指示字符串中的NewLine

现在正确的InputString: “测试”+ vbLf +“测试”+ vbLf + vbLf +“测试”

结果=> HMACa

非常感谢