3

I'm trying to transform a php code into python language.

the php function calculates the 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 got different outputs even I have the same key and data. I still don't know what I'm missing here. please help!

Python output:

YWM3NjlhMDZjMmViMzdmM2E3YjhiZGY4NjhkNTZhOGZhMDgzZDM4MGM1OTkyZTM4YjA5MDNkMDEwNGEwMzJjMA==

Php output:

N7JyAyKocoDx/Opx36nGqAuUKdyGH+ROX+J5AJgQ+/g=

0

1 Answer 1

3

I was able to match 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='
Sign up to request clarification or add additional context in comments.

1 Comment

great! it works also on python2.7, I only changed bytes(API_SECRET_KEY,'ascii') to bytes(API_SECRET_KEY). thank you very much for help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.