Encryption and Decryption | Unified ID 2.0 (2024)

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:

  • 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 one of the code examples provided: see Encryption and Decryption Code Examples.
  • 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 response data envelope which is encrypted and formatted according to the encrypted response envelope.

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"}.

Prerequisites and Notes

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

  • Python
  • Java
  • C#

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.

  • Python
  • Java
  • C#

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.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))

Encryption and Decryption | Unified ID 2.0 (2024)
Top Articles
How to: Paint with Chalk Paint® - The Basics
Dashes, Colons, and Semicolons
This website is unavailable in your location. – WSB-TV Channel 2 - Atlanta
Compare Foods Wilson Nc
Mopaga Game
Southside Grill Schuylkill Haven Pa
Jennette Mccurdy And Joe Tmz Photos
Crazybowie_15 tit*
Assets | HIVO Support
Summoner Class Calamity Guide
Grace Caroline Deepfake
Bowie Tx Craigslist
Inside the life of 17-year-old Charli D'Amelio, the most popular TikTok star in the world who now has her own TV show and clothing line
Craigslist Red Wing Mn
Las 12 mejores subastas de carros en Los Ángeles, California - Gossip Vehiculos
Free Online Games on CrazyGames | Play Now!
TBM 910 | Turboprop Aircraft - DAHER TBM 960, TBM 910
Everything you need to know about Costco Travel (and why I love it) - The Points Guy
Metro Pcs.near Me
Leccion 4 Lesson Test
Vegas7Games.com
Chamberlain College of Nursing | Tuition & Acceptance Rates 2024
Shoe Station Store Locator
Wsbtv Fish And Game Report
Dtm Urban Dictionary
Inter Miami Vs Fc Dallas Total Sportek
Section 408 Allegiant Stadium
HP PARTSURFER - spare part search portal
Babydepot Registry
What Is The Lineup For Nascar Race Today
The Rise of "t33n leaks": Understanding the Impact and Implications - The Digital Weekly
Acuity Eye Group - La Quinta Photos
Puretalkusa.com/Amac
Edict Of Force Poe
Watchseries To New Domain
Studio 22 Nashville Review
Cox Outage in Bentonville, Arkansas
Chatropolis Call Me
Cookie Clicker The Advanced Method
Tyler Perry Marriage Counselor Play 123Movies
Riverton Wyoming Craigslist
Post A Bid Monticello Mn
Santa Clara County prepares for possible ‘tripledemic,’ with mask mandates for health care settings next month
Myrtle Beach Craigs List
Panolian Batesville Ms Obituaries 2022
All Weapon Perks and Status Effects - Conan Exiles | Game...
Avatar: The Way Of Water Showtimes Near Jasper 8 Theatres
Large Pawn Shops Near Me
N33.Ultipro
Overstock Comenity Login
Invitation Quinceanera Espanol
Latest Posts
Article information

Author: Neely Ledner

Last Updated:

Views: 5988

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.