Authentication and Authorisation

BCB APIs are secured with BCB-PKI, a Holder-of-Key scheme aligned with the Open Banking UK Read/Write API Profile and FAPI 1.0. Each request you send is signed with a private key that only you hold. BCB checks the signature, a single-use transaction number (TAN), the timestamp and your source IP before the request reaches any business logic.

This guide explains how to set up your signing key and how to build a signed request.

📘

Why BCB-PKI

  • Every request carries its own proof of identity, so there are no access tokens to fetch, cache or refresh.
  • A captured request cannot be replayed, and a modified request is rejected.
  • BCB never sees your private key. You send BCB a Certificate Signing Request (CSR), and BCB stores only the public key.

How it works

sequenceDiagram
  participant C as Your system
  participant B as BCB API
  C->>C: Build signing payload (method + path and query + body)
  C->>C: Sign with private key (detached JWS)
  C->>B: HTTPS request + BCB-PKI headers + body
  B->>B: Check headers, kid, timestamp, IP allow-list
  B->>B: Verify signature with your public key
  B->>B: Check that the TAN has not been used before
  B-->>C: API response

Before you start

You need the following:

ItemWhere it comes from
A service account for your organisationCreated in the Client Console. See API Self Service.
A key pair and CSRYou generate these yourself (step 1).
A Key ID (kid)Issued by BCB when your CSR is enrolled (step 2). It is shown once, so save it.
A Client IDIssued by BCB with your credential. You send it as the iss claim.
Your public egress IP addressesYou register them on the service account allow-list. The list accepts IPv4 addresses, IPv4 CIDR ranges, IPv6 addresses, and IPv6 CIDR ranges.
An accurate system clockYour servers must be synchronised with NTP. Requests more than about 5 minutes out are rejected.

Base URLs:

EnvironmentBase URL
UAThttps://api.uat.bcb.group
Productionhttps://api.bcb.group

See BCB Group Environments for details.

Step 1: Create your signing key

BCB accepts two algorithms:

AlgorithmKey typeNotes
PS256RSA, 2048, 3072 or 4096 bits (3072 recommended)RSASSA-PSS with SHA-256 and a 32-byte salt.
ES256EC, curve P-256 onlyECDSA with SHA-256. Smaller keys and signatures, and fast to sign in an HSM.

RSA 4096 is supported if your security policy requires it. We still recommend 3072 bits, which gives a strong security margin with smaller signatures and faster signing, especially in an HSM.

❗️

RS256 is not accepted

RSA PKCS#1 v1.5 signatures (RS256) are rejected. If your library defaults to RS256, change it to PS256.

Choose where the key will live:

OptionUse for
A: Cloud KMS or HSMProduction. The private key is created inside the HSM and can never be exported. Your application asks the HSM to sign each request.
B: OpenSSL key fileUAT, local development and Postman testing.
🚧

Protect the private key

Anyone who can use your private key can sign requests as you. Never commit a key to source control, email it, or send it to BCB. BCB will never ask for it.

Option A: Cloud KMS or HSM

You need two things from your HSM: a non-exportable signing key, and a CSR signed by that key. Neither Google Cloud KMS nor AWS KMS can create a CSR directly, so BCB provides a small tool that builds the CSR and asks your KMS to sign it. The key never leaves the HSM.

1. Create the key

# Key ring (once per project and region)
gcloud kms keyrings create bcb-api --location europe-west2

# HSM-protected signing key. For PS256 use: --default-algorithm rsa-sign-pss-3072-sha256 (or rsa-sign-pss-4096-sha256)
gcloud kms keys create bcb-signing-prod \
  --keyring bcb-api --location europe-west2 \
  --purpose asymmetric-signing \
  --default-algorithm ec-sign-p256-sha256 \
  --protection-level hsm

# Allow only your workload's service account to sign
gcloud kms keys add-iam-policy-binding bcb-signing-prod \
  --keyring bcb-api --location europe-west2 \
  --member "serviceAccount:[email protected]" \
  --role roles/cloudkms.signerVerifier

# Key version name, used by the CSR tool and your application:
# projects/your-project/locations/europe-west2/keyRings/bcb-api/cryptoKeys/bcb-signing-prod/cryptoKeyVersions/1
# HSM-protected signing key. For PS256 use: --key-spec RSA_3072 (or RSA_4096)
aws kms create-key \
  --key-spec ECC_NIST_P256 \
  --key-usage SIGN_VERIFY \
  --description "BCB API request signing (production)"

aws kms create-alias --alias-name alias/bcb-signing-prod --target-key-id <KeyId from the output above>

# Grant your workload's IAM role only kms:Sign and kms:GetPublicKey on this key,
# in the key policy or an IAM policy scoped to the key ARN.
# Requires a Premium vault or Managed HSM. For PS256 use: --kty RSA-HSM --size 3072 (or 4096)
az keyvault key create \
  --vault-name your-vault \
  --name bcb-signing-prod \
  --kty EC-HSM --curve P-256 \
  --ops sign verify

