Calculate hmac value with base64 encode using sha256 python

I am trying to convert PHP code to python language.

php function calculates hmac value using sha256 and base64 encoding.

My Php function:

<?php

define('SHOPIFY_APP_SECRET', 'some_key');

function verify_webhook($data)
{
$calculated_hmac = base64_encode(hash_hmac('sha256', $data, 
SHOPIFY_APP_SECRET, true));
echo $calculated_hmac;
}

$data = "some_data";
$verified = verify_webhook($data);
?>

      

My Python function:

import base64
import hmac
import binascii
from hashlib import sha256

API_SECRET_KEY = "some_key"
data = "some_data"

def verify_webhook():
    dig = hmac.new(
        API_SECRET_KEY,
        msg=data,
        digestmod=sha256
        ).digest()
    calculated_hmac = base64.b64encode(bytes(binascii.hexlify(dig)))
    print(calculated_hmac)

verify_webhook()

      

I have different outputs, even I have the same key and data. I still don't know what I am missing here. please, help!

Python output:

YWM3NjlhMDZjMmViMzdmM2E3YjhiZGY4NjhkNTZhOGZhMDgzZDM4MGM1OTkyZTM4YjA5MDNkMDEwNGEwMzJjMA ==

Php output:

N7JyAyKocoDx / Opx36nGqAuUKdyGH + ROX + J5AJgQ + / r =

+3


source to share


1 answer


I was able to map your php output using Python 3:



>>> dig = hmac.new( bytes(API_SECRET_KEY,'ascii'), 
                    msg=bytes(data, 'ascii'), digestmod=sha256 )
>>> dig.digest()
b'7\xb2r\x03"\xa8r\x80\xf1\xfc\xeaq\xdf\xa9\xc6\xa8\x0b\x94)\xdc\x86\x1f\xe4N_\xe2y\x00\x98\x10\xfb\xf8'
>>> base64.b64encode(dig.digest())
b'N7JyAyKocoDx/Opx36nGqAuUKdyGH+ROX+J5AJgQ+/g='

      

0


source







All Articles