使用Python中的Flask进行Hmac验证 (含有PHP和RUBY参考)

5

我一直在寻找一种用Python和Flask实现selly.gg商家网站中的HMAC验证的方法。

所以,selly的开发文档给出了以下示例来验证HMAC签名(使用PHP和ruby):https://developer.selly.gg/?php#signing-validating (代码如下:)

PHP:

<?php
        $signature = hash_hmac('sha512', json_encode($_POST), $secret);
        if hash_equals($signature, $signatureFromHeader) {
            // Webhook is valid 
        }
?>

红宝石:

signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha512'), secret, payload.to_json)
is_valid_signature = ActiveSupport::SecurityUtils.secure_compare(request.headers['X-Selly-Signature'], signature)

目前我所了解的是:它们不使用base64进行编码(就像shopify和其他一些平台一样),而是使用SHA-512。它将秘密代码与json响应数据一起编码,最后请求头是“X-Selly-Signature”。

我已经编写了以下代码(基于Shopify用于HMAC签名的代码 https://help.shopify.com/en/api/getting-started/webhooks):

SECRET = "secretkeyhere"
def verify_webhook(data, hmac_header):
    digest = hmac.new(bytes(SECRET, 'ascii'), bytes(json.dumps(data), 'utf8'), hashlib.sha512).hexdigest()
    return hmac.compare_digest(digest, hmac_header)
try:
    responsebody = request.json #line:22
    status = responsebody['status']#line:25
except Exception as e:
    print(e)
    return not_found()
print("X Selly sign: " + request.headers.get('X-Selly-Signature'))
verified = verify_webhook(responsebody, request.headers.get('X-Selly-Signature'))
print(verified)

然而,Selly有一个Webhook模拟器,即使具有正确的密钥和有效请求,verify_webhook也将始终返回False。我尝试联系Selly支持,但他们不能为我提供更多帮助。
您可以在以下地址测试Webhook模拟器: https://selly.io/dashboard/{your账户}/developer/webhook/simulate
1个回答

3

除了您不需要对请求数据进行json.dumps之外,您几乎是正确的。这可能会导致输出发生更改,例如格式方面的更改,这些更改将不符合原始数据的意思,从而导致HMAC失败。

例如:

{"id":"fd87d909-fbfc-466c-964a-5478d5bc066a"}

与其不同的是:

{
  "id":"fd87d909-fbfc-466c-964a-5478d5bc066a"
}

实际上是:

{x0ax20x20"id":"fd87d909-fbfc-466c-964a-5478d5bc066a"x0a}

对于这两个输入,哈希值将完全不同。

看一下 json.loadsjson.dumps 如何修改格式,并因此改变哈希值:

http_data = b'''{
    "id":"fd87d909-fbfc-466c-964a-5478d5bc066a"
}
'''
print(http_data)
h = hashlib.sha512(http_data).hexdigest()
print(h)
py_dict = json.loads(http_data) # deserialise to Python dict
py_str = json.dumps(py_dict) # serialise to a Python str
py_bytes = json.dumps(py_dict).encode('utf-8') # encode to UTF-8 bytes
print(py_str)
h2 = hashlib.sha512(py_bytes).hexdigest()
print(h2)

输出:

b'{\n    "id":"fd87d909-fbfc-466c-964a-5478d5bc066a"\n}\n'
364325098....
{"id": "fd87d909-fbfc-466c-964a-5478d5bc066a"}
9664f687a....

很遗憾,Selly的PHP例子展示的内容与此类似。实际上,Selly的PHP例子是没有用的,因为数据不会被表单编码,所以数据不会在$_POST中出现!

这里是我的小Flask例子:

import hmac
import hashlib
from flask import Flask, request, Response

app = Flask(__name__)

php_hash = "01e5335ed340ef3f211903f6c8b0e4ae34c585664da51066137a2a8aa02c2b90ca13da28622aa3948b9734eff65b13a099dd69f49203bc2d7ae60ebee9f5d858"
secret = "1234ABC".encode("ascii") # returns a byte object

@app.route("/", methods=['POST', 'GET'])
def selly():
    request_data = request.data # returns a byte object
    hm = hmac.new(secret, request_data, hashlib.sha512)
    sig = hm.hexdigest()

    resp = f"""req: {request_data}
    sig: {sig}
    match: {sig==php_hash}"""

    return Response(resp, mimetype='text/plain')

app.run(debug=True)

请注意使用request.data来获取原始的字节输入,并且简单地使用encodesecret字符串进行编码,以获取编码后的字节(而不是使用冗长的bytes()实例化方法)。
可以使用以下方式进行测试:
curl -X "POST" "http://localhost:5000/" \
 -H 'Content-Type: text/plain; charset=utf-8' \
 -d "{\"id\":\"fd87d909-fbfc-466c-964a-5478d5bc066a\"}"

我还编写了一些 PHP 代码来验证两种语言是否创建了相同的结果:

<?php
    header('Content-Type: text/plain');
    $post = file_get_contents('php://input');
    print $post;
    $signature = hash_hmac('sha512', $post, "1234ABC");
    print $signature;
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接