Skip to content
RDCpassRDCpassMinistère de l’Économie NumériqueMinistère de l’Économie Numérique
Guides : Authentication
On this page

Authentication

In production, every request to an RDCPASS third-party API must satisfy three independent security layers at once — a valid HMAC-SHA256 signature, a client certificate presented over mutual TLS, and AES-256-GCM payload encryption. These are not alternative options — a request missing any one of them is rejected before it reaches identity services.

Credential set

Test

# Test set: key ID, signing secret, encryption key
RDCPASS_KEY_ID=key_test_…
RDCPASS_SIGNING_SECRET=sk_test_…
RDCPASS_ENCRYPTION_KEY=ek_test_…

Production

RDCPASS_KEY_ID=key_live_…
RDCPASS_SIGNING_SECRET=sk_live_…
RDCPASS_ENCRYPTION_KEY=ek_live_…
Key IDkey_test_ or key_live_
Names the set. It stays readable in the console.
Signing secretsk_test_ or sk_live_
Signs every call. Shown once; afterwards, only its last four characters.
Encryption keyek_test_ or ek_live_
Encrypts the payload. Shown once, like the secret.

The test set is issued when the application is created. The production set requires an approved business file, an approved application and at least one production IP address, then a confirmation of your identity.

RDCpass console, Credentials tab of the Mosala Mobile application in test: two active sets, key_test_nZpe3tqcWAQU and key_test_mb7Qx2LdT4vA, with their author, creation date, last use and Active status.RDCpass console, Credentials tab of the Mosala Mobile application in test: two active sets, key_test_nZpe3tqcWAQU and key_test_mb7Qx2LdT4vA, with their author, creation date, last use and Active status.RDCpass console, Credentials tab of the Mosala Mobile application in test: two active sets, key_test_nZpe3tqcWAQU and key_test_mb7Qx2LdT4vA, with their author, creation date, last use and Active status.
An application’s Credentials tab, in the console.

Required headers

The three layers below are enforced through a small set of custom headers, sent on every request:

HeaderSent byDescription
X-RDCPASS-Key-IdClientYour application's key ID. Not a secret — safe to appear in logs, comparable to an AWS Access Key ID. It tells RDCPASS which application's signing secret to verify your signature against.
X-RDCPASS-TimestampClientUnix seconds at request time. Rejected with 401 if more than 5 minutes off server time.
X-RDCPASS-NonceClientAny unique string per request. A reused nonce is treated as a replay attack and rejected with 401.
X-RDCPASS-IVClient & serverBase64-encoded 12-byte AES-GCM initialization vector. The client sends one on the request; the server returns a fresh one on the response.
X-RDCPASS-SignatureClientHex-encoded HMAC-SHA256 signature over the request, computed as described below.

1. Key ID + HMAC-SHA256 request signing

X-RDCPASS-Key-Id identifies which application is calling — it's an identifier, not a secret, and it's safe to appear in logs (comparable to an AWS Access Key ID). It simply tells RDCPASS which application's signing secret to verify your signature against.

The actual authentication is an HMAC-SHA256 signature over a canonical string:

method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body

body is the exact raw bytes sent on the wire — and because payload encryption also applies to every request (see section 3), that means the ciphertext bytes, not the plaintext. Encrypt the request body first, then sign the encrypted result. Signing the plaintext produces a signature the server can never reproduce, since it only ever sees the encrypted body.

The signature is hex-encoded and sent as X-RDCPASS-Signature. X-RDCPASS-Timestamp must be within 5 minutes of server time, and X-RDCPASS-Nonce must be unique per request — a reused nonce is rejected with 401 as a replay attempt.

A call that is wrongly signed, or signed with a revoked set, is refused with invalid_signature. It is not billed.

Python

import hashlib
import hmac
import os
import time
import uuid

