Encrypted Callbacks
When encryption is switched on for an API key, the data in every callback sent for that key is unreadable until you decrypt it. Encryption always comes with signing, so verify the signature before you decrypt.
What an encrypted callback looks like​
With encryption on, the body is an envelope in place of the usual JSON. The headers are the same as on a signed callback, and the signature is computed over this envelope exactly as received.
{
"encrypted": true,
"algorithm": "AES-256-GCM",
"iv": "<base64, 12 bytes>",
"tag": "<base64, 16 bytes>",
"data": "<base64 ciphertext>"
}
| Field | Meaning |
|---|---|
encrypted | Always true on an encrypted callback |
algorithm | Always AES-256-GCM |
iv | The initialisation vector, new for every callback |
tag | The authentication tag; decryption fails if the envelope was altered |
data | The encrypted callback JSON |
Handle it​
- Verify the signature and timestamp against the raw body, as in Signed Callbacks. Reject on failure without decrypting.
- Parse the envelope and base64-decode
iv,taganddata. - Decrypt
datawith AES-256-GCM, using the key from yourencryption_secret(hex-decoded to 32 bytes), theivand thetag. Reject the callback if decryption fails. - The result is the usual callback JSON. Parse it and carry on as before, including the
transactionnumbercheck.
Verify the signature before you decrypt. If the signature check fails, reject the callback without decrypting it.
Hex-decode the encryption_secret to 32 bytes before you use it as the key. Do not use it as text.
- PHP
- Node
- Python
- Java
- C# (.NET)
- Go
// after the signature check
$envelope = json_decode($raw, true);
$json = openssl_decrypt(
base64_decode($envelope['data']),
'aes-256-gcm',
hex2bin($encryptionSecret),
OPENSSL_RAW_DATA,
base64_decode($envelope['iv']),
base64_decode($envelope['tag'])
);
if ($json === false) {
http_response_code(400);
exit;
}
$payload = json_decode($json, true);
// after the signature check
const envelope = JSON.parse(req.body);
const decipher = crypto.createDecipheriv(
'aes-256-gcm',
Buffer.from(encryptionSecret, 'hex'),
Buffer.from(envelope.iv, 'base64')
);
decipher.setAuthTag(Buffer.from(envelope.tag, 'base64'));
// final() throws if the envelope was altered or the secret is wrong
const json = Buffer.concat([
decipher.update(Buffer.from(envelope.data, 'base64')),
decipher.final(),
]).toString('utf8');
const payload = JSON.parse(json);
Node takes the tag separately, through setAuthTag, before final() is called.
Needs the cryptography package (pip install cryptography); the standard library has no AES-GCM.
import base64
import json
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def decrypt_callback(raw_body: bytes, encryption_secret: str) -> dict:
# call this only after verify_signature() has passed
envelope = json.loads(raw_body)
key = bytes.fromhex(encryption_secret) # 64 hex chars -> 32 bytes
iv = base64.b64decode(envelope["iv"])
tag = base64.b64decode(envelope["tag"])
data = base64.b64decode(envelope["data"])
# raises InvalidTag if the envelope was altered or the secret is wrong
plain = AESGCM(key).decrypt(iv, data + tag, None)
return json.loads(plain)
This library expects the tag appended to the ciphertext, which is why the sample passes data + tag. Catch InvalidTag and reject the callback.
Uses the JDK's own AES-GCM. The JSON parsing below uses Jackson; any JSON library works.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HexFormat;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
static String decryptCallback(byte[] rawBody, String encryptionSecret) throws Exception {
// call this only after verifySignature() has passed
JsonNode envelope = new ObjectMapper().readTree(rawBody);
byte[] key = HexFormat.of().parseHex(encryptionSecret); // 64 hex chars -> 32 bytes
byte[] iv = Base64.getDecoder().decode(envelope.get("iv").asText());
byte[] tag = Base64.getDecoder().decode(envelope.get("tag").asText());
byte[] data = Base64.getDecoder().decode(envelope.get("data").asText());
// the JDK expects the tag appended to the ciphertext
byte[] dataAndTag = new byte[data.length + tag.length];
System.arraycopy(data, 0, dataAndTag, 0, data.length);
System.arraycopy(tag, 0, dataAndTag, data.length, tag.length);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
new GCMParameterSpec(128, iv)); // 128 bit tag
// throws AEADBadTagException if the envelope was altered or the secret is wrong
return new String(cipher.doFinal(dataAndTag), StandardCharsets.UTF_8);
}
The 128 in GCMParameterSpec is the tag length in bits (16 bytes). Catch AEADBadTagException and reject the callback. The returned string is the usual callback JSON.
Uses AesGcm from the base class library.
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
static string DecryptCallback(byte[] rawBody, string encryptionSecret)
{
// call this only after VerifySignature() has passed
using JsonDocument envelope = JsonDocument.Parse(rawBody);
byte[] key = Convert.FromHexString(encryptionSecret); // 64 hex chars -> 32 bytes
byte[] iv = Convert.FromBase64String(envelope.RootElement.GetProperty("iv").GetString());
byte[] tag = Convert.FromBase64String(envelope.RootElement.GetProperty("tag").GetString());
byte[] data = Convert.FromBase64String(envelope.RootElement.GetProperty("data").GetString());
byte[] plain = new byte[data.Length];
using var aes = new AesGcm(key, 16); // 16 byte tag
aes.Decrypt(iv, data, tag, plain); // throws if the envelope was altered or the secret is wrong
return Encoding.UTF8.GetString(plain);
}
.NET takes the tag as its own argument. The two-argument AesGcm(key, 16) constructor needs .NET 8 or later; on .NET 5 to 7 use new AesGcm(key). Catch CryptographicException and reject the callback.
Uses only the standard library.
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
)
type envelope struct {
IV string `json:"iv"`
Tag string `json:"tag"`
Data string `json:"data"`
}
// call this only after verifySignature() has passed
func decryptCallback(rawBody []byte, encryptionSecret string) ([]byte, error) {
var env envelope
if err := json.Unmarshal(rawBody, &env); err != nil {
return nil, err
}
key, err := hex.DecodeString(encryptionSecret) // 64 hex chars -> 32 bytes
if err != nil {
return nil, err
}
iv, err := base64.StdEncoding.DecodeString(env.IV)
if err != nil {
return nil, err
}
tag, err := base64.StdEncoding.DecodeString(env.Tag)
if err != nil {
return nil, err
}
data, err := base64.StdEncoding.DecodeString(env.Data)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
if len(iv) != gcm.NonceSize() {
return nil, errors.New("unexpected iv length")
}
// Go expects the tag appended to the ciphertext;
// returns an error if the envelope was altered or the secret is wrong
return gcm.Open(nil, iv, append(data, tag...), nil)
}
The IV length is checked first because gcm.Open panics on a wrong-sized IV instead of returning an error. The returned bytes are the usual callback JSON.
Where the tag goes​
The envelope carries the tag on its own. Libraries differ in how they want it:
| Language | Tag handling |
|---|---|
| PHP, Node, C# | Passed separately |
Python (cryptography), Java, Go | Appended to the end of the ciphertext |
If decryption fails on a callback whose signature passed, first check that you are passing the tag the way your library expects.