# Grant your workload's identity the "Key Vault Crypto User" role on this key.

Grant signing rights to the single workload identity that calls BCB. Do not give people day-to-day access to sign with the production key, and keep the KMS audit log (Cloud Audit Logs, AWS CloudTrail or Azure Monitor) turned on for it.

2. Create the CSR

Run the CSR tool with credentials that can sign with the key:

pip install asn1crypto cryptography google-cloud-kms google-crc32c
python bcb_pki_csr.py --provider gcp \
  --key projects/your-project/locations/europe-west2/keyRings/bcb-api/cryptoKeys/bcb-signing-prod/cryptoKeyVersions/1 \
  --org "Your Company Ltd" --cn your-company-payments-prod > bcb-signing-key.csr
pip install asn1crypto cryptography boto3
python bcb_pki_csr.py --provider aws \
  --key alias/bcb-signing-prod \
  --org "Your Company Ltd" --cn your-company-payments-prod > bcb-signing-key.csr

Check the CSR before you upload it:

openssl req -in bcb-signing-key.csr -noout -verify -text

The tool needs bcb_pki.py from Reference implementations in the same folder:

"""Create a PKCS#10 CSR for a key that never leaves your HSM / KMS.

Usage:
  python bcb_pki_csr.py --provider gcp --key projects/P/locations/L/keyRings/R/cryptoKeys/K/cryptoKeyVersions/1 \
      --org "Your Company Ltd" --cn your-company-payments-prod > bcb-signing-key.csr
  python bcb_pki_csr.py --provider aws --key arn:aws:kms:eu-west-2:111122223333:key/KEY-ID \
      --org "Your Company Ltd" --cn your-company-payments-prod > bcb-signing-key.csr

Requires: pip install asn1crypto cryptography (plus google-cloud-kms google-crc32c, or boto3)
"""
import argparse
import sys

from asn1crypto import algos, csr, keys, pem, x509

from bcb_pki import AwsKmsSigner, GcpKmsSigner, KeySigner

SIGNER_FACTORIES = {"gcp": GcpKmsSigner, "aws": AwsKmsSigner}

# The CSR is self-signed with the same algorithm the key will use for API requests.
CSR_SIGNATURE_ALGORITHMS = {
    "ES256": algos.SignedDigestAlgorithm({"algorithm": "sha256_ecdsa"}),
    "PS256": algos.SignedDigestAlgorithm({
        "algorithm": "rsassa_pss",
        "parameters": algos.RSASSAPSSParams({
            "hash_algorithm": {"algorithm": "sha256"},
            "mask_gen_algorithm": {"algorithm": "mgf1", "parameters": {"algorithm": "sha256"}},
            "salt_length": 32,
        }),
    }),
}


def build_csr(signer: KeySigner, organisation: str, common_name: str) -> bytes:
    info = csr.CertificationRequestInfo({
        "version": "v1",
        "subject": x509.Name.build({"organization_name": organisation, "common_name": common_name}),
        "subject_pk_info": keys.PublicKeyInfo.load(signer.public_key_der()),
        "attributes": [],
    })
    request = csr.CertificationRequest({
        "certification_request_info": info,
        "signature_algorithm": CSR_SIGNATURE_ALGORITHMS[signer.algorithm],
        "signature": signer.sign(info.dump()),
    })
    return pem.armor("CERTIFICATE REQUEST", request.dump())


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--provider", choices=SIGNER_FACTORIES, required=True)
    parser.add_argument("--key", required=True, help="GCP key version name, or AWS key ID / ARN / alias")
    parser.add_argument("--org", required=True, help="Your legal entity name")
    parser.add_argument("--cn", required=True, help="A name for this key, e.g. your-company-payments-prod")
    args = parser.parse_args()
    sys.stdout.buffer.write(build_csr(SIGNER_FACTORIES[args.provider](args.key), args.org, args.cn))


if __name__ == "__main__":
    main()

Azure Key Vault and other HSMs. The tool is built around one small interface, KeySigner (see Reference implementations). To support another HSM, implement algorithm, public_key_der() and sign(), then add it to SIGNER_FACTORIES. Azure Key Vault returns ES256 signatures as raw R || S rather than DER, so convert them to DER for the CSR. For an on-premises or dedicated HSM with a PKCS#11 interface (for example AWS CloudHSM, Thales Luna or Entrust nShield), you can instead create the CSR with OpenSSL, the libp11 PKCS#11 engine and your vendor's PKCS#11 library:

openssl req -new -engine pkcs11 -keyform engine \
  -key "pkcs11:token=your-token;object=bcb-signing-prod;type=private" \
  -sha256 -subj "/O=Your Company Ltd/CN=your-company-payments-prod" \
  -out bcb-signing-key.csr