def sign_request(method: str, path: str, plaintext_body: bytes, key_id: str, secret_key: str, payload_key: bytes):
    # Payload encryption applies to every request. Encrypt FIRST, then sign
    # the resulting ciphertext — never sign the plaintext body.
    encrypted_body, iv_b64 = encrypt_payload(plaintext_body, payload_key)  # see AES-256-GCM below

    timestamp = str(int(time.time()))
    nonce = str(uuid.uuid4())

    # string_to_sign = method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body
    # "body" here is the exact bytes going on the wire — the ciphertext,
    # not the plaintext — concatenated as raw bytes, not re-encoded.
    prefix = f"{method.upper()}\n{path}\n{timestamp}\n{nonce}\n".encode("utf-8")
    string_to_sign = prefix + encrypted_body

    signature = hmac.new(
        secret_key.encode("utf-8"),
        string_to_sign,
        hashlib.sha256,
    ).hexdigest()

    return {
        "headers": {
            "X-RDCPASS-Key-Id": key_id,
            "X-RDCPASS-Timestamp": timestamp,
            "X-RDCPASS-Nonce": nonce,
            "X-RDCPASS-IV": iv_b64,
            "X-RDCPASS-Signature": signature,
        },
        "body": encrypted_body,
    }

Node.js

const crypto = require('crypto')

function signRequest(method, path, plaintextBody, keyId, secretKey, payloadKey) {
  // Payload encryption applies to every request. Encrypt FIRST, then sign
  // the resulting ciphertext — never sign the plaintext body.
  const { encryptedBody, ivB64 } = encryptPayload(plaintextBody, payloadKey) // see AES-256-GCM below

  const timestamp = String(Math.floor(Date.now() / 1000))
  const nonce = crypto.randomUUID()

  // stringToSign = method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body
  // "body" here is the exact bytes going on the wire — the ciphertext,
  // not the plaintext — concatenated as raw bytes, not re-encoded.
  const prefix = Buffer.from(`${method.toUpperCase()}\n${path}\n${timestamp}\n${nonce}\n`, 'utf-8')
  const stringToSign = Buffer.concat([prefix, encryptedBody])

  const signature = crypto.createHmac('sha256', secretKey).update(stringToSign).digest('hex')

  return {
    headers: {
      'X-RDCPASS-Key-Id': keyId,
      'X-RDCPASS-Timestamp': timestamp,
      'X-RDCPASS-Nonce': nonce,
      'X-RDCPASS-IV': ivB64,
      'X-RDCPASS-Signature': signature,
    },
    body: encryptedBody,
  }
}

Go

package main

import (
	"crypto/hmac"
	crand "crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"strings"
	"time"
)

// randomNonce needs only to be unique per request, not RFC 4122-shaped —
// a random hex string avoids pulling in a UUID package for this alone.
func randomNonce() string {
	b := make([]byte, 16)
	if _, err := io.ReadFull(crand.Reader, b); err != nil {
		panic(err)
	}
	return hex.EncodeToString(b)
}

func signRequest(method, path string, plaintextBody, keyID, secretKey string, payloadKey []byte) map[string]any {
	// Payload encryption applies to every request. Encrypt FIRST, then sign
	// the resulting ciphertext — never sign the plaintext body.
	encryptedBody, ivB64 := encryptPayload([]byte(plaintextBody), payloadKey) // see AES-256-GCM below

	timestamp := fmt.Sprintf("%d", time.Now().Unix())
	nonce := randomNonce()

	// stringToSign = method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body
	// "body" here is the exact bytes going on the wire — the ciphertext,
	// not the plaintext — concatenated as raw bytes, not re-encoded.
	prefix := fmt.Sprintf("%s\n%s\n%s\n%s\n", strings.ToUpper(method), path, timestamp, nonce)
	stringToSign := append([]byte(prefix), encryptedBody...)

	mac := hmac.New(sha256.New, []byte(secretKey))
	mac.Write(stringToSign)
	signature := hex.EncodeToString(mac.Sum(nil))

	return map[string]any{
		"headers": map[string]string{
			"X-RDCPASS-Key-Id":    keyID,
			"X-RDCPASS-Timestamp": timestamp,
			"X-RDCPASS-Nonce":     nonce,
			"X-RDCPASS-IV":        ivB64,
			"X-RDCPASS-Signature": signature,
		},
		"body": encryptedBody,
	}
}

Java

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HexFormat;
import java.util.Map;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

