Various HMAC_SHA256 functions in classic ASP gives different results

こ雲淡風輕ζ 提交于 2019-12-01 19:07:09

Check out the following example.

The only requirement with this approach is Microsoft .Net Framework 2.0 (preinstalled starting from Windows Server 2003 R2) to use Com Interops.

I tried to be descriptive in the comments but feel free to ask questions about it.

'Returns Byte(), UTF-8 bytes of unicode string
Function Utf8Bytes(text)
    With Server.CreateObject("System.Text.UTF8Encoding")
        Utf8Bytes = .GetBytes_4(text)
    End With
End Function

'Returns String, sequential hexadecimal digits per byte
'data As Byte()
Function BinToHex(data)
    With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
        .dataType = "bin.hex"
        .nodeTypedValue = data
        BinToHex = .text
    End With
End Function

'Returns Byte(), a keyed hash generated using SHA256 method
'data As String, key As Byte()
Function HashHmacSha256(data, key)
    With Server.CreateObject("System.Security.Cryptography.HMACSHA256")
        .Key = key
        HashHmacSha256 = .ComputeHash_2(UTF8Bytes(data))
    End With
End Function

'Returns Byte(), of a packed hexadecimal string
'instead of PHP's pack('H*'
Function HexToBin(data)
    With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
        .dataType = "bin.hex"
        .text = data
        HexToBin = .nodeTypedValue
    End With
End Function

packed_secret = HexToBin("1234567890ABCDEF")
message = "stackoverflow"
binary_hash = HashHmacSha256(message, packed_secret)
string_hash = BinToHex(binary_hash)

Response.Write string_hash
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!