简体   繁体   中英

Generate Hmac in Javascript from python code

I am trying to generate an hmac hash in javascript.

here is some python code I want to replicate in Javascript:

mac = hmac.new("33fsfsdgvwrg2g223f4f42gf4f34f43f", digestmod=hashlib.sha1)
mac.update(method)
mac.update(url)
mac.update(data)
mac.update(str(timestamp))

r = requests.request(method, url, data=data, headers={
    'Content-Type': 'application/json',
    'Authorization': " signature="'mac.hexdigest()'" ",
})

This is what I have so far, and it does not seem to be what I need:

var message = "shah me";
var secret = "33fsfsdgvwrg2g223f4f42gf4f34f43f";
var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64);

var shaObj = new jsSHA('shah me', "ASCII");
var jssha = shaObj.getHMAC('33fsfsdgvwrg2g223f4f42gf4f34f43f', "ASCII", "SHA-1", "B64");

It looks like your "current solution" is just a copy paste of jsSHA, CryptoJS and OpenSSL libraries giving different results with your key substituted in.

Anyways, you don't need to use both CryptoJS and jsSHA. You should pick one and stick with it.

According to the docs , the python mac.update function is equivalent to appending data to the message. I believe this is the key to your problems, since neither CryptoJS nor jsSHA have an equivalent update function but instead expect you to have the full message to begin with.

The following Python code and the Javascript code that follows it are equivalent:

import hashlib
import hmac

method = 'method'
url = 'url'
data = 'data'
timestamp = 'timestamp'

mac = hmac.new("33fsfsdgvwrg2g223f4f42gf4f34f43f", digestmod=hashlib.sha1)
mac.update(method)
mac.update(url)
mac.update(data)
mac.update(timestamp)

print mac.hexdigest()

Here is the Javascript:

<script src="sha.js"></script>
<script>
  var secret = '33fsfsdgvwrg2g223f4f42gf4f34f43f';
  var message = 'methodurldatatimestamp';
  var shaObj = new jsSHA(message, "ASCII");
  document.write(shaObj.getHMAC(secret, "ASCII", "SHA-1", "HEX"));
</script>

Note that the Javascript code puts the full message ( 'methodurldatatimestamp' ) in the jsSHA constructor. I believe this is the key to your problem. Hope this helps!

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