100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > php hash hmac 优势 PHP hash_hmac与Python hmac

php hash hmac 优势 PHP hash_hmac与Python hmac

时间:2024-06-23 23:51:09

相关推荐

php hash hmac 优势 PHP hash_hmac与Python hmac

今天为俺开发钉钉群自定义机器人ding-bot(PHP)增加签名支持,参考官方文档钉钉开发文档

签名机制如下:

#python 3.8

import time

import hmac

import hashlib

import base64

import urllib.parse

timestamp = str(round(time.time() * 1000))

secret = 'this is secret'

secret_enc = secret.encode('utf-8')

string_to_sign = '{}\n{}'.format(timestamp, secret)

string_to_sign_enc = string_to_sign.encode('utf-8')

hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()

sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

print(timestamp)

print(sign)

示例加密代码是python hmac

hmac.new(key, msg=None, digestmod=None)

key 使用的密钥

msg要进行哈希运行的消息

digestmod哈希算法 参考:/project/explore-python/Standard-Modules/hmac.html

与之对应的是php hash_hmac

hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )

$algo哈希算法名称,例如:"md5","sha256","sha1" 等。 如何获取受支持的算法清单,请参见hash_algos()

$data 要进行哈希运行的消息

$key使用的密钥

$raw_output设置为TRUE输出原始二进制数据, 设置为FALSE输出小写 16 进制字符串

因此PHP实现以上签名如下:

$timestamp = time()*1000;

$secret = 'this is secret';

$stringToSign = $timestamp."\n".$secret;

$hmacCode = hash_hmac('sha256',$stringToSign,$secret,true);

$sign = urlencode(base64_encode($hmacCode));

var_dump($timestamp);

var_dump($sign);

欢迎大家关注我的钉钉机器人ding-bot/hbh112233abc/ding-bot支持ThinkPHP6的日志通道哦:)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。