简体   繁体   中英

Calculate hmac value with base64 encode using sha256 python

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=

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='

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