3. Sign requests with the HSM

Your application uses GcpKmsSigner or AwsKmsSigner from the reference implementations in place of a key file. Keep these in mind:

  • One KMS call per API request. This adds a few milliseconds to tens of milliseconds to each call. Check your provider's signing quotas against your peak request rate.
  • KMS errors are retryable. If the KMS call fails or times out, retry it with backoff. Nothing has been sent to BCB yet.
  • ECDSA format. Cloud KMS and AWS KMS return DER-encoded ECDSA signatures. JWS needs the raw 64-byte R || S value. The reference code converts it for you.
  • Rotation. Each new key or key version needs its own CSR and kid, so a KMS's automatic rotation does not help here (Google Cloud KMS and AWS KMS do not rotate asymmetric keys automatically anyway). Plan rotation as a scheduled task.

Option B: OpenSSL key file

Use this for UAT, local development and Postman. Generate the key and CSR with OpenSSL, using the commands for your chosen algorithm.

# Private key, PKCS#8 format ("BEGIN PRIVATE KEY")
# 3072 bits recommended; 4096 is also accepted
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out bcb-signing-key.pem

# Certificate Signing Request
openssl req -new -key bcb-signing-key.pem -sha256 \
  -subj "/O=Your Company Ltd/CN=your-company-payments-uat" \
  -out bcb-signing-key.csr
# Private key, PKCS#8 format ("BEGIN PRIVATE KEY")
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out bcb-signing-key.pem

# Certificate Signing Request
openssl req -new -key bcb-signing-key.pem -sha256 \
  -subj "/O=Your Company Ltd/CN=your-company-payments-uat" \
  -out bcb-signing-key.csr

If you already have an RSA key in PKCS#1 format (BEGIN RSA PRIVATE KEY), convert it to PKCS#8:

openssl pkcs8 -topk8 -nocrypt -in key.pem -out key-pkcs8.pem

Store the key file in a secret manager, not on disk or in your code repository.