class SignRequest {
    static Map<String, Object> signRequest(String method, String path, byte[] plaintextBody, String keyId, String secretKey, byte[] payloadKey) throws Exception {
        // Payload encryption applies to every request. Encrypt FIRST, then
        // sign the resulting ciphertext — never sign the plaintext body.
        EncryptPayload.Encrypted encrypted = EncryptPayload.encryptPayload(plaintextBody, payloadKey); // see AES-256-GCM below
        byte[] encryptedBody = encrypted.ciphertext();
        String ivB64 = encrypted.ivB64();

        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        String nonce = UUID.randomUUID().toString();

        // prefix + body = method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body
        // "body" here is the exact bytes going on the wire — the ciphertext,
        // not the plaintext — concatenated as raw bytes, not re-encoded.
        String prefix = method.toUpperCase() + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n";
        byte[] prefixBytes = prefix.getBytes(StandardCharsets.UTF_8);
        byte[] stringToSign = new byte[prefixBytes.length + encryptedBody.length];
        System.arraycopy(prefixBytes, 0, stringToSign, 0, prefixBytes.length);
        System.arraycopy(encryptedBody, 0, stringToSign, prefixBytes.length, encryptedBody.length);

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        String signature = HexFormat.of().formatHex(mac.doFinal(stringToSign));

        return Map.of(
            "headers", Map.of(
                "X-RDCPASS-Key-Id", keyId,
                "X-RDCPASS-Timestamp", timestamp,
                "X-RDCPASS-Nonce", nonce,
                "X-RDCPASS-IV", ivB64,
                "X-RDCPASS-Signature", signature
            ),
            "body", encryptedBody
        );
    }
}

Rust

use hmac::{Hmac, Mac};
use sha2::Sha256;
use uuid::Uuid;
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

type HmacSha256 = Hmac<Sha256>;

struct SignedRequest {
    headers: HashMap<&'static str, String>,
    body: Vec<u8>,
}

fn sign_request(method: &str, path: &str, plaintext_body: &[u8], key_id: &str, secret_key: &str, payload_key: &[u8]) -> SignedRequest {
    // Payload encryption applies to every request. Encrypt FIRST, then sign
    // the resulting ciphertext — never sign the plaintext body.
    let (encrypted_body, iv_b64) = encrypt_payload(plaintext_body, payload_key); // see AES-256-GCM below

    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs().to_string();
    let nonce = Uuid::new_v4().to_string();

    // string_to_sign = method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body
    // "body" here is the exact bytes going on the wire — the ciphertext,
    // not the plaintext — concatenated as raw bytes, not re-encoded.
    let prefix = format!("{}\n{}\n{}\n{}\n", method.to_uppercase(), path, timestamp, nonce);
    let mut string_to_sign = prefix.into_bytes();
    string_to_sign.extend_from_slice(&encrypted_body);

    let mut mac = HmacSha256::new_from_slice(secret_key.as_bytes()).expect("HMAC can take key of any size");
    mac.update(&string_to_sign);
    let signature = hex::encode(mac.finalize().into_bytes());

    SignedRequest {
        headers: HashMap::from([
            ("X-RDCPASS-Key-Id", key_id.to_string()),
            ("X-RDCPASS-Timestamp", timestamp),
            ("X-RDCPASS-Nonce", nonce),
            ("X-RDCPASS-IV", iv_b64),
            ("X-RDCPASS-Signature", signature),
        ]),
        body: encrypted_body,
    }
}

PHP

<?php

// nonce needs only to be unique per request, not RFC 4122-shaped -- a
// random hex string avoids pulling in a UUID package for this alone.
function signRequest(string $method, string $path, string $plaintextBody, string $keyId, string $secretKey, string $payloadKey): array
{
    // Payload encryption applies to every request. Encrypt FIRST, then
    // sign the resulting ciphertext — never sign the plaintext body.
    [$encryptedBody, $ivB64] = encryptPayload($plaintextBody, $payloadKey); // see AES-256-GCM below

    $timestamp = (string) time();
    $nonce = bin2hex(random_bytes(16));

    // stringToSign = method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body
    // "body" here is the exact bytes going on the wire — the ciphertext,
    // not the plaintext — concatenated as raw bytes, not re-encoded.
    $prefix = strtoupper($method) . "\n" . $path . "\n" . $timestamp . "\n" . $nonce . "\n";
    $stringToSign = $prefix . $encryptedBody;

    $signature = hash_hmac('sha256', $stringToSign, $secretKey);

    return [
        'headers' => [
            'X-RDCPASS-Key-Id' => $keyId,
            'X-RDCPASS-Timestamp' => $timestamp,
            'X-RDCPASS-Nonce' => $nonce,
            'X-RDCPASS-IV' => $ivB64,
            'X-RDCPASS-Signature' => $signature,
        ],
        'body' => $encryptedBody,
    ];
}

