现在的位置: 首页 > 综合 > 正文

Python对PHP服务器hmac_sha1签名认证方法的匹配实现

2013年05月24日 ⁄ 综合 ⁄ 共 570字 ⁄ 字号 评论关闭

如果你写的PHP服务端API,在签名中使用了PHP的hash_hmac函数,并且使用了base64编码,

如下:

        //HMAC-SHA1加密
        $hmac_sha1_str = base64_encode(hash_hmac("sha1", $string_to_sign, $secret_access_key));
        //编码URL

        $signature = urlencode($hmac_sha1_str);

现在一个Python客户端程序想要来调用你的API,首先要通过安全认证,其签名方法可实现如下:

signature = urllib.quote(
    base64.b64encode(
        hmac.new(secret_access_key, string_to_sign, digestmod=hashlib.sha1)
        .hexdigest()
    ))

有两点需要注意:

1. 不能使用encodestring, 因为该函数会在字符串末尾添加上行结束符号%0A,即\n

参见说明文档:http://docs.python.org/library/base64.html

2. 不能使用hmac的digest方法,而需要使用hexdigest才能和PHP的hash_hmac结果对上。

iefreer

抱歉!评论已关闭.