> For the complete documentation index, see [llms.txt](https://docs.tutelar.io/tutelar-api-document/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tutelar.io/tutelar-api-document/fraud-detection-monitoring/create-transaction/encryption.md). Agents can also search and read this documentation through its [MCP server](https://docs.tutelar.io/tutelar-api-document/~gitbook/mcp).

# Encryption

## Client Request and Response Payload Encryption

When encryption is enabled, the client must encrypt the entire request payload before sending it to the API and decrypt the encrypted response payload upon receiving the API response.

The encryption mechanism uses AWS KMS-managed key management with key rotation support to securely manage encryption keys. The client uses the configured public key to protect the AES data encryption key (DEK), while the backend uses AWS KMS to recover the DEK and process the encrypted payload.

The client integration must support the request and response encryption format, including the nonce and authentication tag required for secure AES-GCM decryption.

## Client Request Encryption

The client must encrypt the complete transaction request before sending it to the API.

#### Step 1: Configure the server's RSA public key<br>

The client uses the public key provided by the server.

```
const serverPublicKey = `-----BEGIN PUBLIC KEY----- RSA_PUBLIC_KEY -----END PUBLIC KEY-----`;
```

{% hint style="info" %}
The public key protects the AES encryption key. The corresponding private key must remain securely controlled by the server.&#x20;
{% endhint %}

#### Step 2: Generate an AES-256 key

The client generates a new random AES key for every request.

```
const aesKey = await crypto.subtle.generateKey(
    {
        name: "AES-GCM",
        length: 256
    },
    true,
    ["encrypt", "decrypt"]
);
```

Here:

* `AES-GCM`: Encryption algorithm.
* `256`: Key size in bits.
* `true`: Allows exporting the raw key.
* `encrypt`, `decrypt`: Permitted operations.

The generated AES key is unique for that request.

The client then exports the key:<br>

```
const rawKey = new Uint8Array(
    await crypto.subtle.exportKey("raw", aesKey)
);
```

**Why export it?**

Because RSA needs the raw AES key bytes to encrypt it using the public key.

#### Step 3: Generate a nonce

```
const nonce = crypto.getRandomValues( new Uint8Array(12) );
```

Nonce means a number used once.

AES-GCM requires a unique nonce for each encryption under a given key.

Here, the nonce is 12 bytes (96 bits).

Think of it as an additional random value that makes the encryption operation unique.

Important points:

* Nonce is not secret.
* It is sent along with the ciphertext.
* It is required for decryption.
* Never reuse the same nonce with the same AES key.

#### Step 4: Encrypt the complete JSON payload

First, convert the transaction JSON into bytes:

```
const payload = new TextEncoder().encode(
    JSON.stringify(requestPayload)
);
```

```
const ciphertext = new Uint8Array(
    await crypto.subtle.encrypt(
        {
            name: "AES-GCM",
            iv: nonce
        },
        aesKey,
        payload
    )
);
```

{% hint style="info" %}
All request fields are protected, including customer information, payment details, device information, and other transaction fields.
{% endhint %}

#### Step 5: Encrypt the AES key using RSA

At this point, the client has:

* Original AES key.
* Encrypted transaction payload.
* Nonce.

But how does the backend obtain the AES key?

The client encrypts the AES key using the server's RSA public key.

First, convert the PEM public key into bytes:

```
function pemToBytes(pem) {
    const base64 = pem
        .replace(/-----BEGIN PUBLIC KEY-----/g, "")
        .replace(/-----END PUBLIC KEY-----/g, "")
        .replace(/\s/g, "");
    return Uint8Array.from(
        atob(base64),
        character => character.charCodeAt(0)
    );
}
```

Then import the RSA public key:

```
const rsaKey = await crypto.subtle.importKey(
    "spki",
    pemToBytes(publicKeyPem),
    {
        name: "RSA-OAEP",
        hash: "SHA-256"
    },
    false,
    ["encrypt"]
);
```

Now encrypt the AES key:

```
const encryptedKey = new Uint8Array(
    await crypto.subtle.encrypt(
        {
            name: "RSA-OAEP"
        },
        rsaKey,
        rawKey
    )
);
```

What happens?

```
Original AES key
       |
RSA public key
       |
Encrypted AES key
```

The client can now safely send the encrypted AES key to the backend.

#### Step 6: Prepare the Encrypted Request

After encrypting the AES encryption key using the server's RSA public key and encrypting the JSON payload using AES-256-GCM, convert the resulting binary data into Base64 strings.

This is required because the API accepts JSON data, which cannot directly carry binary data.

**1. Define the Base64 conversion function**

```
function toBase64(bytes) {
    let binary = "";

    for (const byte of bytes) {
        binary += String.fromCharCode(byte);
    }

    return btoa(binary);
}
```

**2. Convert the encrypted data into Base64**

```
const encryptedKeyBase64 = toBase64(encryptedKey);
const nonceBase64 = toBase64(nonce);
const ciphertextBase64 = toBase64(ciphertext);
```

Where:

* `encryptedKey`: AES encryption key encrypted using the server's RSA public key.
* `nonce`: 12-byte nonce generated for AES-256-GCM encryption.
* `ciphertext`: Encrypted JSON payload, including the 128-bit GCM authentication tag appended to the ciphertext.

**3. Prepare the encrypted request object**

Create the request object using the Base64-encoded values.

```
const encryptedRequest = {
    keyVersion: "v1",
    encryptedKey: encryptedKeyBase64,
    nonce: nonceBase64,
    ciphertext: ciphertextBase64
};
```

**4. Final API request payload**

The request sent to the backend will have the following JSON structure:

```
{
    "keyVersion": "v1",
    "encryptedKey": "BASE64_ENCODED_RSA_ENCRYPTED_AES_KEY",
    "nonce": "BASE64_ENCODED_12_BYTE_NONCE",
    "ciphertext": "BASE64_ENCODED_AES_GCM_CIPHERTEXT"
}
```

* <mark style="color:green;">keyVersion:</mark> Identifies the KMS key version corresponding to the public key used to encrypt the AES DEK.
* <mark style="color:green;">encryptedKey:</mark> AES key encrypted using the server's RSA public key.
* <mark style="color:green;">nonce:</mark> Nonce used for AES-GCM encryption.
* <mark style="color:green;">ciphertext:</mark> Encrypted complete JSON payload, including the AES-GCM authentication tag.

**Key rotation:** The client must set keyVersion to the version associated with the public key it uses. During rotation, the backend can support both configured key versions and select the appropriate KMS key based on this field. Once the client migration is complete, the previous key version can be retired.

**5. Send the encrypted request to the server**

```
const response = await fetch("/api/v1/fraud-detector/transaction/create", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Authorization": `Basic ${accessToken}`
    },
    body: JSON.stringify(encryptedRequest)
});

const result = await response.json();
```

**JavaScript Encryption Example**

```
const publicKeyPem = `-----BEGIN PUBLIC KEY-----
YOUR_RSA_PUBLIC_KEY
-----END PUBLIC KEY-----`;
function pemToBytes(pem) {
    const base64 = pem
        .replace(/-----BEGIN PUBLIC KEY-----/g, "")
        .replace(/-----END PUBLIC KEY-----/g, "")
        .replace(/\s/g, "");
    return Uint8Array.from(
        atob(base64),
        character => character.charCodeAt(0)
    );
}
function toBase64(bytes) {
    let binary = "";
    for (const byte of bytes) {
        binary += String.fromCharCode(byte);
    }
    return btoa(binary);
}
async function encryptRequest(requestPayload) {
    const aesKey = await crypto.subtle.generateKey(
        {
            name: "AES-GCM",
            length: 256
        },
        true,
        ["encrypt", "decrypt"]
    );
    const rawKey = new Uint8Array(
        await crypto.subtle.exportKey("raw", aesKey)
    );
    const nonce = crypto.getRandomValues(new Uint8Array(12));
    const payload = new TextEncoder().encode(
        JSON.stringify(requestPayload)
    );
    const ciphertext = new Uint8Array(
        await crypto.subtle.encrypt(

 {
                name: "AES-GCM",
                iv: nonce
            },
            aesKey,
            payload
        )
    );
    const rsaKey = await crypto.subtle.importKey(
        "spki",
        pemToBytes(publicKeyPem),
        {
            name: "RSA-OAEP",
            hash: "SHA-256"
        },
        false,
        ["encrypt"]
    );
    const encryptedKey = new Uint8Array(
        await crypto.subtle.encrypt(
            {
                name: "RSA-OAEP"
            },
            rsaKey,
            rawKey
        )
    );
    rawKey.fill(0);
    return {
        encryptedRequest: {
            keyVersion: "v1",
            encryptedKey: toBase64(encryptedKey),
            nonce: toBase64(nonce),
            ciphertext: toBase64(ciphertext)
        },
        aesKey
    };
}
```

## Client Response Decryption

The client now receives the encrypted response.

It must decrypt it before accessing the risk result.

#### Step 1: Retain the recovered AES key

After decrypting the incoming request, the backend already has the AES key.

It should retain it temporarily until the response has been encrypted.

```
Client generated AES key
          |
Encrypted and sent to server
          |
Server recovers AES key using KMS
          |
Server uses the key for:
    1. Request decryption
    2. Response encryption
```

#### Step 2: Read the encrypted response

Extract the response nonce, ciphertext, and authentication tag according to the agreed response format. These values are required to decrypt and authenticate the response.

```
function base64ToBytes(value) {
    return Uint8Array.from(
        atob(value),
        character => character.charCodeAt(0)
    );
}
const nonce = base64ToBytes(responseData.data.nonce);
const ciphertext = base64ToBytes(
    responseData.data.ciphertext
);
```

#### Step 3: Prepare the encrypted bytes

Convert the Base64 values into bytes and arrange the ciphertext and authentication tag in the format expected by the client's cryptography library.

The Web Crypto API expects the AES-GCM authentication tag to be appended to the ciphertext. If the API returns the tag separately, the client must combine them before decryption.

#### Step 4: Decrypt the response

Use AES-256-GCM with the retained AES key and the response nonce.

```
const decryptedBuffer = await crypto.subtle.decrypt(
    {
        name: "AES-GCM",
        iv: nonce,
        tagLength: 128
    },
    aesKey,
    encryptedBytes
);
```

This recovers the original response and verifies its integrity. Decryption must fail if authentication fails; the client must not use an unauthenticated response.

#### Step 5: Convert the response into JSON

Convert the decrypted bytes into text and parse the JSON.

```json
const decryptedResponse = JSON.parse(
    new TextDecoder().decode(decryptedBuffer)
);
```

The client can now access the transaction response as a normal JSON object for its application logic.

```
async function decryptResponse(responseData, aesKey) {
    const nonce = fromBase64(responseData.data.nonce);
    const ciphertext = fromBase64(responseData.data.ciphertext);
    const decryptedBuffer = await crypto.subtle.decrypt(
        {
            name: "AES-GCM",
            iv: nonce,
            tagLength: 128
        },
        aesKey,
        ciphertext
    );
    return JSON.parse(
        new TextDecoder().decode(decryptedBuffer)
    );
}
```

#### Sample API Request

```
{
  "keyVersion": "v1",
  "encryptedKey": "BASE64_ENCRYPTED_AES_KEY",
  "nonce": "BASE64_NONCE",
  "ciphertext": "BASE64_CIPHERTEXT"
}

```

#### Sample API Response

```
{
  "success": true,
  "message": "Transaction risk results are",
  "data": {
    "nonce": "BASE64_RESPONSE_NONCE",
    "ciphertext": "BASE64_ENCRYPTED_RESPONSE"
  }
}
```

#### Error Response

**If the encrypted request payload is missing, invalid, or cannot be decrypted using the configured AWS KMS key and AES key, the API returns an error response.**

```
{
   "success": false,
   "code": 400,
   "message": "Invalid encrypted payload"
}
{
   "success": false,
   "code": 400,
   "message": "Unable to process encrypted request"
}
```

**Possible causes:**

* Incorrect RSA public key used to encrypt the AES key.
* AWS KMS key configuration or decryption failure.
* Invalid or mismatched AES key.
* Incorrect nonce or modified ciphertext.
* Invalid AES-GCM authentication tag.
* Plaintext payload sent instead of the encrypted request envelope.

<br>