C#

using System.Security.Cryptography;
using System.Text;

public static class SignRequest
{
    public static (Dictionary<string, string> Headers, byte[] Body) Sign(
        string method, string path, byte[] plaintextBody, string keyId, string secretKey, byte[] payloadKey)
    {
        // Payload encryption applies to every request. Encrypt FIRST, then
        // sign the resulting ciphertext — never sign the plaintext body.
        var (encryptedBody, ivB64) = EncryptPayload.Encrypt(plaintextBody, payloadKey); // see AES-256-GCM below

        var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        var nonce = Guid.NewGuid().ToString();

        // stringToSign = method + "\n" + path + "\n" + timestamp + "\n" + nonce + "\n" + body
        // "body" here is the exact bytes going on the wire — the ciphertext,
        // not the plaintext — concatenated as raw bytes, not re-encoded.
        var prefix = Encoding.UTF8.GetBytes($"{method.ToUpperInvariant()}\n{path}\n{timestamp}\n{nonce}\n");
        var stringToSign = new byte[prefix.Length + encryptedBody.Length];
        Buffer.BlockCopy(prefix, 0, stringToSign, 0, prefix.Length);
        Buffer.BlockCopy(encryptedBody, 0, stringToSign, prefix.Length, encryptedBody.Length);

        var signature = Convert.ToHexString(
            HMACSHA256.HashData(Encoding.UTF8.GetBytes(secretKey), stringToSign)).ToLowerInvariant();

        var headers = new Dictionary<string, string>
        {
            ["X-RDCPASS-Key-Id"] = keyId,
            ["X-RDCPASS-Timestamp"] = timestamp,
            ["X-RDCPASS-Nonce"] = nonce,
            ["X-RDCPASS-IV"] = ivB64,
            ["X-RDCPASS-Signature"] = signature,
        };

        return (headers, encryptedBody);
    }
}

Contract to be confirmed by the API team.

2. mTLS client certificates

Every request must also present a client certificate issued by RDCPASS, in Sandbox as well as in Production. This is mutual TLS: RDCPASS authenticates to you via its server certificate as usual, and you authenticate to RDCPASS via a certificate it has issued, on every connection.

This matters because it's a possession-based credential layered on top of a knowledge-based one. A signing secret is a string — if it leaks, anyone who has it can compute valid signatures. A leaked secret alone is still useless without also possessing the matching private key and certificate, since the request never reaches the layer that checks the signature unless the mTLS handshake succeeds first.

Your servers also authenticate with a client certificate, in both environments. Generate the private key and the CSR on your side, upload the CSR in the console: RDCpass issues a certificate valid for 12 months. The private key never leaves your servers.

Terminal
openssl req -new -newkey rsa:2048 -nodes -keyout client.key -out client.csr -subj "/CN=api.example.cd"

Accepted keys: RSA of 2048 bits or more, or ECDSA on P-256, P-384 or P-521. The console warns you 30, 7 and 1 day before expiry, in the environment the certificate belongs to.

How certificates are issued

Generate a private key and a certificate signing request (CSR) on your own infrastructure and upload only the CSR, on the Credentials screen of the application. RDCPASS signs it and the certificate is bound to that application. The private key never leaves your servers. Sandbox issues from the moment the application exists; Production after your production access is approved. See Going to production for the full sequence.

Sandbox and Production are signed by different authorities

