hmacsha1输出vb.net和python之间的十六进制字符串不同 [英] hmacsha1 output hex strings different between vb.net and python

查看:149
本文介绍了hmacsha1输出vb.net和python之间的十六进制字符串不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在vb.net中使用HMACSHA1在Webrequest中进行消息身份验证.从服务器收到(403)Forbidden"消息后,我决定查看我在VB中的签名计算是否与给出的示例python代码中的计算匹配.十六进制的字符串曾经如此相似,但并不完全相同.请注意py签名中的两个额外0,但不在下面由*表示的vb中.我假设py示例代码是好的并且返回正确的输出,所以使vb匹配可能会解决我的问题,那么diff是什么?

I am using HMACSHA1 in vb.net for message authentication in a webrequest. After getting a "(403) Forbidden" message from the server, I decided to see if my signature calculation in VB matched the calculation in the sample python code I was given. The hex strings were ever so similar, but not quite exactly the same. Note the two extra 0s in the py signature but not in the vb indicated by * below. I'm assuming the py example code is good and returns correct output, so getting the vb to match may solve my problem, so what is the diff?

vb sig returns: a729e16e5c4a444a302a72c3d44544fe58aa90
py sig returns: a729e16e5c4a444a3002a72c3d44544f0e58aa90
.................................*..............*.......

这是py代码,基于( http://apiaxle.com/docs/signing-requests/):

Here is py code, based on pseudo-code at (http://apiaxle.com/docs/signing-requests/):

import hmac
from hashlib import sha1
from time import time
key =    'ba1d92...'    #32 bit hex number (string)
secret = '2a3759...'    #128 bit hex number (string)
curr_time = str(int(time()))
concat = curr_time+key
# hmac expects byte, so convert
concatB = (concat).encode('utf-8')
secretB = secret.encode('utf-8')
h1 = hmac.new(secretB, concatB, sha1)
# h1 is byte, so convert to hex
api_sig = h1.hexdigest()

这是vb代码:

Dim uTime As Integer = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds
Dim api_sig As String = ""
Using myhmac As New HMACSHA1(System.Text.Encoding.UTF8.GetBytes(secret))
  Dim hashValue As Byte() = myhmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(String.Concat(uTime.ToString, key)))
  Dim i As Integer
  For i = 0 To (hashValue.Length - 1)
    api_sig = api_sig + Hex(hashValue(i))
  Next i

推荐答案

您的VB输出未正确填充小于16的十六进制数字;字节0x02仅表示为2,而不是02,0x0E字节包括为e,而不是0e.

Your VB output doesn't correctly pad the hex digits for values smaller than 16; the byte 0x02 is represented as just 2, not 02, and the 0x0E byte is included as e, not 0e.

您需要添加.PadLeft()通话:

api_sig = api_sig + Hex(hashValue(i)).PadLeft(2, "0"c)

或使用字符串格式:

api_sig = api_sig + String.Format("{0:X2}", hashValue(i))

这篇关于hmacsha1输出vb.net和python之间的十六进制字符串不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