Step 2: Enrol your CSR

  1. Sign in to the Client Console and open your service account.
  2. Upload the .csr file (PKCS#10, PEM).
  3. Complete the one-time passcode (OTP) check.
  4. Copy the Key ID (kid) that is displayed. It is shown only once.
  5. Make sure your egress IP addresses are on the service account's IP allow-list.

Keys are valid for at most 365 days. A service account can hold more than one active key, so you can rotate without downtime (see Key rotation and revocation).

Step 3: Build the signing payload

The signing payload is three values joined together as UTF-8 bytes, with nothing between them:

<HTTP METHOD><PATH AND QUERY><RAW BODY>
PartRule
MethodUppercase, for example POST.
Path and queryThe URL path and query string exactly as sent, starting with /. Do not include the scheme or host. Keep percent-encoding and trailing slashes exactly as sent.
BodyThe exact bytes you send in the request body, including any whitespace. For GET and HEAD, the body is empty.

Examples:

RequestSigning payload
GET https://api.uat.bcb.group/v3/accounts?limit=10GET/v3/accounts?limit=10
POST https://api.uat.bcb.group/v3/payments with body {"amount":"10.50","currency":"GBP"}POST/v3/payments{"amount":"10.50","currency":"GBP"}
🚧

Sign the bytes you send

Serialise your JSON body once, sign that string, and send that same string. Many HTTP clients re-serialise objects (for example axios with an object body, or requests with json=). This can change key order or whitespace and will break the signature. Pass a pre-serialised string or bytes instead. Do not compress the request body.

The same applies to the query string. Build the final URL once, sign it, and send that same URL. Do not let your HTTP client add, reorder or re-encode query parameters after signing (for example axios with params, or requests with params=).

Step 4: Build the protected header

The JWS protected header is a JSON object with these fields:

FieldValue
algPS256 or ES256. Must match the key you enrolled.
kidYour Key ID. Must match the value in the Authorization header.
crit["http://openbanking.org.uk/iat", "http://openbanking.org.uk/tan", "http://openbanking.org.uk/iss"]
http://openbanking.org.uk/iatIssued-at time, in Unix seconds (integer). Must be within about 5 minutes of BCB's clock.
http://openbanking.org.uk/tanA new random UUID for every request. A TAN can never be reused.
http://openbanking.org.uk/issYour client identifier, we suggest your company domain https://<company-domain> but for more granularity https://<company-domain>/<description-key>

Example:

{
  "alg": "PS256",
  "kid": "3f1c9a52-7d0e-4b8a-9a61-2f5d7c4e8b10",
  "crit": [
    "http://openbanking.org.uk/iat",
    "http://openbanking.org.uk/tan",
    "http://openbanking.org.uk/iss"
  ],
  "http://openbanking.org.uk/iat": 1792161668,
  "http://openbanking.org.uk/tan": "2536d281-9162-4791-828e-e21cacca6d69",
  "http://openbanking.org.uk/iss": "https://auth.yourcompany.com/payments-prod"
}

Serialise the header once, without pretty-printing. The signature covers these exact bytes.

Step 5: Create the detached signature

SegmentEncoding
Headerbase64url of the header JSON, no padding
Payloadbase64url of the signing payload, no padding
Signaturebase64url of the signature bytes, no padding
  1. Build the signing input: base64url(header) + "." + base64url(payload).
  2. Sign the signing input (as ASCII bytes) with your private key:
    • PS256: RSASSA-PSS, SHA-256, MGF1 with SHA-256, salt length 32.
    • ES256: ECDSA P-256 with SHA-256. The signature must be the 64-byte raw R || S value, not DER.
  3. Build the detached JWS by leaving the payload segment out: base64url(header) + ".." + base64url(signature).
📘

All three segments use base64url

The header, payload and signature segments all use base64url (- and _, no padding), as in a standard RFC 7515 JWS. Do not use standard Base64 (+ and /) for the payload. For example, POST/v3/payments{"ref":"Inv ?>"} must encode as ...SW52ID8-In0, not ...SW52ID8+In0.

The payload segment is never sent. BCB rebuilds it from the method, path and query string, and body it receives, then checks your signature against it.

Step 6: Send the request

Add these headers to every request:

HeaderValue
AuthorizationBCB-PKI <kid>
x-jws-signatureThe detached JWS from step 5 (header..signature).
x-bcb-request-idA new UUID v4 for every request. Quote it when you contact support.
x-bcb-timestampCurrent UTC time in ISO 8601 format, for example 2026-10-16T14:41:08.547Z. Must be within 5 minutes of BCB's clock.
Content-Typeapplication/json when the request has a body.

Example:

POST /v3/payments HTTP/1.1
Host: api.uat.bcb.group
Authorization: BCB-PKI 3f1c9a52-7d0e-4b8a-9a61-2f5d7c4e8b10
x-jws-signature: eyJhbGciOiJQUzI1NiIsImtpZCI6...fQ..Qaj17O8fqlEUqdBxlHWmaZqk...
x-bcb-request-id: b1eb92de-f25e-4432-830e-81aee72b5c6c
x-bcb-timestamp: 2026-10-16T14:41:08.547Z
Content-Type: application/json

{"amount":"10.50","currency":"GBP"}
📘

Every request is verified independently

BCB verifies each request on its own merits. If any check fails, the request is rejected in full. No part of it is processed.

Reference implementations

The reference code separates what is signed (BcbPkiSigner) from where the key lives (KeySigner). Choose a key signer for your environment and the rest of your code stays the same:

Key signerKey location
LocalKeySignerPKCS#8 PEM loaded by your application (UAT and development)
GcpKmsSignerGoogle Cloud KMS key version
AwsKmsSignerAWS KMS key

TypeScript requires Node.js 18+, plus @google-cloud/kms or @aws-sdk/client-kms if you use them. Python requires 3.9+ and cryptography, plus google-cloud-kms and google-crc32c, or boto3.

import { constants, createHash, createPrivateKey, randomUUID, sign, type KeyObject } from 'node:crypto';
import type { KeyManagementServiceClient } from '@google-cloud/kms';
import { SignCommand, type KMSClient } from '@aws-sdk/client-kms';

export type BcbPkiAlgorithm = 'PS256' | 'ES256';

/** One key operation, many backends: local PEM, Google Cloud KMS, AWS KMS, or your own HSM. */
export interface KeySigner {
  readonly algorithm: BcbPkiAlgorithm;
  /** Returns the JWS signature bytes: RSA-PSS signature, or raw 64-byte R||S for ES256. */
  sign(data: Buffer): Promise<Buffer>;
}

const sha256 = (data: Buffer): Buffer => createHash('sha256').update(data).digest();

/** CRC32C (Castagnoli), used by Cloud KMS to detect corruption in transit. */
const CRC32C_TABLE = Array.from({ length: 256 }, (_, n) => {
  let c = n;
  for (let k = 0; k < 8; k++) c = c & 1 ? 0x82f63b78 ^ (c >>> 1) : c >>> 1;
  return c >>> 0;
});
export const crc32c = (data: Uint8Array): number =>
  (data.reduce((crc, byte) => CRC32C_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8), 0xffffffff) ^ 0xffffffff) >>> 0;

/** KMS services return DER-encoded ECDSA signatures; JWS ES256 needs raw R||S. */
const derToJose = (der: Buffer): Buffer => {
  let offset = der[1] & 0x80 ? 3 : 2; // skip SEQUENCE header
  const readInt = (): Buffer => {
    const length = der[offset + 1];
    const value = der.subarray(offset + 2, offset + 2 + length);
    offset += 2 + length;
    const trimmed = value[0] === 0 ? value.subarray(1) : value;
    return Buffer.concat([Buffer.alloc(32 - trimmed.length), trimmed]);
  };
  return Buffer.concat([readInt(), readInt()]);
};

