Please, I’m having problem in validating a data with HMAC SHA512 signature using python hmac library. I’ve read the documentation and I’ve also look into series of examples online but after the implementation, the signature is always different from the hmac hexdigest.
Please, I will be glad with your solution responses. Thanks
This is my code:
import hashlib
import hmac
import json
def validate_signature(key: str, data: dict, signature: str) -> bool:
hmac_obj = hmac.new(
key=key.encode("utf-8"),
msg=json.dumps(data).encode("utf-8"),
digestmod=hashlib.sha512,
)
print("Signature: ", signature)
print("HMAC_OBJ: ", hmac_obj.hexdigest())
print("is_validate: ", hmac_obj.hexdigest() == signature)
return hmac_obj.hexdigest() == signature
I call the function with my secret_key, data to validate, and the signature associated with the data.
And I’m getting unmatched Signature and HMAC_OBJ.
I’m expecting the function to return True
but it’s returning False
.
PraiseGod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
It appears that you are having problems using the hmac package to validate HMAC signatures in Python.
The most frequent cause of a discrepancy between the intended signature and the HMAC signature is inconsistent handling of the signature, key, or input data.
Please try below code for generation of you signature and validation:
import hashlib
import hmac
import json
def validate_signature(key: str, data: dict, signature: str) -> bool:
hmac_obj = hmac.new(
key=key.encode("utf-8"),
msg=json.dumps(data).encode("utf-8"),
digestmod=hashlib.sha512,
)
hmac_digest = hmac_obj.hexdigest()
print("Expected Signature:", signature)
print("Calculated HMAC Digest:", hmac_digest)
is_valid = hmac_digest == signature
print("Validation Result:", is_valid)
return is_valid
def generate_signature(key: str, data: dict) -> str:
hmac_obj = hmac.new(
key=key.encode("utf-8"),
msg=json.dumps(data).encode("utf-8"),
digestmod=hashlib.sha512,
)
return hmac_obj.hexdigest()
secret_key = "your_secret_key"
data = {"key": "value"} # Sample data
provided_signature = generate_signature(secret_key, data)
validate_signature(secret_key, data, provided_signature)