Verify Webhook Signatures with HMAC
The X-Signature header of a Chaingateway webhook lets you check that a request really comes from Chaingateway. It contains the base64-encoded HMAC-SHA256 of the transaction id (txid) from the payload, keyed with your personal secret. Your receiver recomputes the value and compares it with the header. The header is sent once you have set a personal secret.
What does the X-Signature header protect against?
Section titled “What does the X-Signature header protect against?”It protects against forged requests: anyone can send a POST request to your public receiver URL, but only a sender who knows the personal secret can produce a matching signature. HMAC, defined in RFC 2104, combines a hash function with a secret key, here SHA-256. NIST FIPS 198-1 specifies the same construction as the Keyed-Hash Message Authentication Code.
The signature covers the txid and nothing else. The amount, the addresses and the token fields in the body are not signed. A valid pair of txid and signature therefore does not prove that the rest of the body is unchanged. After the check, treat the txid as a lookup key: read the transaction with GET /api/v2/{chain}/transactions/{txid} and credit the payment from the data that the API returns, not from the amount in the notification body.
How do I set the personal secret?
Section titled “How do I set the personal secret?”You set or regenerate the personal secret in your profile settings. Follow these steps:
- Open Profile Settings.
- Find the section labeled “Personal Secret”.
- If no secret is set, click “Set Personal Secret” to generate one. If a secret exists, click “Regenerate Secret” to replace it.
Two details matter for a running system. If you have no personal secret yet, adding one switches on the X-Signature header for all outgoing webhooks. Deploy a receiver that accepts and verifies the header before you do this. If you regenerate an existing secret, the new secret applies to webhook notifications immediately. Update the receiver at the same time, or it rejects valid requests.
How is the X-Signature header built?
Section titled “How is the X-Signature header built?”Chaingateway reads the txid from the payload, computes an HMAC with the SHA-256 hash function over it, using the personal secret as the key, and base64-encodes the 32 result bytes. The txid is the unique transaction identifier that already appears in the webhook body, so the receiver has everything it needs to recompute the value. The secret is shared only between Chaingateway and you.
How do I verify the signature in my code?
Section titled “How do I verify the signature in my code?”Recompute the HMAC from the txid in the body and compare it with the header value. Use a constant-time comparison function so that the comparison time reveals nothing about the expected value. The examples below do this in Python, Java, PHP and JavaScript.
import hmacimport hashlibimport base64
def verify_signature(txid, received_signature, personal_secret): # Generate the expected signature expected_signature = base64.b64encode(hmac.new( personal_secret.encode(), txid.encode(), hashlib.sha256 ).digest()).decode()
# Compare the expected signature with the received signature return hmac.compare_digest(expected_signature, received_signature)
# Example usagetxid = 'your_txid_here'received_signature = 'received_signature_here'personal_secret = 'your_personal_secret_here'
if verify_signature(txid, received_signature, personal_secret): print("Signature is valid.")else: print("Invalid signature.")import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;
public class SignatureVerifier { public static boolean verifySignature(String txid, String receivedSignature, String personalSecret) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec(personalSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); mac.init(secretKeySpec);
byte[] signatureBytes = mac.doFinal(txid.getBytes(StandardCharsets.UTF_8)); String expectedSignature = Base64.getEncoder().encodeToString(signatureBytes);
// Constant-time comparison return MessageDigest.isEqual( expectedSignature.getBytes(StandardCharsets.UTF_8), receivedSignature.getBytes(StandardCharsets.UTF_8)); }
public static void main(String[] args) { try { String txid = "your_txid_here"; String receivedSignature = "received_signature_here"; String personalSecret = "your_personal_secret_here";
if (verifySignature(txid, receivedSignature, personalSecret)) { System.out.println("Signature is valid."); } else { System.out.println("Invalid signature."); } } catch (Exception e) { e.printStackTrace(); } }}<?phpfunction verifySignature($txid, $receivedSignature, $personalSecret) { // Generate the expected signature $expectedSignature = base64_encode(hash_hmac('sha256', $txid, $personalSecret, true));
// Compare the expected signature with the received signature return hash_equals($expectedSignature, $receivedSignature);}
// Example usage$txid = 'your_txid_here';$receivedSignature = 'received_signature_here';$personalSecret = 'your_personal_secret_here';
if (verifySignature($txid, $receivedSignature, $personalSecret)) { echo "Signature is valid.";} else { echo "Invalid signature.";}const crypto = require('crypto');
function verifySignature(txid, receivedSignature, personalSecret) { // Generate the expected signature const expectedSignature = crypto .createHmac('sha256', personalSecret) .update(txid) .digest('base64');
// timingSafeEqual throws if the lengths differ, so check them first const expected = Buffer.from(expectedSignature); const received = Buffer.from(receivedSignature); return expected.length === received.length && crypto.timingSafeEqual(expected, received);}
// Example usageconst txid = 'your_txid_here';const receivedSignature = 'received_signature_here';const personalSecret = 'your_personal_secret_here';
if (verifySignature(txid, receivedSignature, personalSecret)) { console.log("Signature is valid.");} else { console.log("Invalid signature.");}How can I test my verification code?
Section titled “How can I test my verification code?”Test the function with a fixed input before you connect it to live traffic. The values below are a test vector that you can reproduce with any HMAC-SHA256 tool. The secret is a placeholder, not a real personal secret. If your function returns a different value for this input, the bug is in your code and not in the webhook.
personal_secret: my_personal_secrettxid: 18f52f2a55b94a6e3705de4abb18e95dfce79970f27b29450705c561e12b6988X-Signature: t2vU2mYBCv/UvpKprNJB7qbgrCpPXKb6NWgL77xsZgQ=Common mistakes are hashing the whole JSON body instead of the txid, using the hex digest instead of base64, and comparing with ==, which is not constant-time. Also remember that the personal secret is account-wide. A secret that you regenerate in the profile settings changes the signature of every webhook of the account at once.
What should I do when the signature does not match?
Section titled “What should I do when the signature does not match?”Reject the request with an error status such as 401 or 403 and do not process the body. Log the txid, the received header and the source address, so that you can tell a misconfigured secret from a forged request. If the same sender produces mismatches right after you regenerated the secret, the receiver still uses the old one. A forged request that only guesses a txid cannot produce a valid signature without the secret.
What else should a webhook receiver do?
Section titled “What else should a webhook receiver do?”Signature verification is one layer. The following measures cover the rest of the path.
- Serve the receiver over HTTPS, so the payload is encrypted in transit. OWASP’s REST Security Cheat Sheet recommends HTTPS for every endpoint that handles sensitive data.
- Reject requests with a missing or wrong
X-Signaturewith an error status, and log them. - Use the
txidas an idempotency key. A notification that you re-send withPOST /api/v2/{chain}/webhooks/notifications/{id}/retrycarries the sametxidand must not credit a payment twice. - Keep the personal secret in a secrets store, never in the repository, and rotate it if it may have leaked. Chaingateway does not retry failed deliveries on its own, so plan the update of the receiver and the secret as one step, and re-send missed notifications from the failed list afterwards.
Sources
Section titled “Sources”- RFC 2104, HMAC: Keyed-Hashing for Message Authentication
- NIST FIPS 198-1, The Keyed-Hash Message Authentication Code (HMAC)
- OWASP REST Security Cheat Sheet
- Webhooks in this documentation for the payload and the retry endpoints.