The two environments have their own certificate authority, so a Sandbox certificate is refused in Production and the other way round — and so is the chain you install to trust RDCPASS. Download the chain of the environment you are calling, and issue a certificate for each. This is deliberate: a certificate minted to rehearse against synthetic data must carry no privilege over real citizen data.

The certificate and the signing secret must belong to the same application — RDCPASS rejects any request where the mTLS client certificate and the X-RDCPASS-Key-Id resolve to different applications. This is deliberate: it stops a leaked signing secret from one application being combined with a different application's certificate to forge a valid-looking request.

3. AES-256-GCM payload encryption

Every request body is encrypted client-side with AES-256-GCM, using the application's encryption key, before it is signed (section 1). The IV is 12 random bytes, base64-encoded, sent in the X-RDCPASS-IV header — it must be freshly generated for every request and never reused with the same key.

Responses are encrypted the same way: RDCPASS generates its own fresh IV per response, returned in its own X-RDCPASS-IV header, and encrypts the response body with the same encryption key. Decrypt it the same way you encrypted the request.

Python

import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def encrypt_payload(plaintext: bytes, payload_key: bytes) -> tuple[bytes, str]:
    # 12 random bytes, generated fresh for every request. Never reuse an
    # IV with the same key — doing so breaks GCM's confidentiality guarantee.
    iv = os.urandom(12)

    aesgcm = AESGCM(payload_key)  # payload_key is 32 bytes (AES-256)
    ciphertext = aesgcm.encrypt(iv, plaintext, associated_data=None)
    # ciphertext already includes the 16-byte GCM auth tag appended —
    # this is the exact byte string that becomes the request body.

    return ciphertext, base64.b64encode(iv).decode("ascii")

def decrypt_response(ciphertext: bytes, iv_b64: str, payload_key: bytes) -> bytes:
    # The server encrypts its response the same way, with its own fresh IV
    # returned in the X-RDCPASS-IV response header.
    iv = base64.b64decode(iv_b64)
    aesgcm = AESGCM(payload_key)
    return aesgcm.decrypt(iv, ciphertext, associated_data=None)

Node.js

const crypto = require('crypto')

function encryptPayload(plaintext, payloadKey) {
  // 12 random bytes, generated fresh for every request. Never reuse an
  // IV with the same key — doing so breaks GCM's confidentiality guarantee.
  const iv = crypto.randomBytes(12)

  const cipher = crypto.createCipheriv('aes-256-gcm', payloadKey, iv) // payloadKey is 32 bytes (AES-256)
  const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()])
  // Node returns the auth tag separately — append it so the wire format
  // matches every other language (ciphertext with the 16-byte GCM tag
  // appended at the end).
  const encryptedBody = Buffer.concat([ciphertext, cipher.getAuthTag()])

  return { encryptedBody, ivB64: iv.toString('base64') }
}

function decryptResponse(ciphertext, ivB64, payloadKey) {
  // The server encrypts its response the same way, with its own fresh IV
  // returned in the X-RDCPASS-IV response header.
  const iv = Buffer.from(ivB64, 'base64')
  const authTag = ciphertext.subarray(ciphertext.length - 16)
  const encrypted = ciphertext.subarray(0, ciphertext.length - 16)

  const decipher = crypto.createDecipheriv('aes-256-gcm', payloadKey, iv)
  decipher.setAuthTag(authTag)
  return Buffer.concat([decipher.update(encrypted), decipher.final()])
}

Go

package main

import (
	"crypto/aes"
	"crypto/cipher"
	crand "crypto/rand"
	"encoding/base64"
	"io"
)

func encryptPayload(plaintext, payloadKey []byte) (encryptedBody []byte, ivB64 string) {
	// 12 random bytes, generated fresh for every request. Never reuse an
	// IV with the same key — doing so breaks GCM's confidentiality guarantee.
	iv := make([]byte, 12)
	if _, err := io.ReadFull(crand.Reader, iv); err != nil {
		panic(err)
	}

	block, err := aes.NewCipher(payloadKey) // payloadKey is 32 bytes (AES-256)
	if err != nil {
		panic(err)
	}
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err)
	}
	// Seal appends the 16-byte GCM auth tag to the end of the ciphertext —
	// this is the exact byte string that becomes the request body.
	ciphertext := aesgcm.Seal(nil, iv, plaintext, nil)

	return ciphertext, base64.StdEncoding.EncodeToString(iv)
}

