Python 对PHP hmac_sha1 签名实现

hashlib 是个专门提供hash算法的库,现在里面包括md5, sha1, sha224, sha256, sha384, sha512,使用非常简单、方便。

Python 对PHP hmac_sha1 签名实现

php

1
2
3
4
//HMAC-SHA1加密
$hmac_sha1_str = base64_encode(hash_hmac("sha1", $string_to_sign, $secret_access_key));
//编码URL
$signature = urlencode($hmac_sha1_str);

python

1
2
3
4
5
signature = urllib.quote(
    base64.b64encode(
        hmac.new(secret_access_key, string_to_sign, digestmod=hashlib.sha1)
        .hexdigest()
    ))

有两点需要注意

  • 不能使用encodestring, 因为该函数会在字符串末尾添加上行结束符号%0A,即\n
  • 不能使用hmac的digest方法,而需要使用 hexdigest 才能和PHP的hash_hmac结果对上。

如下

1
2
3
4
5
6
import hmac
h = hmac.new(key, data, digest_module)
# hex output:
result = h.hexdigest()
# raw output:
result = h.digest()

sha256 例子

php 版

1
echo hash_hmac("sha256","a", "1");

python 版

1
2
3
4
import hmac,hashlib
key='1'
data='a'
print hmac.new(key, data, hashlib.sha256).hexdigest()

本文网址: https://py.youbbs.org/topic/103.html 转摘请注明来源

Suggested Topics

python SQLite 数据库提速经验

SQLite 特点是轻巧,依赖少,数据库就一个文件,打包即可提走。最近做一个应用,千万条数据,更新频繁,但处理方式很简单,首先直接用SQLite 处理,结果两分钟可以完成处理一次,这个还是太慢了。下面介绍 SQLite 优化提速的经验。...

python 解析电子书的信息

epub 书是可供人们下载的开放性资源格式的电子图书。epub 文件通常与类似亚马逊Kindle 这样的电子阅读器不兼容。...

给ssdb python 接口提速

SSDB 是个新兴的数据库,其数据库的特点简单,性能高效,有好多python 接口,个人比较后选择一个最理想的,但还有提速空间,这里仅作经验分享。...

Leave a Comment