Skip to main content

Encrypting Requests and Decrypting Responses

note

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

This guide includes the following sections:

Overview

For almost all EUID 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 EUID API requests and decrypting respective responses:

  • To use the APIs, in addition to your client API key, you need your client secret.
  • You can write your own custom code or use the Python scripts provided in the following sections.
  • Request and response use AES/GCM/NoPadding encryption algorithm with 96-bit initialization vector and 128-bit authentication tag.
  • The raw, unencrypted JSON body of the request is wrapped in a binary unencrypted request data envelope which then gets encrypted and formatted according to the Encrypted Request Envelope.
  • The response JSON body is wrapped in a binary unencrypted request data envelope which is encrypted and formatted according to the Encrypted Response Envelope.

Workflow

The high-level request-response workflow for the EUID 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 EUID endpoints explains the respective JSON body format requirements and parameters, includes call examples, and shows decrypted responses. The following sections provide examples of the encryption and decryption scripts in Python, field layout requirements, and request and response examples.

Encrypting Requests

You have the option of writing your own code for encrypting requests, using an EUID 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 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 an EUID 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": "AgAAAQFt3aNLXKXEyWS8Tpezcymk1Acv3n+ClOHLdAgqR0kt0Y+pQWSOVaW0tsKZI4FOv9K/rZH9+c4lpm2DBpmFJqjdF6FAaAzva5vxDIX/67UOspsYtiwxH73zU7Fj8PhVf1JcpsxUHRHzuk3vHF+ODrM13A8NAVlO1p0Wkb+cccIIhQ==",
"user_token": "AgAAAPpTqz7/Z+40Ue5G3XOM2RiyU6RS9Q5yj1n7Tlg7PN1K1LZWejvo8Er7A+Q8KxdXdj0OrKRf/XEGWsyUJscRNu1bg/MK+5AozvoJKUca8b10eQdYU86ZOHPH7pFnFhD5WHs=",
"refresh_token": "AAAAAQLMcnV+YE6/xoPDZBJvJtWyPyhF9QTV4242kFdT+DE/OfKsQ3IEkgCqD5jmP9HuR4O3PNSVnCnzYq2BiDDz8SLsKOo6wZsoMIn95jVWBaA6oLq7uUGY5/g9SUOfFmX5uDXUvO0w2UCKi+j9OQhlMfxTsyUQUzC1VQOx6ed/gZjqH/Sw6Kyk0XH7AlziqSyyXA438JHqyJphGVwsPl2LGCH1K2MPxkLmyzMZ2ghTzrr0IgIOXPsL4lXqSPkl/UJqnO3iqbihd66eLeYNmyd1Xblr3DwYnwWdAUXEufLoJbbxifGYc+fPF+8DpykpyL9neq3oquxQWpyHsftnwYaZT5EBZHQJqAttHUZ4yQ==",
"identity_expires": 1654623500142,
"refresh_expires": 1657214600142,
"refresh_from": 1654622900142,
"refresh_response_key": "wR5t6HKMfJ2r4J7fEGX9Gw=="
},
"status": "success"
}

Encryption and Decryption Code Examples

This section includes an encryption and decryption code example 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"}.

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.

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"}' | python3 uid2_request.py https://prod.euid.eu/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.euid.eu/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))