Apply HMAC SHA-512 algorithm using secret key in python

I'm trying to apply the HMAC SHA-512 algorithm using a secret key in python, but I can't find the correct way to sign.

I was able to accomplish with nodejs and C # but not for python

in nodejs

return crypto.createHmac('sha512', new Buffer(secretString, 'base64')).update(new Buffer(stringToSign)).digest('base64');

      

in c #

byte[] secretkeyBytes = Encoding.UTF8.GetBytes(apiSecret);
byte[] inputBytes = Encoding.UTF8.GetBytes(stringToSign);
using (var hmac = new HMACSHA512(secretkeyBytes))
{
  byte[] hashValue = hmac.ComputeHash(inputBytes);
  signature = System.Convert.ToBase64String(hashValue);
}

      

but in python I don't understand how to do this. I've already tried:

b_secret_string=base64.b64encode(secret_string.encode('utf-8'))
hash = hmac.new(base64.b64encode(b_secret_string),'',sha512)
hash.update(string_to_sign.encode('utf-8'))
signature = base64.b64encode(hash.digest())

      

and

hashed = hmac.new(str(secret_string.encode('utf-8')),'',sha512)
hashed.update(string_to_sign.encode('utf-8'))
signature = base64.b64encode(hashed.digest())

      

but it doesn't work. If possible, can someone give me some light? I really appreciate it.

UPDATE:

Also tried the following:

string_to_sign = string_to_sign.encode('utf-8')
secret_string = secret_string.encode('utf-8')
hash = hmac.new(secret_string, string_to_sign, hashlib.sha512)
signature = base64.b64encode(hash.digest())

      

tried to use hexdigest () too:

signature = base64.b64encode(hash.hexdigest())

      

if anyone wants to test it. Should return the same as this code in nodejs.

var crypto = require('crypto');

a = new Buffer('PRIVATE_KEY', 'base64');
hash = crypto.createHmac('sha512', a)
stringToSign = 'Qaru Funtime';
hash.update(new Buffer(stringToSign));
console.log(hash.digest('base64'));

$ node example.js
ugmH0VdttdAxGdpzNJnaNn1KlVS4wBzoK//dsPuvK65Zsl8FgT+3aLGnsEubThlv5/3chfyMmsUH//LdS1MXqg==

      

+3


source to share


2 answers


I found a way to do the same in python. Answering here in case anyone moves on to the same issue in the future.



    hmac_key = base64.b64decode(secret_string)
    signature = hmac.new(hmac_key, string_to_sign, hashlib.sha512)
    signature_b64 = signature.digest().encode('base64')
    signature_lines = signature_b64.splitlines()
    signature_b64 = ''.join(signature_lines)

      

+3


source


What about:



import hashlib    
print hashlib.sha512('some string').hexdigest()

      

+1


source







All Articles