const toJws = (algorithm: BcbPkiAlgorithm, signature: Buffer): Buffer =>
  algorithm === 'ES256' ? derToJose(signature) : signature;

/** PKCS#8 PEM held by your application. Prefer a KMS/HSM signer in production. */
export class LocalKeySigner implements KeySigner {
  private readonly key: KeyObject;
  readonly algorithm: BcbPkiAlgorithm;

  constructor(privateKeyPem: string) {
    this.key = createPrivateKey(privateKeyPem);
    this.algorithm = this.key.asymmetricKeyType === 'ec' ? 'ES256' : 'PS256';
  }

  async sign(data: Buffer): Promise<Buffer> {
    return this.algorithm === 'PS256'
      ? sign('sha256', data, { key: this.key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: 32 })
      : sign('sha256', data, { key: this.key, dsaEncoding: 'ieee-p1363' });
  }
}

/** Google Cloud KMS: RSA_SIGN_PSS_3072_SHA256 or RSA_SIGN_PSS_4096_SHA256 (PS256) or EC_SIGN_P256_SHA256 (ES256). */
export class GcpKmsSigner implements KeySigner {
  constructor(
    private readonly client: KeyManagementServiceClient,
    private readonly keyVersionName: string,
    readonly algorithm: BcbPkiAlgorithm,
  ) {}

  async sign(data: Buffer): Promise<Buffer> {
    const digest = sha256(data);
    const [response] = await this.client.asymmetricSign({
      name: this.keyVersionName,
      digest: { sha256: digest },
      digestCrc32c: { value: crc32c(digest) },
    });
    const signature = Buffer.from(response.signature as Uint8Array);
    // Integrity checks recommended by Google.
    if (!response.verifiedDigestCrc32c || response.name !== this.keyVersionName
      || crc32c(signature) !== Number(response.signatureCrc32c?.value)) {
      throw new Error('Cloud KMS integrity check failed');
    }
    return toJws(this.algorithm, signature);
  }
}

/** AWS KMS: KeySpec RSA_3072 or RSA_4096 (PS256) or ECC_NIST_P256 (ES256), KeyUsage SIGN_VERIFY. */
export class AwsKmsSigner implements KeySigner {
  private static readonly KMS_ALGORITHMS = { PS256: 'RSASSA_PSS_SHA_256', ES256: 'ECDSA_SHA_256' } as const;

  constructor(
    private readonly client: KMSClient,
    private readonly keyId: string,
    readonly algorithm: BcbPkiAlgorithm,
  ) {}

  async sign(data: Buffer): Promise<Buffer> {
    const { Signature } = await this.client.send(new SignCommand({
      KeyId: this.keyId,
      Message: sha256(data),
      MessageType: 'DIGEST',
      SigningAlgorithm: AwsKmsSigner.KMS_ALGORITHMS[this.algorithm],
    }));
    if (!Signature) throw new Error('AWS KMS returned no signature');
    return toJws(this.algorithm, Buffer.from(Signature));
  }
}

// --- Request signing -------------------------------------------------------------------------

const CLAIM_IAT = 'http://openbanking.org.uk/iat';
const CLAIM_TAN = 'http://openbanking.org.uk/tan';
const CLAIM_ISS = 'http://openbanking.org.uk/iss';

/** base64url, no padding. "+" becomes "-" and "/" becomes "_". */
const base64url = (buf: Buffer): string => buf.toString('base64url');

const toBuffer = (body?: Buffer | string): Buffer =>
  body === undefined ? Buffer.alloc(0) : Buffer.isBuffer(body) ? body : Buffer.from(body, 'utf8');

/** Path and query string as sent on the wire. No scheme or host. */
export const signingPath = (url: string | URL): string => {
  const parsed = new URL(url);
  return parsed.pathname + parsed.search;
};

/** Canonical signing payload: METHOD || path and query || raw body bytes, with nothing between them. */
export const buildSigningPayload = (method: string, path: string, body?: Buffer | string): Buffer =>
  Buffer.concat([Buffer.from(method.toUpperCase(), 'utf8'), Buffer.from(path, 'utf8'), toBuffer(body)]);

export interface SignedRequest {
  headers: Record<string, string>;
  body: Buffer; // Send exactly these bytes. Do not re-serialise.
}

export class BcbPkiSigner {
  constructor(
    private readonly kid: string,       // Key ID issued by BCB when your CSR was enrolled
    private readonly clientId: string,  // Client ID issued with this credential (the iss claim)
    private readonly keySigner: KeySigner,
  ) {}

