简体   繁体   中英

HMAC SHA-1 Signature not giving correct output as expected

I am trying to create a HMAC-SHA1 signature of a test input but it isn't giving the result as expected. Code is tested in JS which gives a correct output but in python it doesn't. The expected signature of the output is

uAXlaiKQ9pdfD12xCPFuys=

But giving

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 Code

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);

You have extra spaces in the javascript version (or missing spaces in the Python) of the string you are signing after x-date and salt . Every character counts here:

'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

Change these and you should get the same result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM