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://pylist.com/topic/103.html 转摘请注明来源

Suggested Topics

python 半角全角的相互转换

全角与半角在中文输入法里经常要接触到,后台在处理用户输入数据时需要对半角全角的相互转换。下面是python 实现的半角全角的相互转换功能。...

python SQLite 数据库提速经验

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

Python List 按键高效排序方法

Python含有许多古老的排序规则,这些规则在你创建定制的排序方法时会占用很多时间,而这些排序方法运行时也会拖延程序实际的运行速度。...

python编程中常用的12种基础知识总结

python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python调用系统命令或者脚本,Python 读写文件。...

Leave a Comment