func decryptResponse(ciphertext []byte, ivB64 string, payloadKey []byte) []byte {
	// The server encrypts its response the same way, with its own fresh IV
	// returned in the X-RDCPASS-IV response header.
	iv, err := base64.StdEncoding.DecodeString(ivB64)
	if err != nil {
		panic(err)
	}
	block, err := aes.NewCipher(payloadKey)
	if err != nil {
		panic(err)
	}
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err)
	}
	plaintext, err := aesgcm.Open(nil, iv, ciphertext, nil)
	if err != nil {
		panic(err)
	}
	return plaintext
}

Java

import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

class EncryptPayload {
    record Encrypted(byte[] ciphertext, String ivB64) {}

    static Encrypted encryptPayload(byte[] plaintext, byte[] payloadKey) throws Exception {
        // 12 random bytes, generated fresh for every request. Never reuse
        // an IV with the same key — doing so breaks GCM's confidentiality
        // guarantee.
        byte[] iv = new byte[12];
        new SecureRandom().nextBytes(iv);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(payloadKey, "AES"), new GCMParameterSpec(128, iv)); // payloadKey is 32 bytes (AES-256)
        // doFinal appends the 16-byte GCM auth tag to the end of the
        // ciphertext — this is the exact byte string that becomes the
        // request body.
        byte[] ciphertext = cipher.doFinal(plaintext);

        return new Encrypted(ciphertext, Base64.getEncoder().encodeToString(iv));
    }

    static byte[] decryptResponse(byte[] ciphertext, String ivB64, byte[] payloadKey) throws Exception {
        // The server encrypts its response the same way, with its own
        // fresh IV returned in the X-RDCPASS-IV response header.
        byte[] iv = Base64.getDecoder().decode(ivB64);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(payloadKey, "AES"), new GCMParameterSpec(128, iv));
        return cipher.doFinal(ciphertext);
    }
}

Rust

use aes_gcm::aead::{Aead, AeadCore, KeyInit, OsRng};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use base64::Engine;

fn encrypt_payload(plaintext: &[u8], payload_key: &[u8]) -> (Vec<u8>, String) {
    // 12 random bytes, generated fresh for every request. Never reuse an
    // IV with the same key — doing so breaks GCM's confidentiality guarantee.
    let iv = Aes256Gcm::generate_nonce(&mut OsRng);

    let key = Key::<Aes256Gcm>::from_slice(payload_key); // payload_key is 32 bytes (AES-256)
    let cipher = Aes256Gcm::new(key);
    // encrypt() appends the 16-byte GCM auth tag to the end of the
    // ciphertext — this is the exact byte string that becomes the request
    // body.
    let ciphertext = cipher.encrypt(&iv, plaintext).expect("encryption failure");

    (ciphertext, base64::engine::general_purpose::STANDARD.encode(iv))
}

fn decrypt_response(ciphertext: &[u8], iv_b64: &str, payload_key: &[u8]) -> Vec<u8> {
    // The server encrypts its response the same way, with its own fresh IV
    // returned in the X-RDCPASS-IV response header.
    let iv_bytes = base64::engine::general_purpose::STANDARD.decode(iv_b64).expect("invalid base64");
    let iv = Nonce::from_slice(&iv_bytes);
    let key = Key::<Aes256Gcm>::from_slice(payload_key);
    let cipher = Aes256Gcm::new(key);
    cipher.decrypt(iv, ciphertext).expect("decryption failure")
}

PHP

<?php

function encryptPayload(string $plaintext, string $payloadKey): array
{
    // 12 random bytes, generated fresh for every request. Never reuse an
    // IV with the same key — doing so breaks GCM's confidentiality guarantee.
    $iv = random_bytes(12);

    $tag = '';
    $ciphertext = openssl_encrypt(
        $plaintext,
        'aes-256-gcm',
        $payloadKey, // 32 bytes (AES-256)
        OPENSSL_RAW_DATA,
        $iv,
        $tag,
        '',
        16 // 16-byte GCM auth tag
    );
    // openssl_encrypt() returns the auth tag separately via the $tag
    // reference parameter — append it so the wire format matches every
    // other language (ciphertext with the 16-byte GCM tag appended at
    // the end).
    $encryptedBody = $ciphertext . $tag;

    return [$encryptedBody, base64_encode($iv)];
}

