Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to validate a post request sign and so far the signed hash is not coordinating the test hash that I have generated with my flask API.

I have executed the following code to verify the signature in Ruby:

payload_body = request.body.read

signature = "sha1=" + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"), SECRET_TOKEN, payload_body)

The code in Flask/Python 3.6:

import hashlib, hmac

data=request.get_data()

key=SECRET_TOKEN.encode("utf-8"))

signature = "sha1=" + hmac.new(key, data, hashlib.sha1).hexdigest()

With the following data:

SECRET_TOKEN=""

request_data={"type": "verification_approved","data":{"level":"v1","user_id":"d6d782ef-568b-4355-8eb4-2d32ac97b44c"}}

The desired output:

Ruby hash: "sha1=2e7c4e307e25dd0ce4baad4d90dc7d4b63bdbab6" # as indicated in the documentation

And I got:

Python hash: "sha1=b9361bca2a38228c741ef60296b468693752b76d" # my implementation

Any help/pointers would be greatly appreciated!

1 Answer

0 votes
by (108k points)

Kindly refer to the below code that will implement the HMAC SHA1 signature validation:

import hmac

from hashlib import sha1

from flask import request, abort

@app.route("/webhook", methods=["POST"])

def webhook(request):

    if "X-Fractal-Signature" not in request.headers:

        abort(403)

    signature = request.headers.get("X-Fractal-Signature", "").split("=")[1]

    # Generate our own signature based on the request payload

    secret = os.environ.get('FRACTAL_SECRET', '').encode("utf-8")

    mac = hmac.new(secret, msg=request.data, digestmod=sha1)

    # Ensure the two signatures match

    if not str(mac.hexdigest()) == str(signature):

        abort(403)

I would suggest you to use a 403s instead of 400 in the abort function.

If you want to know more about Python basics then do refer to the below Python tutorial that will help you out in a better way:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 9, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...