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 List 按键高效排序方法

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

python 对中文链接安全转码

当一个链接里包含中文时,有些浏览器并不能正确解析,这就需要首先对中文作安全转码,这里介绍用 python 对中文链接安全转码,...

Leave a Comment