[英]Calculate hmac value with base64 encode using sha256 python
I'm trying to transform a php code into python language. 我正在尝试将PHP代码转换为python语言。
the php function calculates the hmac value using sha256 and base64 encoding. php函数使用sha256和base64编码计算hmac值。
My Php function: 我的Php功能:
<?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: 我的Python函数:
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: Python输出:
YWM3NjlhMDZjMmViMzdmM2E3YjhiZGY4NjhkNTZhOGZhMDgzZDM4MGM1OTkyZTM4YjA5MDNkMDEwNGEwMzJjMA== YWM3NjlhMDZjMmViMzdmM2E3YjhiZGY4NjhkNTZhOGZhMDgzZDM4MGM1OTkyZTM4YjA5MDNkMDEwNGEwMzJjMA ==
Php output: Php输出:
N7JyAyKocoDx/Opx36nGqAuUKdyGH+ROX+J5AJgQ+/g= N7JyAyKocoDx / Opx36nGqAuUKdyGH + ROX + J5AJgQ + /克=
I was able to match your php output using Python 3: 我能够使用Python 3匹配您的PHP输出:
>>> 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='
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.