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 正确计算大文件md5 值

python 计算文件的md5值很方便,但如果只是简单的把文件都入到内存中,大文件会导致问题,一般采用切片的方式分段计算,下面的几个函数可以很好的解决这个问题。...

SAE+python+Tornado+pyTenjin 的完整示例

python 简单易懂,Tornado 高效易学,pyTenjin 轻巧快速,SAE 安全稳定使用门槛低。现在把他们结合在一起做了一个可运行在SAE 上的完整示例。...

在 Ubuntu 16.04.6 LTS 系统上安装 Python 3.6.3

自己的阿里云一个 VPS 用的是系统 Ubuntu 16.04.6 LTS,自带的python版本是 `2.7.12` 与 `3.5.2`,有时候要用到 python `3.6`,又不想卸掉原来版本。下面介绍安装 python 3.6.3 的过程,因为版本较旧,遇到一些坑,这里记录一下。...

Leave a Comment