Webhook Signature
Every webhook BCB sends is signed with a BCB private key. Verify the signature before you act on a webhook, so you know that BCB sent it and that the body was not changed in transit.
BCB signs with a private key held in Google Cloud KMS, which never leaves the key management service. You verify with BCB's public key, published below. There is no shared secret to set up or store.
Two layers of protection
- Signature. Proves BCB sent the body and that it was not modified. Always check it.
- Source IP. Webhooks come from fixed BCB IP addresses. See Webhook verification for the list, and reject requests from any other address.
How webhooks are signed
| Item | Value |
|---|---|
| Header | X-BCB-SIGNATURE |
| Algorithm | RSA PKCS#1 v1.5 with SHA-256 (RS256, SHA256withRSA), 2048-bit key |
| Signed content | The raw HTTP request body, exactly as received. Nothing else is signed (no URL or headers). |
| Encoding | Standard Base64 (+ and /), with padding |
| Method | POST, with Content-Type: application/json |
Example request:
POST /your/webhook/endpoint HTTP/1.1
Content-Type: application/json
X-BCB-SIGNATURE: WFiP/cRtzxA7KEIw46l9qqh5RChpWQ3FiGrrWgdEAmUs...fve0zgFAAw==
{"status":0,"message":"this is a test json string","test":true}
Not the same scheme as API request signingWebhook signatures are separate from the BCB-PKI signatures you send to the BCB API. Webhooks use a plain Base64 RSA signature over the body, not a detached JWS, and they are signed with BCB's key, not yours.
BCB public keys
Use the key for the environment the webhook comes from. Save it in your application's configuration. You do not need to fetch it at runtime.
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlEWLDLbTwpN5EDCvt/jn
2x1ey1uU5zggWkl6ZjDbJmfbWiUdxB/icE0vDg738rmN8Iidf/L+Wk5vQP2A6J8d
1D4N16Cmi5wPFmbqcs6Nd5iDOAoda6WRxP5XOUOdCCL5b7O9oRCjIwucDZGrszVV
YFGKni59OlxNmXGvR874q5r0TjxOwx0y38Gx9xel6xOBo+impqHl65rBs4JFP6Y5
o+0nczD3/6i2A1iugdNQXDMQ3trduUBh5qnliHwkO0gQ5IXDtbPLWt9kW2LRFJij
UoKYGO1ocT4+FniwPLCsHlZGChAtTcLPF5sVoTc1em0jDMqWag44vMOVqJ0himVO
7QIDAQAB
-----END PUBLIC KEY----------BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqhwQWNVfS6CRrzo6u9Qh
ZQ0rxB0AUm1bytritMvSHOloWAXW9UwXSbD97CrJ4uc7NjYKmAswJ5ErrNCHLbrE
msvjwHfeAd+koeodqa+oakGp/Q3bTcDvrNN+UQP3SNj5Mv2FrhrxJo/G9c9YUdrp
TDtz+jk6mG8EdJuLJdIKmLRtR6Jq9j/Cp6c6RHM57cHXcRo3GVsrXE+NBTA7eFAB
G1izVgn+qAwEayabXcCNC5AtRwPZLT4r10NuTn8Gw1mjNgOa4GeLcLIiqdDQIoZ1
B6SN40ytOxCZziVK0XAcjeYa6Q7vyvd1qt7gdERGFH1CCTTkjqeErsxiJgpfgFSC
OQIDAQAB
-----END PUBLIC KEY-----Check that you copied the key correctly by comparing its SHA-256 fingerprint:
| Environment | SHA-256 fingerprint of the DER-encoded key |
|---|---|
| Production | 8b0e22e0dd91d71a802f1a618711bdd1adb29a5978ae9c0bf4570e6437493f4a |
| Sandbox | 4637480771bfbaed4d3a4b00d88edb1fdef75e9f39f6fb365154e5674c53a63c |
openssl pkey -pubin -in bcb-webhook-production.pem -outform DER | openssl dgst -sha256Verify a webhook
- Read the raw request body as bytes, before any JSON parsing.
- Read the
X-BCB-SIGNATUREheader and Base64-decode it. - Verify the decoded signature over the raw body with the BCB public key, using RSA PKCS#1 v1.5 and SHA-256.
- If verification fails, or the header is missing, respond with
401and do not process the webhook. - Only then parse the JSON and process the event.
Verify the raw bytes, not parsed JSONThe signature covers the exact bytes BCB sent. If your framework parses the body into an object and you serialise it again, key order, whitespace or number formatting can change and verification will fail. Capture the raw body first:
- Express:
express.raw({ type: 'application/json' })on the webhook route, then usereq.body(aBuffer).- FastAPI / Starlette:
await request.body().- Flask:
request.get_data().- Spring: accept the body as
@RequestBody byte[].
Reference implementations
These examples use only standard libraries (node:crypto, cryptography for Python, and java.security). Each one returns false instead of throwing when the signature is missing, malformed or wrong.
import { createPublicKey, verify } from 'node:crypto';
import { readFileSync } from 'node:fs';
const BCB_WEBHOOK_PUBLIC_KEY = createPublicKey(readFileSync('bcb-webhook-production.pem', 'utf8'));
/** Returns true if X-BCB-SIGNATURE is a valid signature of the raw body bytes. */
export function verifyBcbWebhook(rawBody: Buffer, signatureHeader: string | undefined): boolean {
if (!signatureHeader) return false;
return verify('sha256', rawBody, BCB_WEBHOOK_PUBLIC_KEY, Buffer.from(signatureHeader, 'base64'));
}
// Express example
// app.post('/webhooks/bcb', express.raw({ type: 'application/json' }), (req, res) => {
// if (!verifyBcbWebhook(req.body, req.get('X-BCB-SIGNATURE'))) return res.sendStatus(401);
// const event = JSON.parse(req.body.toString('utf8'));
// res.sendStatus(200);
// });import base64
import binascii
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
with open("bcb-webhook-production.pem", "rb") as f:
BCB_WEBHOOK_PUBLIC_KEY = serialization.load_pem_public_key(f.read())
def verify_bcb_webhook(raw_body: bytes, signature_header: str | None) -> bool:
"""Returns True if X-BCB-SIGNATURE is a valid signature of the raw body bytes."""
if not signature_header:
return False
try:
signature = base64.b64decode(signature_header, validate=True)
BCB_WEBHOOK_PUBLIC_KEY.verify(signature, raw_body, padding.PKCS1v15(), hashes.SHA256())
return True
except (InvalidSignature, binascii.Error, ValueError):
return False
# FastAPI example
# @app.post("/webhooks/bcb")
# async def bcb_webhook(request: Request):
# raw_body = await request.body()
# if not verify_bcb_webhook(raw_body, request.headers.get("X-BCB-SIGNATURE")):
# raise HTTPException(status_code=401)
# event = json.loads(raw_body)import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public final class BcbWebhookVerifier {
private final PublicKey publicKey;
public BcbWebhookVerifier(Path publicKeyPem) throws Exception {
String pem = Files.readString(publicKeyPem)
.replaceAll("-----(BEGIN|END) PUBLIC KEY-----", "")
.replaceAll("\\s", "");
this.publicKey = KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(pem)));
}
/** Returns true if X-BCB-SIGNATURE is a valid signature of the raw body bytes. */
public boolean verify(byte[] rawBody, String signatureHeader) {
if (signatureHeader == null || signatureHeader.isEmpty()) return false;
try {
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(publicKey);
verifier.update(rawBody);
return verifier.verify(Base64.getDecoder().decode(signatureHeader));
} catch (IllegalArgumentException | GeneralSecurityException e) {
return false;
}
}
}Test your implementation
Use this example with the production public key. Your code should return true. Change any character in the body and it should return false.
| Item | Value |
|---|---|
| Body (exact bytes) | {"status":0,"message":"this is a test json string","test":true} |
WFiP/cRtzxA7KEIw46l9qqh5RChpWQ3FiGrrWgdEAmUsSWrYtMFVKA2paLBdN/l4nGmGBObS/3L9Erz9v3xH1LbBFCpLi7E1qmNwwXyq6WdLrtE1grKeBrJuU73b2K7GsPCpCW3pbWnRnRfIsLChdTTe+fxOD1Ba1FfFF34gCXc+lOHWPT7FZVw3pBhB2Mz3Ff9j+h+7rSaVKydOoUl/vjh+GmxFQ+/6ZWpdvZMLNiCBWU6a1RkqR8uJGH4iF1eGzhU5brW8UFXFrUv84tCGodPbRUrnCTWCpyPhKC6YHYDFGQRkZTAPFG/HVxuFygK4nszVw62LQWecfve0zgFAAw==Security recommendations
- Reject unsigned or invalid webhooks. Respond with
401and do not process them. - Allow-list BCB's source IPs as a second check. See Webhook verification.
- Use HTTPS for your webhook endpoint.
- Process each event once. The signature covers only the body, not a timestamp, so a valid webhook could be delivered more than once. Use the identifiers in the payload (for example the transaction
id, orendToEndIdentificationfor payment status) to ignore duplicates. - Respond quickly. Return a
2xxstatus as soon as you have verified and stored the webhook, then do any slow processing afterwards. - Plan for missed deliveries. BCB does not currently retry failed deliveries. If your endpoint is unavailable or returns an error, that webhook is not sent again. Use the API to reconcile any events you may have missed.
Troubleshooting
- Verification always fails. You are probably verifying a re-serialised body. Use the raw bytes as received. Check that no middleware decompresses, trims or re-encodes the body first.
- Wrong key. Sandbox webhooks are signed with the sandbox key and production webhooks with the production key. Check the fingerprint.
- Wrong algorithm. Use RSA PKCS#1 v1.5 (
RS256,SHA256withRSA), not RSA-PSS and not HMAC. - Wrong encoding. The header is standard Base64 with padding. If your library expects base64url, convert it first.
Updated 17 days ago