Skip to main content

Encrypting Requests and Decrypting Responses

note

If you're a publisher and are implementing UID2 on the client side, encryption and decryption is managed automatically by your implementation, such as Prebid.js (see UID2 Client-Side Integration Guide for Prebid.js) or the JavaScript SDK (see Client-Side Integration Guide for JavaScript).

For almost all UID2 endpoints, requests sent to the endpoint must be encrypted and responses from the endpoint must be decrypted.

The only exception is that requests to the POST /token/refresh endpoint do not need to be encrypted.

Here's what you need to know about encrypting UID2 API requests and decrypting respective responses:

Workflow

The high-level request-response workflow for the UID2 APIs includes the following steps:

  1. Prepare the request body with input parameters in the JSON format.
  2. Wrap the request JSON in an unencrypted request data envelope.
  3. Encrypt the envelope using AES/GCM/NoPadding algorithm and your secret key.
  4. Assemble the Encrypted Request Envelope.
  5. Send the encrypted request and receive the encrypted response.
  6. Parse the Encrypted Response Envelope.
  7. Decrypt the data in the response envelope.
  8. Parse the resulting Unencrypted Response Data Envelope.
  9. (Optional, recommended) Ensure that the nonce in the response envelope matches the nonce in the request envelope.
  10. Extract the response JSON object from the unencrypted envelope.

A code example for encrypting requests and decrypting responses can help with automating steps 2-10 and serves as a reference of how to implement these steps in your application.

Documentation for the individual UID2 endpoints explains the respective JSON body format requirements and parameters, includes call examples, and shows decrypted responses. The following sections provide encryption and decryption code examples, field layout requirements, and request and response examples.

Encrypting Requests

You have the option of writing your own code for encrypting requests, using a UID2 SDK, or using one of the provided code examples (see Encryption and Decryption Code Examples). If you choose to write your own code, be sure to follow the field layout requirements listed in Unencrypted Request Data Envelope and Encrypted Request Envelope.

Unencrypted Request Data Envelope

The following table describes the field layout for request encryption code.

Offset (Bytes)Size (Bytes)Description
08The Unix timestamp (in milliseconds). Must be int64 big endian.
88Nonce: Random 64 bits of data used to help protect against replay attacks. The corresponding Unencrypted Response Data Envelope should contain the same nonce value for the response to be considered valid.
16NPayload, which is a request JSON document serialized in UTF-8 encoding.

Encrypted Request Envelope

The following table describes the field layout for request encryption code.

Offset (Bytes)Size (Bytes)Description
01The version of the envelope format. Must be 1.
11296-bit initialization vector (IV), which is used to randomize data encryption.
13NPayload (unencrypted request data envelope) encrypted using the AES/GCM/NoPadding algorithm.
13 + N16128-bit GCM authentication tag used to verify data integrity.

Decrypting Responses

You have the option of writing your own code for decrypting responses, using a UID2 SDK, or using one of the provided code examples (see Encryption and Decryption Code Examples). If you choose to write your own code, be sure to follow the field layout requirements listed in Encrypted Response Envelope and Unencrypted Response Data Envelope.

note

The response is encrypted only if the service returns HTTP status code 200.

Encrypted Response Envelope

The following table describes the field layout for response decryption code.

Offset (Bytes)Size (Bytes)Description
01296-bit initialization vector (IV), which is used to randomize data encryption.
12NPayload (Unencrypted Response Data Envelope) encrypted using the AES/GCM/NoPadding algorithm.
12 + N16128-bit GCM authentication tag used to verify data integrity.

Unencrypted Response Data Envelope

The following table describes the field layout for response decryption code.

Offset (Bytes)Size (Bytes)Description
08The Unix timestamp (in milliseconds). Must be int64 big endian.
88Nonce. For the response to be considered valid, this should match the nonce in the unencrypted request data envelope.
16NPayload, which is a response JSON document serialized in UTF-8 encoding.

Response Example

For example, a decrypted response to the POST /token/generate request for an email address might look like this:

{
"body": {
"advertising_token": "A4AAAABlh75XmviGJi-hkLGs96duivRhMd3a3pe7yTIwbAHudfB9wFTj2FtJTdMW5TXXd1KAb-Z3ekQ_KImZ5Mi7xP75jRNeD6Mt6opWwXCCpQxYejP0R6WnCGnWawx9rLu59LsHv6YEA_ARNIUUl9koobfA9pLmnxE3dRedDgCKm4xHXYk01Fr8rOts6iJj2AhYISR3XkyBpqzT-vqBjsHH0g",
"identity_expires": 1724899014352,
"refresh_expires": 1724981814352,
"refresh_from": 1724896314352,
"refresh_response_key": "TS0H0szacv/F3U8bQjZwjSaZJjxZbMvxqHn1l3TL/iY=",
"refresh_token": "AAAAAGYzgUszke2sV9CxXnxyFfUU+KDCJUCXNbj1/FVcCjvR7K07jYaWe44wxM6SOTwG7WQB4XfIcquMqH57iHUnAu1zacYf9g58BtbhKCYWTwrdpB0fSqTANBXOYy+yBnl6tLRwVv32LqRCj76D8meO4tw+MKlUAc2EoFzFNPSfZLpA3Jk4q68vH6VJH/WIuu1tulrVm5J8RZAZnmTlEcsPdjoOC6X4w3aAwiwtbeGw7yOO0immpVoC5KaXnT9olRPTlrt8F9SvebLIcqkYhvRMPpl1S89yeneyGo++RnD9qSHIrfu9To3VwYW018QuvyA15uv4No4BoAzyPuHqzQ8gAs6csWwZ7VwfYD7DSJXlQiIpwzjA2Hl8mgg/5fcXwKEJ"
},
"status": "success"
}