function decryptResponse(string $ciphertext, string $ivB64, string $payloadKey): string
{
    // The server encrypts its response the same way, with its own fresh IV
    // returned in the X-RDCPASS-IV response header.
    $iv = base64_decode($ivB64);
    $tag = substr($ciphertext, -16);
    $encrypted = substr($ciphertext, 0, -16);

    return openssl_decrypt($encrypted, 'aes-256-gcm', $payloadKey, OPENSSL_RAW_DATA, $iv, $tag);
}

C#

using System.Security.Cryptography;

public static class EncryptPayload
{
    public static (byte[] EncryptedBody, string IvB64) Encrypt(byte[] plaintext, byte[] payloadKey)
    {
        // 12 random bytes, generated fresh for every request. Never reuse an
        // IV with the same key — doing so breaks GCM's confidentiality guarantee.
        var iv = RandomNumberGenerator.GetBytes(12);

        var ciphertext = new byte[plaintext.Length];
        var tag = new byte[16]; // 16-byte GCM auth tag
        using var aes = new AesGcm(payloadKey); // payloadKey is 32 bytes (AES-256)
        aes.Encrypt(iv, plaintext, ciphertext, tag);

        // AesGcm keeps the tag separate — append it so the wire format
        // matches every other language (ciphertext with the 16-byte GCM
        // tag appended at the end).
        var encryptedBody = new byte[ciphertext.Length + tag.Length];
        Buffer.BlockCopy(ciphertext, 0, encryptedBody, 0, ciphertext.Length);
        Buffer.BlockCopy(tag, 0, encryptedBody, ciphertext.Length, tag.Length);

        return (encryptedBody, Convert.ToBase64String(iv));
    }

    public static byte[] Decrypt(byte[] ciphertext, string ivB64, byte[] payloadKey)
    {
        // The server encrypts its response the same way, with its own fresh
        // IV returned in the X-RDCPASS-IV response header.
        var iv = Convert.FromBase64String(ivB64);
        var tag = ciphertext[^16..];
        var encrypted = ciphertext[..^16];

        var plaintext = new byte[encrypted.Length];
        using var aes = new AesGcm(payloadKey);
        aes.Decrypt(iv, encrypted, tag, plaintext);
        return plaintext;
    }
}

Contract to be confirmed by the API team.

Putting it together

A fully authenticated request carries all five headers above, with a ciphertext body:

Example request
POST /v1/kyc/validations HTTP/1.1
Host: api.rdcpass.cd
Content-Type: application/octet-stream
X-RDCPASS-Key-Id: key_live_9f2ac3d0e1b74a2f
X-RDCPASS-Timestamp: 1735297420
X-RDCPASS-Nonce: 5f3e2a1b-8c9d-4e6f-a1b2-3c4d5e6f7a8b
X-RDCPASS-IV: 8k2LpQz9vXbNc3Rt5gYwZQ==
X-RDCPASS-Signature: 3f7a9c2e1b8d4f6a0e5c7b9d2a4f6e8c1b3d5f7a9c0e2b4d6f8a1c3e5b7d9f0a

<AES-256-GCM ciphertext bytes — the encrypted, signed request body>

Contract to be confirmed by the API team.

A request must pass all three checks — a valid HMAC signature, a valid client certificate bound to the same application, and, once decrypted, a well-formed request body — before it reaches RDCPASS's identity services. Any one failing on its own is enough for the request to be rejected.

Rotate and revoke

  1. Create a second set: the old one stays active.
  2. Deploy the new values to your servers, then check your calls.
  3. Revoke the old set. Revocation is immediate and final.

IP address list

Optional in test, required in production: while it is empty, every production call is refused. It accepts public IPv4 and IPv6 addresses, ranges no wider than /24 and /48, each with a 60-character label.

Esc