我正在尝试创建测试输入的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);
答案 0 :(得分:0)
在x-date
和salt
之后要签名的字符串的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
更改这些,您应该得到相同的结果