Encryption and Decryption Code Examples

This section includes encryption and decryption code examples in different programming languages.

For the POST /token/refresh endpoint, the code takes the values for refresh_token and refresh_response_key that were obtained from a prior call to POST /token/generate or POST /token/refresh.

note

For Windows, if you're using Windows Command Prompt instead of PowerShell, you must also remove the single quotes surrounding the JSON. For example, use echo {"email": "test@example.com", "optout_check": 1}.

Prerequisites and Notes

Before using the code example, check the prerequisites and notes for the language you're using.

The following code example encrypts requests and decrypts responses using Python. The required parameters are shown at the top of the code example, or by running python3 uid2_request.py.

note

For Windows, replace python3 with python.

The Python code requires the pycryptodomex and requests packages. You can install these as follows:

pip install pycryptodomex
pip install requests

Code Example

Choose the code example you want to use. Remember to review the Prerequisites and Notes.

uid2_request.py
"""
Usage:
echo '<json>' | python3 uid2_request.py <url> <api_key> <client_secret>

Example:
echo '{"email": "test@example.com", "optout_check": 1}' | python3 uid2_request.py https://prod.uidapi.com/v2/token/generate PRODGwJ0hP19QU4hmpB64Y3fV2dAed8t/mupw3sjN5jNRFzg= wJ0hP19QU4hmpB64Y3fV2dAed8t/mupw3sjN5jNRFzg=


Refresh Token Usage:
python3 uid2_request.py <url> --refresh-token <refresh_token> <refresh_response_key>

Refresh Token Usage example:
python3 uid2_request.py https://prod.uidapi.com/v2/token/refresh --refresh-token AAAAAxxJ...(truncated, total 388 chars) v2ixfQv8eaYNBpDsk5ktJ1yT4445eT47iKC66YJfb1s=

"""

import base64
import os
import sys
import time
import json

import requests
from Cryptodome.Cipher import AES

def b64decode(b64string, param):
try:
return base64.b64decode(b64string)
except Exception:
print(f"Error: <{param}> is not base64 encoded")
sys.exit()

if len(sys.argv) != 4 and len(sys.argv) != 5:
print(__doc__)
sys.exit()

url = sys.argv[1]

is_refresh = 1 if sys.argv[2] == '--refresh-token' else 0
if is_refresh:
refresh_token = sys.argv[3]
secret = b64decode(sys.argv[4], "refresh_response_key")
print(f"\nRequest: Sending refresh_token to {url}\n")
http_response = requests.post(url, refresh_token)
else:
api_key = sys.argv[2]
secret = b64decode(sys.argv[3], "client_secret")
payload = "".join(sys.stdin.readlines())

iv = os.urandom(12)
cipher = AES.new(secret, AES.MODE_GCM, nonce=iv)

millisec = int(time.time() * 1000)
request_nonce = os.urandom(8)

print(f"\nRequest: Encrypting and sending to {url} : {payload}")

body = bytearray(millisec.to_bytes(8, 'big'))
body += bytearray(request_nonce)
body += bytearray(bytes(payload, 'utf-8'))

ciphertext, tag = cipher.encrypt_and_digest(body)

envelope = bytearray(b'\x01')
envelope += bytearray(iv)
envelope += bytearray(ciphertext)
envelope += bytearray(tag)

base64Envelope = base64.b64encode(bytes(envelope)).decode()

http_response = requests.post(url, base64Envelope, headers={"Authorization": "Bearer " + api_key})

# Decryption
response = http_response.content
if http_response.status_code != 200:
print(f"Response: Error HTTP status code {http_response.status_code}", end=", check api_key\n" if http_response.status_code == 401 else "\n")
print(response.decode("utf-8"))
else:
resp_bytes = base64.b64decode(response)
iv = resp_bytes[:12]
data = resp_bytes[12:len(resp_bytes) - 16]
tag = resp_bytes[len(resp_bytes) - 16:]

cipher = AES.new(secret, AES.MODE_GCM, nonce=iv)
decrypted = cipher.decrypt_and_verify(data, tag)

if is_refresh != 1:
json_resp = json.loads(decrypted[16:].decode("utf-8"))
else:
json_resp = json.loads(decrypted.decode("utf-8"))

print("Response JSON:")
print(json.dumps(json_resp, indent=4))