Ensuring data hasn't been tampered with using cryptographic signatures.
How does a server know that a session cookie or a webhook payload hasn't been altered by an attacker? It uses an HMAC (Hash-based Message Authentication Code).
The server hashes the message along with a Secret Key that only the server knows. It appends this "Signature Tag" to the data. When the data comes back, the server re-runs the HMAC. Because of the Avalanche Effect, even if a single bit of the message is changed, the resulting tag completely changes, exposing the forgery!
import hmac
import hashlib
def generate_signature(secret, message):
return hmac.new(
key=secret.encode(),
msg=message.encode(),
digestmod=hashlib.sha256
).hexdigest()
def verify(secret, message, received_sig):
expected_sig = generate_signature(secret, message)
# Use compare_digest to prevent Timing Attacks!
if hmac.compare_digest(expected_sig, received_sig):
return True
return False