Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply HMAC SHA-512 algorithm using a secret key in python

I am trying to Apply HMAC SHA-512 algorithm using a secret key in python but I am not finding the correct way to sign.

I was able to do using 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 am not figuring a way to do that. I 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 is not working. If possible can someone give me a light? I really appreciate it.

UPDATE:

Also tried with 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 using hexdigest() too:

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

if someone 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 = 'Stack OverFlow Funtime';
hash.update(new Buffer(stringToSign));
console.log(hash.digest('base64'));

$ node example.js
ugmH0VdttdAxGdpzNJnaNn1KlVS4wBzoK//dsPuvK65Zsl8FgT+3aLGnsEubThlv5/3chfyMmsUH//LdS1MXqg==
like image 231
Renan Vicente Avatar asked Sep 25 '26 15:09

Renan Vicente


2 Answers

I found a way to do the same in python. Answering here if someone pass for the same issue in 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)
like image 181
Renan Vicente Avatar answered Sep 27 '26 04:09

Renan Vicente


How about:

import hashlib    
print hashlib.sha512('some string').hexdigest()
like image 20
Ionut Hulub Avatar answered Sep 27 '26 03:09

Ionut Hulub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!