  /** Signs one HTTP attempt. Every retry needs a new call: new TAN and timestamp. The path and query string are signed. */
  async signRequest(method: string, url: string | URL, body?: Buffer | string): Promise<SignedRequest> {
    const rawBody = ['GET', 'HEAD'].includes(method.toUpperCase()) ? Buffer.alloc(0) : toBuffer(body);
    const now = new Date();

    const protectedHeader = {
      alg: this.keySigner.algorithm,
      kid: this.kid,
      crit: [CLAIM_IAT, CLAIM_TAN, CLAIM_ISS],
      [CLAIM_IAT]: Math.floor(now.getTime() / 1000),
      [CLAIM_TAN]: randomUUID(),
      [CLAIM_ISS]: this.clientId,
    };

    const encodedHeader = Buffer.from(JSON.stringify(protectedHeader), 'utf8').toString('base64url');
    const encodedPayload = base64url(buildSigningPayload(method, signingPath(url), rawBody));
    const signature = await this.keySigner.sign(Buffer.from(`${encodedHeader}.${encodedPayload}`, 'ascii'));

    return {
      headers: {
        Authorization: `BCB-PKI ${this.kid}`,
        'x-jws-signature': `${encodedHeader}..${signature.toString('base64url')}`,
        'x-bcb-request-id': randomUUID(),
        'x-bcb-timestamp': now.toISOString(),
        ...(rawBody.length > 0 && { 'Content-Type': 'application/json' }),
      },
      body: rawBody,
    };
  }
}
"""BCB-PKI request signing. Key operations sit behind KeySigner, so a local key, Google Cloud KMS
or AWS KMS can be swapped without changing how requests are signed."""
import base64
import hashlib
import json
import time
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Dict, Optional, Protocol, Union
from urllib.parse import urlsplit

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature

CLAIM_IAT = "http://openbanking.org.uk/iat"
CLAIM_TAN = "http://openbanking.org.uk/tan"
CLAIM_ISS = "http://openbanking.org.uk/iss"


# --- Key signers -----------------------------------------------------------------------------

class KeySigner(Protocol):
    algorithm: str  # "PS256" or "ES256"

    def public_key_der(self) -> bytes:
        """SubjectPublicKeyInfo, DER. Used to build the CSR."""

    def sign(self, data: bytes) -> bytes:
        """Sign SHA-256(data). Returns X.509-style bytes: RSA-PSS signature, or DER-encoded ECDSA."""


def algorithm_for(public_key_der: bytes) -> str:
    """Derive the JWS algorithm from the key itself, so it can never drift from the enrolled key."""
    key = serialization.load_der_public_key(public_key_der)
    if isinstance(key, rsa.RSAPublicKey) and key.key_size >= 2048:
        return "PS256"
    if isinstance(key, ec.EllipticCurvePublicKey) and isinstance(key.curve, ec.SECP256R1):
        return "ES256"
    raise ValueError("Unsupported key: use RSA (2048 bits or more) or EC P-256")


class LocalKeySigner:
    """PKCS#8 PEM private key held by your application. Prefer a KMS/HSM signer in production."""

    def __init__(self, private_key_pem: bytes):
        self._key = serialization.load_pem_private_key(private_key_pem, password=None)
        self.algorithm = algorithm_for(self.public_key_der())

    def public_key_der(self) -> bytes:
        return self._key.public_key().public_bytes(
            serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)

    def sign(self, data: bytes) -> bytes:
        if self.algorithm == "PS256":
            return self._key.sign(data, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=32), hashes.SHA256())
        return self._key.sign(data, ec.ECDSA(hashes.SHA256()))


