title | description | hide_table_of_contents | sidebar_position |
---|---|---|---|
Encryption and Decryption | Information about encrypting UID2 requests and decrypting responses. | false | 11 |
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import Link from '@docusaurus/Link'; import IdentityGenerateResponse from '../snippets/_example-identity-generate-response.mdx';
:::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.
The high-level request-response workflow for the UID2 APIs includes the following steps:
- Prepare the request body with input parameters in the JSON format.
- Wrap the request JSON in an unencrypted request data envelope.
- Encrypt the envelope using AES/GCM/NoPadding algorithm and your secret key.
- Assemble the Encrypted Request Envelope.
- Send the encrypted request and receive the encrypted response.
- Parse the Encrypted Response Envelope.
- Decrypt the data in the response envelope.
- Parse the resulting Unencrypted Response Data Envelope.
- (Optional, recommended) Ensure that the nonce in the response envelope matches the nonce in the request envelope.
- 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.
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.
The following table describes the field layout for request encryption code.
Offset (Bytes) | Size (Bytes) | Description |
---|---|---|
0 | 8 | The Unix timestamp (in milliseconds) of the request, in int64 big endian format. When the server receives and decrypts the envelope, it checks the embedded timestamp. If the timestamp is older than 60 seconds, the request is considered stale and is rejected. |
8 | 8 | Nonce: 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. |
16 | N | Payload, which is a request JSON document serialized in UTF-8 encoding. |
The following table describes the field layout for request encryption code.
Offset (Bytes) | Size (Bytes) | Description |
---|---|---|
0 | 1 | The version of the envelope format. Must be 1 . |
1 | 12 | 96-bit initialization vector (IV), which is used to randomize data encryption. |
13 | N | Payload (unencrypted request data envelope) encrypted using the AES/GCM/NoPadding algorithm. |
13 + N | 16 | 128-bit GCM authentication tag used to verify data integrity. |
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. :::
The following table describes the field layout for response decryption code.
Offset (Bytes) | Size (Bytes) | Description |
---|---|---|
0 | 12 | 96-bit initialization vector (IV), which is used to randomize data encryption. |
12 | N | Payload (Unencrypted Response Data Envelope) encrypted using the AES/GCM/NoPadding algorithm. |
12 + N | 16 | 128-bit GCM authentication tag used to verify data integrity. |
The following table describes the field layout for response decryption code.
Offset (Bytes) | Size (Bytes) | Description |
---|---|---|
0 | 8 | The Unix timestamp (in milliseconds) of the response, in int64 big endian format. |
8 | 8 | Nonce. For the response to be considered valid, this should match the nonce in the unencrypted request data envelope. |
16 | N | Payload, which is a response JSON document serialized in UTF-8 encoding. |
For example, a decrypted response to the POST /token/generate request for an email address might look like this:
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}
. :::
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 pycryptodomexpip install requests
The following code example encrypts requests and decrypts responses using Java. The required parameters are shown at the top of the main function, or by building and running the following:
java -jar Uid2Request-jar-with-dependencies.jar
The Java example is written for JDK version 11 or later, and you must have the com.google.code.gson library in your classpath.
If you are using Maven, you can use the following minimal pom.xml
, and run mvn package
to build the project:
<project> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>Uid2Request</artifactId> <version>1.0</version> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>3.4.2</version> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>org.example.Uid2Request</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> <finalName>${artifactId}</finalName> </build> </project>
The following code example encrypts requests and decrypts responses using C#. The required parameters are shown at the top of the file, or by building and running .\uid2_request
.
This file requires .NET 7.0. You can use an earlier version if required, but it must be .NET Core 3.0 or later. To change the version, replace the top-level statements with a Main method and the using declarations with using statements.
The following code example encrypts requests and decrypts responses using Go. The required parameters are shown at the bottom of the file, or by running go run uid2_request.go
.
Choose the code example you want to use. Remember to review the Prerequisites and Notes.
"""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="""importbase64importosimportsysimporttimeimportjsonimportrequestsfromCryptodome.CipherimportAESdefb64decode(b64string, param): try: returnbase64.b64decode(b64string) exceptException: print(f"Error: <{param}> is not base64 encoded") sys.exit() iflen(sys.argv) !=4andlen(sys.argv) !=5: print(__doc__) sys.exit() url=sys.argv[1] is_refresh=1ifsys.argv[2] =='--refresh-token'else0ifis_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.contentifhttp_response.status_code!=200: print(f"Response: Error HTTP status code {http_response.status_code}", end=", check api_key\n"ifhttp_response.status_code==401else"\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) ifis_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))
packageorg.example; importcom.google.gson.Gson; importcom.google.gson.GsonBuilder; importcom.google.gson.JsonObject; importcom.google.gson.JsonParser; importjava.io.BufferedReader; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.net.HttpURLConnection; importjava.net.URL; importjava.nio.ByteBuffer; importjava.nio.charset.StandardCharsets; importjava.security.SecureRandom; importjava.time.Instant; importjava.util.Arrays; importjava.util.Base64; importjavax.crypto.Cipher; importjavax.crypto.spec.GCMParameterSpec; importjavax.crypto.spec.SecretKeySpec; publicclassUid2Request { publicstaticfinalintNONCE_LENGTH_BYTES = 8; privatestaticfinalintGCM_TAG_LENGTH_BYTES = 16; privatestaticfinalintGCM_IV_LENGTH_BYTES = 12; publicstaticvoidmain(String[] args) throwsException { if (args.length != 3 && args.length != 4) { System.out.println( "Usage:" + "\n " + "java -jar Uid2Request-jar-with-dependencies.jar <url> <api_key> <client_secret>" + "\n\n" + "Example:" + "\n " + "echo '{\"email\": \"test@example.com\", \"optout_check\": 1}' | java -jar Uid2Request-jar-with-dependencies.jar https://prod.uidapi.com/v2/token/generate PRODGwJ0hP19QU4hmpB64Y3fV2dAed8t/mupw3sjN5jNRFzg= wJ0hP19QU4hmpB64Y3fV2dAed8t/mupw3sjN5jNRFzg=" + "\n\n\n" + "Refresh Token Usage:" + "\n " + "java -jar Uid2Request-jar-with-dependencies.jar <url> --refresh-token <refresh_token> <refresh_response_key>" + "\n\n" + "Refresh Token Example:" + "\n " + "java -jar Uid2Request-jar-with-dependencies.jar https://prod.uidapi.com/v2/token/refresh --refresh-token AAAAAxxJ...(truncated, total 388 chars) v2ixfQv8eaYNBpDsk5ktJ1yT4445eT47iKC66YJfb1s=" + "\n" ); System.exit(1); } Stringurl = args[0]; booleanisRefresh = "--refresh-token".equals(args[1]); byte[] secret = Base64.getDecoder().decode(args[isRefresh ? 3 : 2]); Stringpayload = isRefresh ? args[2] : newBufferedReader(newInputStreamReader(System.in)).readLine(); HttpURLConnectionconnection = (HttpURLConnection) newURL(url).openConnection(); connection.setRequestMethod("POST"); if (!isRefresh) { StringapiKey = args[1]; byte[] iv = newbyte[GCM_IV_LENGTH_BYTES]; longtimestamp = Instant.now().toEpochMilli(); byte[] requestNonce = newbyte[NONCE_LENGTH_BYTES]; byte[] plaintext = payload.getBytes(StandardCharsets.UTF_8); SecureRandomsecureRandom = newSecureRandom(); secureRandom.nextBytes(iv); secureRandom.nextBytes(requestNonce); ByteBufferbody = ByteBuffer.allocate(8 + requestNonce.length + plaintext.length); body.putLong(timestamp); body.put(requestNonce); body.put(plaintext); Ciphercipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpecparameterSpec = newGCMParameterSpec(GCM_TAG_LENGTH_BYTES * 8, iv); cipher.init(Cipher.ENCRYPT_MODE, newSecretKeySpec(secret, "AES"), parameterSpec); ByteBufferenvelope = ByteBuffer.allocate(1 + body.array().length + GCM_IV_LENGTH_BYTES + GCM_TAG_LENGTH_BYTES); envelope.put((byte) 1); envelope.put(iv); envelope.put(cipher.doFinal(body.array())); payload = Base64.getEncoder().encodeToString(envelope.array()); connection.setRequestProperty("Authorization", "Bearer " + apiKey); } connection.setDoOutput(true); try (OutputStreamos = connection.getOutputStream()) { os.write(payload.getBytes(StandardCharsets.UTF_8)); } // Handle responseintstatus = connection.getResponseCode(); BufferedReaderreader = status == 200 ? newBufferedReader(newInputStreamReader(connection.getInputStream())) : newBufferedReader(newInputStreamReader(connection.getErrorStream())); StringBuilderresponse = newStringBuilder(); Stringline; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); if (status != HttpURLConnection.HTTP_OK) { System.out.println("Error: HTTP status code " + status); System.out.println(response); return; } byte[] respBytes = Base64.getDecoder().decode(response.toString()); CipherrespCipher = Cipher.getInstance("AES/GCM/NoPadding"); respCipher.init(Cipher.DECRYPT_MODE, newSecretKeySpec(secret, "AES"), newGCMParameterSpec(GCM_TAG_LENGTH_BYTES * 8, respBytes, 0, GCM_IV_LENGTH_BYTES)); byte[] decrypted = respCipher.doFinal(respBytes, GCM_IV_LENGTH_BYTES, respBytes.length - GCM_IV_LENGTH_BYTES); JsonObjectjsonResponse; if (!isRefresh) { jsonResponse = JsonParser.parseString(newString(Arrays.copyOfRange(decrypted, 8 + NONCE_LENGTH_BYTES, decrypted.length), StandardCharsets.UTF_8)).getAsJsonObject(); } else { jsonResponse = JsonParser.parseString(newString(decrypted, StandardCharsets.UTF_8)).getAsJsonObject(); } StringprettyJsonResponse = newGsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(jsonResponse); System.out.println("Response JSON:"); System.out.println(prettyJsonResponse); } }
usingSystem.Buffers.Binary;usingSystem.Net;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Text.Json;if(args.Length!=3&&args.Length!=4){Console.WriteLine("""Usage: echo '<json>' | .\uid2_request <url> <api_key> <client_secret>Example: echo '{"email": "test@example.com", "optout_check": 1}' | .\uid2_request https://prod.uidapi.com/v2/token/generate UID2-C-L-999-fCXrMM.fsR3mDqAXELtWWMS+xG1s7RdgRTMqdOH2qaAo= wJ0hP19QU4hmpB64Y3fV2dAed8t/mupw3sjN5jNRFzg=Refresh Token Usage: .\uid2_request <url> --refresh-token <refresh_token> <refresh_response_key>Refresh Token Usage example: .\uid2_request https://prod.uidapi.com/v2/token/refresh --refresh-token AAAAAxxJ...(truncated, total 388 chars) v2ixfQv8eaYNBpDsk5ktJ1yT4445eT47iKC66YJfb1s=""");Environment.Exit(1);}constintGCM_IV_LENGTH=12;stringurl=args[0];byte[]secret;HttpResponseMessage?response;boolisRefresh=args[1]=="--refresh-token";if(isRefresh){stringrefreshToken=args[2];secret=Convert.FromBase64String(args[3]);Console.WriteLine($"\nRequest: Sending refresh_token to {url}\n");usingHttpClienthttpClient=newHttpClient();varcontent=newStringContent(refreshToken,Encoding.UTF8);response=awaithttpClient.PostAsync(url,content);}else{stringapiKey=args[1];secret=Convert.FromBase64String(args[2]);stringpayload=Console.In.ReadToEnd();varrequest=newHttpRequestMessage(HttpMethod.Post,url);request.Headers.Add("Authorization",$"Bearer {apiKey}");varunixTimestamp=newbyte[8];BinaryPrimitives.WriteInt64BigEndian(unixTimestamp,DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());varnonce=newbyte[8];varrnd=newRandom();rnd.NextBytes(nonce);varpayloadBytes=Encoding.UTF8.GetBytes(payload);varunencryptedRequestDataEnvelope=newbyte[unixTimestamp.Length+nonce.Length+payloadBytes.Length];unixTimestamp.CopyTo(unencryptedRequestDataEnvelope,0);nonce.CopyTo(unencryptedRequestDataEnvelope,unixTimestamp.Length);payloadBytes.CopyTo(unencryptedRequestDataEnvelope,unixTimestamp.Length+nonce.Length);variv=newbyte[GCM_IV_LENGTH];rnd.NextBytes(iv);varencryptedPayload=newbyte[unencryptedRequestDataEnvelope.Length];vartag=newbyte[AesGcm.TagByteSizes.MaxSize];usingAesGcmaesGcm=newAesGcm(secret);aesGcm.Encrypt(iv,unencryptedRequestDataEnvelope,encryptedPayload,tag);varenvelopeMemoryStream=newMemoryStream(1+iv.Length+encryptedPayload.Length+AesGcm.TagByteSizes.MaxSize);envelopeMemoryStream.WriteByte(1);//version of the envelope formatenvelopeMemoryStream.Write(iv);envelopeMemoryStream.Write(encryptedPayload);envelopeMemoryStream.Write(tag);varenvelope=Convert.ToBase64String(envelopeMemoryStream.ToArray());request.Content=newStringContent(envelope,Encoding.UTF8);varclient=newHttpClient();response=awaitclient.SendAsync(request);}varresponseStream=awaitresponse.Content.ReadAsStreamAsync();usingvarreader=newStreamReader(responseStream);varresponseBody=awaitreader.ReadToEndAsync();if(response.StatusCode!=HttpStatusCode.OK){Console.WriteLine($"Response: Error HTTP status code {(int)response.StatusCode}"+((response.StatusCode==HttpStatusCode.Unauthorized)?", check api_key":""));Console.WriteLine(responseBody);}else{varencryptedResponseEnvelope=Convert.FromBase64String(responseBody);varresponseMemoryStream=newMemoryStream(encryptedResponseEnvelope);byte[]iv=newbyte[GCM_IV_LENGTH];responseMemoryStream.Read(iv);intencryptedPayloadLength=encryptedResponseEnvelope.Length-GCM_IV_LENGTH-AesGcm.TagByteSizes.MaxSize;byte[]encryptedPayload=newbyte[encryptedPayloadLength];responseMemoryStream.Read(encryptedPayload);byte[]tag=newbyte[AesGcm.TagByteSizes.MaxSize];responseMemoryStream.Read(tag);usingAesGcmaesGcm=newAesGcm(secret);byte[]unencryptedResponseDataEnvelope=newbyte[encryptedPayload.Length];aesGcm.Decrypt(iv,encryptedPayload,tag,unencryptedResponseDataEnvelope);intoffset=isRefresh?0:16;//8 bytes for timestamp + 8 bytes for noncevarjson=Encoding.UTF8.GetString(unencryptedResponseDataEnvelope,offset,unencryptedResponseDataEnvelope.Length-offset);Console.WriteLine("Response JSON:");usingvarjDoc=JsonDocument.Parse(json);Console.WriteLine(JsonSerializer.Serialize(jDoc,newJsonSerializerOptions{WriteIndented=true}));}
package main import ( "bytes""crypto/aes""crypto/cipher""crypto/rand""encoding/base64""encoding/binary""encoding/json""fmt""io""log""net/http""os""strings""time" ) const ( nonceLengthBytes=8gcmIVLengthBytes=12 ) funcmain() { subArgs:=os.Args[1:] iflen(subArgs) !=3&&len(subArgs) !=4 { printUsage() os.Exit(1) } url:=subArgs[0] response, err:=func() (map[string]interface{}, error) { ifsubArgs[1] =="--refresh-token" { returnrefresh(url, subArgs[2], subArgs[3]) } else { returngenerate(url, subArgs[1], subArgs[2]) } }() iferr!=nil { log.Fatal(err) } prettyPrint(response) } funcrefresh(urlstring, refreshTokenstring, refreshResponseKeystring) (map[string]interface{}, error) { fmt.Printf("Request: Sending refresh_token to %s\n", url) response, err:=http.Post(url, "", strings.NewReader(refreshToken)) iferr!=nil { returnnil, err } returndeserializeResponse(response, refreshResponseKey, true) } funcgenerate(urlstring, apiKeystring, secretstring) (map[string]interface{}, error) { payload, err:=io.ReadAll(os.Stdin) iferr!=nil { returnnil, err } key, err:=base64.StdEncoding.DecodeString(secret) iferr!=nil { returnnil, err } unencryptedEnvelope, err:=makeUnencryptedEnvelope(payload) iferr!=nil { returnnil, err } envelope, err:=makeEncryptedEnvelope(unencryptedEnvelope, key) iferr!=nil { returnnil, err } req, err:=http.NewRequest("POST", url, strings.NewReader(base64.StdEncoding.EncodeToString(envelope))) iferr!=nil { returnnil, err } req.Header.Add("Authorization", "Bearer "+apiKey) response, err:=http.DefaultClient.Do(req) iferr!=nil { returnnil, err } returndeserializeResponse(response, secret, false) } funcaesgcm(key []byte) (cipher.AEAD, error) { block, err:=aes.NewCipher(key) iferr!=nil { returnnil, err } returncipher.NewGCM(block) } funcdecryptResponse(ciphertextstring, keystring) ([]byte, error) { ciphertextBytes, err:=base64.StdEncoding.DecodeString(ciphertext) iferr!=nil { returnnil, err } keyBytes, err:=base64.StdEncoding.DecodeString(key) iferr!=nil { returnnil, err } aesgcm, err:=aesgcm(keyBytes) iferr!=nil { returnnil, err } iv:=ciphertextBytes[:gcmIVLengthBytes] returnaesgcm.Open(nil, iv, ciphertextBytes[gcmIVLengthBytes:], nil) } funcdeserialize(bytes []byte) (map[string]interface{}, error) { varanyJsonmap[string]interface{} err:=json.Unmarshal(bytes, &anyJson) returnanyJson, err } funcprettyPrint(objmap[string]interface{}) error { bytes, err:=json.MarshalIndent(obj, "", " ") iferr!=nil { returnerr } fmt.Println(string(bytes)) returnnil } funccheckStatusCode(response*http.Response, body []byte) error { ifresponse.StatusCode!=http.StatusOK { returnfmt.Errorf("Response: Error HTTP status code %d\n%s", response.StatusCode, body) } returnnil } funcmakeUnencryptedEnvelope(payload []byte) ([]byte, error) { timestamp:=make([]byte, 8) binary.BigEndian.PutUint64(timestamp, uint64(time.Now().UnixMilli())) nonce:=make([]byte, nonceLengthBytes) _, err:=rand.Read(nonce) iferr!=nil { returnnil, err } varbody bytes.Bufferbody.Write(timestamp) body.Write(nonce) body.Write(payload) returnbody.Bytes(), nil } funcencrypt(plaintext []byte, iv []byte, key []byte) ([]byte, error) { aesgcm, err:=aesgcm(key) iferr!=nil { returnnil, err } returnaesgcm.Seal(nil, iv, plaintext, nil), nil } funcmakeEncryptedEnvelope(payload []byte, key []byte) ([]byte, error) { iv:=make([]byte, gcmIVLengthBytes) _, err:=rand.Read(iv) iferr!=nil { returnnil, err } ciphertext, err:=encrypt(payload, iv, key) iferr!=nil { returnnil, err } varenvelope bytes.Bufferenvelope.WriteByte(1) envelope.Write(iv) envelope.Write(ciphertext) returnenvelope.Bytes(), nil } funcdeserializeResponse(response*http.Response, keystring, isRefreshbool) (map[string]interface{}, error) { deferresponse.Body.Close() body, err:=io.ReadAll(response.Body) iferr!=nil { returnnil, err } err=checkStatusCode(response, body) iferr!=nil { returnnil, err } plaintext, err:=decryptResponse(string(body), key) iferr!=nil { returnnil, err } offset:=16ifisRefresh { offset=0 } returndeserialize(plaintext[offset:]) } funcprintUsage() { fmt.Println(`Usage: echo '<json>' | go run uid2_request.go <url> <api_key> <client_secret>Example: echo '{"email": "test@example.com", "optout_check": 1}' | go run uid2_request.go https://prod.uidapi.com/v2/token/generate UID2-C-L-999-fCXrMM.fsR3mDqAXELtWWMS+xG1s7RdgRTMqdOH2qaAo= wJ0hP19QU4hmpB64Y3fV2dAed8t/mupw3sjN5jNRFzg=Refresh Token Usage: go run uid2_request.go <url> --refresh-token <refresh_token> <refresh_response_key>Refresh Token Usage example: go run uid2_request.go https://prod.uidapi.com/v2/token/refresh --refresh-token AAAAAxxJ...(truncated, total 388 chars) v2ixfQv8eaYNBpDsk5ktJ1yT4445eT47iKC66YJfb1s=`) }