Verifying notification signatures
Bitclear API signs every notification following the Standard Webhooks specification, using its asymmetric (Ed25519) variant. Notifications are signed with a Bitclear private key and you verify them with the matching public key, so there is no secret to generate, store or rotate on your side.
Headers
Every notification includes three headers:
| Header | Description |
|---|---|
webhook-id |
Unique notification ID, e.g. msg_5f1c2e8a-.... It stays the same when a notification is retried or redelivered, so use it to detect duplicates. |
webhook-timestamp |
Time of this delivery attempt, in seconds since the Unix epoch. |
webhook-signature |
One or more space-separated signatures in the form v1a,<base64 signature>. |
Public keys
Fetch the public keys from:
GET /public/webhook-keys{
"keys": ["whpk_mCNo1Z7mY0tWm0Yx0lD4uHn0bQmVw1wB0t9Zp5T7GxI="]
}
No authentication is needed. Each key is whpk_ followed by a base64-encoded 32-byte Ed25519 public key. Keys differ between sandbox and production.
You can store the key in your configuration, or fetch it and cache it. When Bitclear rotates its key, the list contains two keys for a transition period, and every notification is signed with both. Accepting a notification when any of its signatures verifies against any key you trust lets you switch keys without downtime.
Verifying a notification
- Read the raw request body exactly as received. Don't parse and re-serialize it first, because the signature covers the exact bytes.
- Build the signed content:
{webhook-id}.{webhook-timestamp}.{body}. - For each
v1a,<signature>entry inwebhook-signature, base64-decode the signature and verify it with the Ed25519 public key. Accept the notification if at least one signature verifies. - Reject the notification if
webhook-timestampis more than 5 minutes away from your current time. This protects against replayed requests. - Check that
merchantIdin the body is your merchant ID. The signing key is shared by all Bitclear merchants, so this check guarantees the notification was meant for you. - Skip notifications whose
webhook-idyou have already processed.
Pseudocode:
content = headers['webhook-id'] + '.' + headers['webhook-timestamp'] + '.' + rawBody
valid = any(ed25519_verify(publicKey, content, base64_decode(sig))
for 'v1a,' + sig in headers['webhook-signature'].split(' '))Java
Uses only the JDK (Java 15+):
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.util.Base64;
public class WebhookVerifier {
// X.509 DER prefix for an Ed25519 public key
private static final byte[] ED25519_PREFIX = {0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65,
0x70, 0x03, 0x21, 0x00};
private final PublicKey publicKey;
public WebhookVerifier(String whpkKey) throws Exception {
byte[] raw = Base64.getDecoder().decode(whpkKey.substring("whpk_".length()));
byte[] der = new byte[ED25519_PREFIX.length + raw.length];
System.arraycopy(ED25519_PREFIX, 0, der, 0, ED25519_PREFIX.length);
System.arraycopy(raw, 0, der, ED25519_PREFIX.length, raw.length);
this.publicKey = KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(der));
}
public boolean verify(String id, String timestamp, String signatureHeader, String rawBody)
throws Exception {
long age = Math.abs(Instant.now().getEpochSecond() - Long.parseLong(timestamp));
if (age > 300) {
return false;
}
byte[] content = (id + "." + timestamp + "." + rawBody).getBytes(StandardCharsets.UTF_8);
for (String entry : signatureHeader.split(" ")) {
if (!entry.startsWith("v1a,")) {
continue;
}
Signature verifier = Signature.getInstance("Ed25519");
verifier.initVerify(publicKey);
verifier.update(content);
if (verifier.verify(Base64.getDecoder().decode(entry.substring(4)))) {
return true;
}
}
return false;
}
}
Node.js
const crypto = require('crypto');
function verifyWebhook(whpkKey, headers, rawBody) {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const publicKey = crypto.createPublicKey({
key: { kty: 'OKP', crv: 'Ed25519',
x: Buffer.from(whpkKey.slice(5), 'base64').toString('base64url') },
format: 'jwk',
});
const content = Buffer.from(`${id}.${timestamp}.${rawBody}`, 'utf8');
return headers['webhook-signature'].split(' ')
.filter((entry) => entry.startsWith('v1a,'))
.some((entry) => crypto.verify(null, content, publicKey, Buffer.from(entry.slice(4), 'base64')));
}
Python
Uses the cryptography package:
import base64, time
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
def verify_webhook(whpk_key, headers, raw_body: bytes) -> bool:
msg_id, timestamp = headers['webhook-id'], headers['webhook-timestamp']
if abs(time.time() - int(timestamp)) > 300:
return False
public_key = Ed25519PublicKey.from_public_bytes(base64.b64decode(whpk_key[len('whpk_'):]))
content = f'{msg_id}.{timestamp}.'.encode() + raw_body
for entry in headers['webhook-signature'].split(' '):
if entry.startswith('v1a,'):
try:
public_key.verify(base64.b64decode(entry[4:]), content)
return True
except InvalidSignature:
pass
return False