class GcpKmsSigner:
    """Google Cloud KMS key version with purpose ASYMMETRIC_SIGN.
    Algorithm RSA_SIGN_PSS_3072_SHA256 or RSA_SIGN_PSS_4096_SHA256 (PS256) or EC_SIGN_P256_SHA256 (ES256)."""

    def __init__(self, key_version_name: str, client=None):
        from google.cloud import kms  # pip install google-cloud-kms google-crc32c
        self._name = key_version_name
        self._client = client or kms.KeyManagementServiceClient()
        pem = self._client.get_public_key(request={"name": self._name}).pem
        self._public_der = serialization.load_pem_public_key(pem.encode()).public_bytes(
            serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
        self.algorithm = algorithm_for(self._public_der)

    def public_key_der(self) -> bytes:
        return self._public_der

    def sign(self, data: bytes) -> bytes:
        import google_crc32c
        digest = hashlib.sha256(data).digest()
        response = self._client.asymmetric_sign(request={
            "name": self._name,
            "digest": {"sha256": digest},
            "digest_crc32c": google_crc32c.value(digest),
        })
        # Integrity checks recommended by Google: the request and response were not corrupted in transit.
        if not response.verified_digest_crc32c or response.name != self._name:
            raise RuntimeError("Cloud KMS request integrity check failed")
        if google_crc32c.value(response.signature) != response.signature_crc32c:
            raise RuntimeError("Cloud KMS response integrity check failed")
        return response.signature


class AwsKmsSigner:
    """AWS KMS key with KeyUsage SIGN_VERIFY. KeySpec RSA_3072 or RSA_4096 (PS256) or ECC_NIST_P256 (ES256)."""

    _KMS_ALGORITHMS = {"PS256": "RSASSA_PSS_SHA_256", "ES256": "ECDSA_SHA_256"}

    def __init__(self, key_id: str, client=None):
        import boto3  # pip install boto3
        self._key_id = key_id
        self._client = client or boto3.client("kms")
        self._public_der = self._client.get_public_key(KeyId=key_id)["PublicKey"]
        self.algorithm = algorithm_for(self._public_der)

    def public_key_der(self) -> bytes:
        return self._public_der

    def sign(self, data: bytes) -> bytes:
        return self._client.sign(
            KeyId=self._key_id,
            Message=hashlib.sha256(data).digest(),
            MessageType="DIGEST",
            SigningAlgorithm=self._KMS_ALGORITHMS[self.algorithm],
        )["Signature"]


# --- Request signing -------------------------------------------------------------------------

def _b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def _to_jws_signature(algorithm: str, signature: bytes) -> bytes:
    """JWS ES256 needs the raw 64-byte R||S value; signers return DER."""
    if algorithm != "ES256":
        return signature
    r, s = decode_dss_signature(signature)
    return r.to_bytes(32, "big") + s.to_bytes(32, "big")


def signing_path(url: str) -> str:
    """Path and query string as sent on the wire. No scheme or host."""
    parts = urlsplit(url)
    return (parts.path or "/") + (f"?{parts.query}" if parts.query else "")


def build_signing_payload(method: str, path: str, body: bytes = b"") -> bytes:
    """Canonical signing payload: METHOD || path and query || raw body bytes, with nothing between them."""
    return method.upper().encode("utf-8") + path.encode("utf-8") + body


@dataclass(frozen=True)
class SignedRequest:
    headers: Dict[str, str]
    body: bytes  # send exactly these bytes; do not re-serialise


class BcbPkiSigner:
    def __init__(self, kid: str, client_id: str, key_signer: KeySigner):
        self._kid, self._client_id, self._key = kid, client_id, key_signer

    def sign_request(self, method: str, url: str, body: Optional[Union[bytes, str]] = None) -> SignedRequest:
        """Sign one HTTP attempt. Every retry needs a fresh call (new TAN and timestamp)."""
        raw_body = b"" if method.upper() in ("GET", "HEAD") or body is None else (
            body.encode("utf-8") if isinstance(body, str) else body
        )
        now = time.time()
        protected_header = {
            "alg": self._key.algorithm,
            "kid": self._kid,
            "crit": [CLAIM_IAT, CLAIM_TAN, CLAIM_ISS],
            CLAIM_IAT: int(now),
            CLAIM_TAN: str(uuid.uuid4()),
            CLAIM_ISS: self._client_id,
        }
        encoded_header = _b64url(json.dumps(protected_header, separators=(",", ":")).encode("utf-8"))
        encoded_payload = _b64url(build_signing_payload(method, signing_path(url), raw_body))
        signature = self._key.sign(f"{encoded_header}.{encoded_payload}".encode("ascii"))

        headers = {
            "Authorization": f"BCB-PKI {self._kid}",
            "x-jws-signature": f"{encoded_header}..{_b64url(_to_jws_signature(self._key.algorithm, signature))}",
            "x-bcb-request-id": str(uuid.uuid4()),
            "x-bcb-timestamp": datetime.fromtimestamp(now, timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
        }
        if raw_body:
            headers["Content-Type"] = "application/json"
        return SignedRequest(headers=headers, body=raw_body)

Usage:

import { KeyManagementServiceClient } from '@google-cloud/kms';
import { BcbPkiSigner, GcpKmsSigner } from './bcb-pki';

// Production: key held in Cloud KMS. For AWS: new AwsKmsSigner(new KMSClient({}), 'alias/bcb-signing-prod', 'ES256')
// For UAT with a key file: new LocalKeySigner(await loadPemFromSecretManager())
const keySigner = new GcpKmsSigner(
  new KeyManagementServiceClient(),
  process.env.BCB_KMS_KEY_VERSION!, // projects/.../cryptoKeyVersions/1
  'ES256',
);
const signer = new BcbPkiSigner(process.env.BCB_PKI_KID!, process.env.BCB_CLIENT_ID!, keySigner);

// GET: the path and query string are signed
const listUrl = 'https://api.bcb.group/v3/accounts?limit=10';
const list = await signer.signRequest('GET', listUrl);
const accounts = await fetch(listUrl, { method: 'GET', headers: list.headers });

// POST: serialise once, sign, then send the same bytes
const paymentUrl = 'https://api.bcb.group/v3/payments';
const payment = await signer.signRequest('POST', paymentUrl, JSON.stringify({ amount: '10.50', currency: 'GBP' }));
const result = await fetch(paymentUrl, { method: 'POST', headers: payment.headers, body: payment.body });
import json
import os

import requests

from bcb_pki import AwsKmsSigner, BcbPkiSigner

# Production: key held in AWS KMS. For Google Cloud: GcpKmsSigner(os.environ["BCB_KMS_KEY_VERSION"])
# For UAT with a key file: LocalKeySigner(load_pem_from_secret_manager())
key_signer = AwsKmsSigner("alias/bcb-signing-prod")
signer = BcbPkiSigner(os.environ["BCB_PKI_KID"], os.environ["BCB_CLIENT_ID"], key_signer)

# GET: the path and query string are signed
list_url = "https://api.bcb.group/v3/accounts?limit=10"
signed = signer.sign_request("GET", list_url)
accounts = requests.get(list_url, headers=signed.headers)

# POST: serialise once, sign, then send the same bytes (use data=, not json=)
payment_url = "https://api.bcb.group/v3/payments"
signed = signer.sign_request("POST", payment_url, json.dumps({"amount": "10.50", "currency": "GBP"}))
result = requests.post(payment_url, data=signed.body, headers=signed.headers)

Testing with Postman

BCB provides a Postman collection whose pre-request script signs every request with PS256. To use it:

  1. Set the collection variables bcbBaseUrl, bcbPkiKid and bcbPkiIss.
  2. Add your PKCS#8 private key to the Postman Vault as bcbPkiPrivateKeyPem, then enable Vault support in scripts (Vault > Settings).
  3. Send from the Postman desktop app or Desktop Agent so the request comes from an IP on your allow-list. The Postman Cloud Agent and monitors send from Postman's own addresses and will be rejected.
  4. Use a raw JSON body for signed requests. Percent-encode query values that contain spaces or non-ASCII characters.

Use a dedicated UAT key for Postman. Do not load a production private key into a desktop tool.

Replay protection and retries

Each TAN can be used once per key. BCB remembers it for:

MethodsTAN window
GET, HEAD120 seconds
POST, PUT, PATCH, DELETE600 seconds

When you retry a request (for example after a timeout or a 503), sign it again. Each attempt needs a new TAN, iat, x-bcb-timestamp and x-bcb-request-id. Resending the same headers will be rejected as a replay.

Replay protection stops a captured request from being resent. It does not stop your own system from sending the same payment twice. Keep using your business idempotency key across retries, as described in Idempotency and Duplicate Prevention.

Errors and troubleshooting

StatusMeaningWhat to do
401Verification failed: bad signature, unknown or revoked kid, expired key, iat or timestamp out of range, reused TAN, or source IP not on the allow-list.Do not retry unchanged. Work through the checklist below.
403The request was authenticated, but the service account is not permitted to perform this operation.Check the service account's roles and counterparty access in the Client Console.
503BCB could not complete verification. BCB never lets a request through when a check cannot run.Retry with exponential backoff. Re-sign each attempt.

Treat 401 and 403 as authentication failures and alert on them. Do not retry them in a loop.

Signature checklist

  • The method is uppercase, and the path starts with /, includes the query string exactly as sent, and excludes the scheme and host.
  • The body you signed is byte-for-byte the body you sent. Look for re-serialisation, a trailing newline or a changed character encoding.
  • The header, payload, and signature segments all use base64url (-, _). None of them is padded.
  • alg matches your key type, and you are not using RS256.
  • For PS256, the salt length is 32. For ES256, the signature is raw R || S (64 bytes), not DER.
  • The kid in the header is the same as the one in Authorization.
  • Your server clock is synchronised with NTP.
  • The request leaves from an IP address on your allow-list. Check proxies, NAT gateways and failover regions.

Include the x-bcb-request-id value when you contact support.

Key rotation and revocation

  • Rotate before expiry. Keys last at most 365 days. Create a new key (or KMS key version), enrol its CSR, deploy the new key and kid, confirm traffic is succeeding, then revoke the old key. Both keys work during the overlap.
  • Revoke immediately on suspected compromise. Revoke the key in the Client Console. Revocation takes effect at once. Then enrol a replacement.
  • Use one key per environment and per system. Separate keys for UAT and production, and for different applications, limit the impact of a leak and make audit trails clearer.
  • Keep the allow-list current. Add new egress IPs before you move infrastructure, and remove addresses you no longer use.

Security recommendations

  • In production, keep the key in an HSM or cloud KMS (Option A), so the private key never sits in application memory.
  • Restrict who and what can use the signing key, and log every use.
  • Never log the private key or full x-jws-signature values. Logging x-bcb-request-id is fine and helps with support.
  • Always call BCB over HTTPS. Do not disable certificate validation.