找回密码
 加入
搜索
查看: 601|回复: 4

[网络通信] [已解决]HMAC_SHA256算法结果与python不一样?

[复制链接]
发表于 2021-12-25 16:36:24 | 显示全部楼层 |阅读模式
本帖最后由 oceanwind 于 2021-12-26 20:09 编辑

这两天在试腾讯云接口,以下为链接Hash HMAC - AutoIt Example Scripts - AutoIt Forums (autoitscript.com)的代码附轻微修改。
Local $sSecret = "SecretKey"
Local $sMessage = "AutoIt Rocks!!!"


ConsoleWrite("HMAC-SHA256: " & @TAB & @TAB & _HashHMAC("SHA512", $sMessage, $sSecret) & @CRLF)
ConsoleWrite("HMAC-SHA256: " & @TAB & @TAB & _HashHMAC("SHA256", $sMessage, $sSecret) & @CRLF)
ConsoleWrite("HMAC-SHA1: " & @TAB & @TAB & _HashHMAC("SHA1", $sMessage, $sSecret) & @CRLF)
ConsoleWrite("HMAC-SHA384: " & @TAB & @TAB & _HashHMAC("SHA384", $sMessage, $sSecret) & @CRLF)
ConsoleWrite("HMAC-MD5: " & @TAB & @TAB & _HashHMAC("MD5", $sMessage, $sSecret) & @CRLF)
ConsoleWrite("HMAC-RIPEMD160: " & @TAB &  _HashHMAC("RIPEMD160", $sMessage, $sSecret) & @CRLF)

Func _HashHMAC($sAlgorithm, $bData, $bKey, $bRaw_Output = False)
    Local $oHashHMACErrorHandler = ObjEvent("AutoIt.Error", "_HashHMACErrorHandler")
    Local $oHMAC = ObjCreate("System.Security.Cryptography.HMAC" & $sAlgorithm)
    If @error Then SetError(1, 0, "")
    $oHMAC.key = Binary($bKey)
    Local $bHash = $oHMAC.ComputeHash_2(Binary($bData))
    $rt = SetError(0, 0, $bRaw_Output ? $bHash : StringLower(StringMid($bHash, 3)))
    ;~ Return SetError(0, 0, $bRaw_Output ? $bHash : StringLower(StringMid($bHash, 3)))
    ;~
    $tlen = StringLen($rt)
    $hmac256str = ""
    For $i = 1 To $tlen - 1 Step 2
        ;~ ConsoleWrite($i & @CR)
        $hmac256str &= "\x" & StringMid($rt, $i, 2)
    Next
    Return $hmac256str
EndFunc   ;==>_HashHMAC
256结果如下:
HMAC-SHA256:        \x11\xb7\x5d\x84\x5a\x07\xfc\x5c\x0a\x6c\xc3\xdb\xdb\x9c\x5c\x53\xd3\x03\x41\x29\xe3\x39\x4f\x56\xa2\xf1\x66\x49\xb6\x1a\x5c\x54

以下为PYthon代码:
def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
key = "SecretKey"
data = "AutoIt Rocks!!!"
# secret_date = sign(("TC3" + secret_key).encode("utf-8"), date)
secret_date1 = sign(key.encode("utf-8"), data)
# print('----------16----------("TC3" + secret_key).encode("utf-8")-------------')
# print(("TC3" + secret_key).encode("utf-8"))
print('----------18----------secret_date-------------')
# print(secret_date)
print(secret_date1)
PYthon代码运行结果如下 :

b'\xf1\xcbMQ\x8a\x0e\xda\x9d\\\xbb\xfd\xb7\x85\t\x83\xf1\xe6\x03\xee\xaeHN\xde\xa7nM\xd8\xd8\xde\xb5Un'
这个python结果与au3结果有差异,python有些字符没转成asc码,有朋友知道怎么回事吗?
发表于 2021-12-26 18:27:15 | 显示全部楼层
我也遇到过,没解决
 楼主| 发表于 2021-12-26 18:35:50 | 显示全部楼层
看错版了,应该发在提问版块。
 楼主| 发表于 2021-12-26 20:07:36 | 显示全部楼层
发表于 2021-12-27 08:38:57 | 显示全部楼层

学习一下了!谢谢
您需要登录后才可以回帖 登录 | 加入

本版积分规则

QQ|手机版|小黑屋|AUTOIT CN ( 鲁ICP备19019924号-1 )谷歌 百度

GMT+8, 2024-5-3 21:05 , Processed in 0.072335 second(s), 19 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表