HMAC SHA-1 签名未按预期提供正确的输出

HMAC SHA-1 Signature not giving correct output as expected

我正在尝试创建测试输入的 HMAC-SHA1 签名,但它没有给出预期的结果。代码在 JS 中进行了测试,它给出了正确的输出,但在 python 中却没有。输出的预期签名是

uAXlaiKQ9pdfD12xCPFuys=

但是给予

RTXUTiUzIikVXonWFYWrUg5v0m4=

from base64 import b64encode
import hmac
import hashlib

user = 'Test'
key = b'Test'
date = 'Thu, 25 Aug 2016 07:47:00 GMT'
salt = 'fqLwoha51ESIWC5'
requestLine = "GET /user HTTP/1.1"
stringtosign = requestLine+'\n'+'x-date:'+date+'\nsalt:'+salt
signature = b64encode(hmac.new(key, bytes(stringtosign.encode('utf-8')), hashlib.sha1).digest()).decode().rstrip()
print(signature)

JS代码

var crypto = require("crypto");
var date = "Thu, 25 Aug 2016 07:47:00 GMT";
var username="Test";
var secret = "Test";
var requestline = "GET /user HTTP/1.1";
var salt = "fqLwoha51ESIWC5";
var stringToSign = requestline + "\n" + "x-date: " + date + "\n" + "salt: " + salt;
var requestline = "GET /user HTTP/1.1";
var encodedSignature = crypto.createHmac("sha1", secret).update(stringToSign).digest("base64");
var hmacAuth = 'hmac username="' + username + '",algorithm="hmac-sha1",headers="request-line x-date salt",signature="' + encodedSignature + '"';
console.log(encodedSignature);

您在 x-datesalt 之后签名的字符串的 javascript 版本中有额外的空格(或 Python 中缺少空格)。每个字符在这里都很重要:

'GET /user/tuid=352745859?siteid=80001 HTTP/1.1\nx-date:Thu, 25 Aug 2016 07:47:00 GMT\nsalt:fqLwoha51ESIWC5'
'GET /user/tuid=352745859?siteid=80001 HTTP/1.1\nx-date: Thu, 25 Aug 2016 07:47:00 GMT\nsalt: fqLwoha51ESIWC5

改变这些,你应该得到相同的结果