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 SQLite 数据库提速经验

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

给ssdb python 接口提速

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

python 高效的list 去重方式

list 去重是编程中经常用到的,python 的去重方式很灵活,下面介绍多种去重方式,并比较得出最高效的方式。...

python 正确计算大文件md5 值

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

Leave a Comment