简体   繁体   中英

HMAC SHA256 - Php To Python

PHP CODE SNIPPET

$timestamp    = time();
$appID        = 1;
$key          = '5nF6Ai4ykPY=';
$secret       = '0a75...';

$sign = "key:".$key."id:".$appID.":timestamp:".$timestamp;
$authtoken = rawurlencode(base64_encode(hash_hmac('sha256', $sign, $secret, true)));  
echo $authtoken;
echo $timestamp;

got an encoded string with the value:

wlhiAYAxcUsH1eOx66cJwg8G1ROAbagEqVBo6msBNF8%3D

PYTHON CODE SNIPPET

import hmac
import hashlib
import time

timestamp = time.time()
appid = 60
key = "scas11eABXs="
secret = "N4Rlq....=="

sign = f"key:{key}id:{appid}:timestamp:{int(timestamp)}"


signature = hmac.new(secret.encode(), sign.encode(), hashlib.sha256).hexdigest()
print(signature)

got this value

8a85743f3b1704096b3fe5018de2ff133eb2bac63c93fa8ff26cca328ab83e39

The value i got from the python is way too different from the php, i mean it almost like hexadecimal where as the value from the php code is something different.

Can anyone please help and convert this php code snippet to python so i can get almost similar values.

These two are the exact same between Python and PHP. The key part to observe is that in Python the hexdigest() can be translated to bin2hex() in PHP.

Below I set the same values for the timestamp, appid, key, and secret. When the timestamp changes so will the underlying values. You should always use fixed data that will not change (encryption keys, ephemeral data, etc) when comparing algorithms.

Python

import hmac
import hashlib
import time

timestamp = int(1617543014)
appid = 60
key = "scas11eABXs="
secret = "N4Rlq=="

sign = "key:" + key +"id:" + str(appid) + ":timestamp:" + str(timestamp)

signature = hmac.new(secret.encode(), sign.encode(), hashlib.sha256).hexdigest()
print(signature)

PHP

<?php
$timestamp    = 1617543014;
$appID        = 60;
$key          = 'scas11eABXs=';
$secret       = 'N4Rlq==';

$sign = "key:".$key."id:".$appID.":timestamp:".$timestamp;
$authtoken = bin2hex(hash_hmac('sha256', $sign, $secret, true));
echo $authtoken;

Both produce:

de409427af722c4cfbcb7bd280cd33ace71f33d29d4fc54182ce2a3ee758712e

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