Quickalerts Content hash verification example is wrong

I’m trying to verify the content hash from body, but the code at

looks wrong:

computed_content_hash = base64.b64encode(computed_hash).decode()

computed_content_hash should be the same value of x-qn-content-hash,
but x-qn-content-hash is not a base64 encoded value, but looks like an hexdigest of
a sha256, perhaps in my tests the sha256 of the body is even different from the one in x-qn-content-hash
header, there is an updated code for that check?

Hi @sherpya

Please try the following steps:

  1. Retrieve the body of the webhook payload.
  2. Compute the SHA-256 hash of the payload body.
  3. Encode the hash value in Base64 format.
  4. Compare the resulting hash with the x-qn-content-hash header value in the payload headers.
import hmac
import hashlib
import base64
from urllib.parse import urlparse

secret = 'your_security_token'
given_sign = request.headers.get('x-qn-signature')
nonce = request.headers.get('x-qn-nonce')
timestamp = request.headers.get('x-qn-timestamp')
webhook_url = 'your_webhook_url'

# Retrieve the payload body
payload_body = request.get_data()

# Parse the URL and extract the path
parsed_url = urlparse(webhook_url)
path = parsed_url.path

# Combine the path with the payload body
data = path + payload_body

# Convert the combined string to bytes
data_bytes = data.encode()

# Compute the SHA-256 hash of the data and convert it to hex
computed_hash = hashlib.sha256(data_bytes).hexdigest()

# Generate the expected signature
signature_data = nonce.encode() + computed_hash.encode() + timestamp.encode()
expected_sign = base64.b64encode(hmac.new(secret.encode(), signature_data, hashlib.sha256).digest()).decode()

# Compare the given signature with the expected signature
if given_sign == expected_sign:
    print('The signature given matches the expected signature and is valid.')
    print('The signature given does not match the expected signature and is invalid.')