-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathUid2Encryption.java
More file actions
507 lines (433 loc) · 24.7 KB
/
Uid2Encryption.java
File metadata and controls
507 lines (433 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package com.uid2.client;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
public class Uid2Encryption {
public static final int GCM_AUTHTAG_LENGTH = 16;
public static final int GCM_IV_LENGTH = 12;
private static boolean skipAeadCheck = false;
public static void setSkipAeadCheck(boolean skip) {
skipAeadCheck = skip;
}
static DecryptionResponse decrypt(String token, KeyContainer keys, Instant now, IdentityScope identityScope, String domainOrAppName, ClientType clientType) throws Exception {
if (token.length() < 4)
{
return DecryptionResponse.makeError(DecryptionStatus.INVALID_PAYLOAD);
}
String headerStr = token.substring(0, 4);
boolean isBase64UrlEncoding = (headerStr.indexOf('-') != -1 || headerStr.indexOf('_') != -1);
byte[] data = isBase64UrlEncoding ? Uid2Base64UrlCoder.decode(headerStr) : Base64.getDecoder().decode(headerStr);
if (data[0] == 2)
{
return decryptV2(Base64.getDecoder().decode(token), keys, now, domainOrAppName, clientType);
}
//java byte is signed so we wanna convert to unsigned before checking the enum
int unsignedByte = ((int) data[1]) & 0xff;
if (unsignedByte == AdvertisingTokenVersion.V3.value())
{
return decryptV3(Base64.getDecoder().decode(token), keys, now, identityScope, domainOrAppName, clientType, 3);
}
else if (unsignedByte == AdvertisingTokenVersion.V4.value())
{
// Accept either base64 or base64url encoding.
return decryptV3(Base64.getDecoder().decode(base64UrlToBase64(token)), keys, now, identityScope, domainOrAppName, clientType, 4);
}
return DecryptionResponse.makeError(DecryptionStatus.VERSION_NOT_SUPPORTED);
}
static String base64UrlToBase64(String value) {
// Base64 decoder doesn't require padding.
return value.replace('-', '+')
.replace('_', '/');
}
static DecryptionResponse decryptV2(byte[] encryptedId, KeyContainer keys, Instant now, String domainOrAppName, ClientType clientType) throws Exception {
try {
ByteBuffer rootReader = ByteBuffer.wrap(encryptedId);
int version = (int) rootReader.get();
if (version != 2) {
return DecryptionResponse.makeError(DecryptionStatus.VERSION_NOT_SUPPORTED);
}
long masterKeyId = rootReader.getInt();
Key masterKey = keys.getKey(masterKeyId);
if (masterKey == null) {
return DecryptionResponse.makeError(DecryptionStatus.NOT_AUTHORIZED_FOR_MASTER_KEY);
}
byte[] masterIv = new byte[16];
rootReader.get(masterIv);
byte[] masterDecrypted = decrypt(
Arrays.copyOfRange(encryptedId, 21, encryptedId.length),
masterIv,
masterKey.getSecret());
ByteBuffer masterPayloadReader = ByteBuffer.wrap(masterDecrypted);
long expiryMilliseconds = masterPayloadReader.getLong();
long siteKeyId = masterPayloadReader.getInt();
Key siteKey = keys.getKey(siteKeyId);
if (siteKey == null) {
return DecryptionResponse.makeError(DecryptionStatus.NOT_AUTHORIZED_FOR_KEY);
}
byte[] identityIv = new byte[16];
masterPayloadReader.get(identityIv);
byte[] identityDecrypted = decrypt(
Arrays.copyOfRange(masterDecrypted, 28, masterDecrypted.length),
identityIv,
siteKey.getSecret());
ByteBuffer identityPayloadReader = ByteBuffer.wrap(identityDecrypted);
int siteId = identityPayloadReader.getInt();
int idLength = identityPayloadReader.getInt();
byte[] idBytes = new byte[idLength];
identityPayloadReader.get(idBytes);
String idString = new String(idBytes, StandardCharsets.UTF_8);
PrivacyBits privacyBits = new PrivacyBits(identityPayloadReader.getInt());
long establishedMilliseconds = identityPayloadReader.getLong();
Instant established = Instant.ofEpochMilli(establishedMilliseconds);
int advertisingTokenVersion = 2;
Instant expiry = Instant.ofEpochMilli(expiryMilliseconds);
// if (now.isAfter(expiry)) {
// return DecryptionResponse.makeError(DecryptionStatus.EXPIRED_TOKEN, established, siteId, siteKey.getSiteId(), null, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
// }
if (!isDomainOrAppNameAllowedForSite(clientType, privacyBits.isClientSideGenerated(), siteId, domainOrAppName, keys)) {
return DecryptionResponse.makeError(DecryptionStatus.DOMAIN_OR_APP_NAME_CHECK_FAILED, established, siteId, siteKey.getSiteId(), null, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
}
if (!doesTokenHaveValidLifetime(clientType, keys, now, expiry, now)) {
return DecryptionResponse.makeError(DecryptionStatus.INVALID_TOKEN_LIFETIME, established, siteId, siteKey.getSiteId(), null, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
}
return new DecryptionResponse(DecryptionStatus.SUCCESS, idString, established, siteId, siteKey.getSiteId(), null, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
} catch (ArrayIndexOutOfBoundsException payloadEx) {
return DecryptionResponse.makeError(DecryptionStatus.INVALID_PAYLOAD);
}
}
static DecryptionResponse decryptV3(byte[] encryptedId, KeyContainer keys, Instant now, IdentityScope identityScope, String domainOrAppName, ClientType clientType, int advertisingTokenVersion) {
try {
final IdentityType identityType = getIdentityType(encryptedId);
final ByteBuffer rootReader = ByteBuffer.wrap(encryptedId);
final byte prefix = rootReader.get();
if (decodeIdentityScopeV3(prefix) != identityScope)
{
return DecryptionResponse.makeError(DecryptionStatus.INVALID_IDENTITY_SCOPE);
}
//version
rootReader.get();
final long masterKeyId = rootReader.getInt();
final Key masterKey = keys.getKey(masterKeyId);
if (masterKey == null) {
return DecryptionResponse.makeError(DecryptionStatus.NOT_AUTHORIZED_FOR_MASTER_KEY);
}
final byte[] masterPayload = decryptGCM(encryptedId, rootReader.position(), masterKey.getSecret());
final ByteBuffer masterReader = ByteBuffer.wrap(masterPayload);
final long expiresMilliseconds = masterReader.getLong();
final long generatedMilliseconds = masterReader.getLong();
Instant generated = Instant.ofEpochMilli(generatedMilliseconds);
final int operatorSideId = masterReader.getInt();
final byte operatorType = masterReader.get();
final int operatorVersion = masterReader.getInt();
final int operatorKeyId = masterReader.getInt();
final long siteKeyId = masterReader.getInt();
final Key siteKey = keys.getKey(siteKeyId);
if (siteKey == null) {
return DecryptionResponse.makeError(DecryptionStatus.NOT_AUTHORIZED_FOR_KEY);
}
final byte[] sitePayload = decryptGCM(masterPayload, masterReader.position(), siteKey.getSecret());
final ByteBuffer siteReader = ByteBuffer.wrap(sitePayload);
final int siteId = siteReader.getInt();
final long publisherId = siteReader.getLong();
final int clientKeyId = siteReader.getInt();
final PrivacyBits privacyBits = new PrivacyBits(siteReader.getInt());
final long establishedMilliseconds = siteReader.getLong();
final long refreshedMilliseconds = siteReader.getLong();
final byte[] id = Arrays.copyOfRange(sitePayload, siteReader.position(), sitePayload.length);
final String idString = Base64.getEncoder().encodeToString(id);
final Instant established = Instant.ofEpochMilli(establishedMilliseconds);
final Instant expiry = Instant.ofEpochMilli(expiresMilliseconds);
// if (now.isAfter(expiry)) {
// return DecryptionResponse.makeError(DecryptionStatus.EXPIRED_TOKEN, established, siteId, siteKey.getSiteId(), identityType, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
// }
if (!isDomainOrAppNameAllowedForSite(clientType, privacyBits.isClientSideGenerated(), siteId, domainOrAppName, keys)) {
return DecryptionResponse.makeError(DecryptionStatus.DOMAIN_OR_APP_NAME_CHECK_FAILED, established, siteId, siteKey.getSiteId(), identityType, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
}
if (!doesTokenHaveValidLifetime(clientType, keys, generated, expiry, now)) {
return DecryptionResponse.makeError(DecryptionStatus.INVALID_TOKEN_LIFETIME, generated, siteId, siteKey.getSiteId(), identityType, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
}
return new DecryptionResponse(DecryptionStatus.SUCCESS, idString, established, siteId, siteKey.getSiteId(), identityType, advertisingTokenVersion, privacyBits.isClientSideGenerated(), expiry);
} catch (ArrayIndexOutOfBoundsException payloadEx) {
return DecryptionResponse.makeError(DecryptionStatus.INVALID_PAYLOAD);
}
}
static EncryptionDataResponse encrypt(String rawUid, KeyContainer keys, IdentityScope identityScope, Instant now)
{
if (keys == null)
return EncryptionDataResponse.makeError(EncryptionStatus.NOT_INITIALIZED);
else if (!keys.isValid(now))
return EncryptionDataResponse.makeError(EncryptionStatus.KEYS_NOT_SYNCED);
Key masterKey = keys.getMasterKey(now);
if (masterKey == null)
return EncryptionDataResponse.makeError(EncryptionStatus.NOT_AUTHORIZED_FOR_MASTER_KEY);
Key defaultKey = keys.getDefaultKey(now);
if (defaultKey == null)
{
return EncryptionDataResponse.makeError(EncryptionStatus.NOT_AUTHORIZED_FOR_KEY);
}
Instant expiry = now.plusSeconds(keys.getTokenExpirySeconds());
Uid2TokenGenerator.Params encryptParams = Uid2TokenGenerator.defaultParams().WithTokenGenerated(Instant.now()).withTokenExpiry(expiry);
try
{
String advertisingToken = (identityScope == IdentityScope.UID2) ? Uid2TokenGenerator.generateUid2TokenV4(rawUid, masterKey, keys.getCallerSiteId(), defaultKey, encryptParams) :
Uid2TokenGenerator.generateEuidTokenV4(rawUid, masterKey, keys.getCallerSiteId(), defaultKey, encryptParams);
return new EncryptionDataResponse(EncryptionStatus.SUCCESS, advertisingToken);
}
catch (Exception e)
{
return EncryptionDataResponse.makeError(EncryptionStatus.ENCRYPTION_FAILURE);
}
}
static EncryptionDataResponse encryptData(EncryptionDataRequest request, KeyContainer keys, IdentityScope identityScope, String domainOrAppName, ClientType clientType) {
if (request.getData() == null) {
throw new IllegalArgumentException("data to encrypt must not be null");
}
final Instant now = request.getNow();
Key key = request.getKey();
int siteId = -1;
if (key == null) {
int siteKeySiteId;
if (keys == null) {
return EncryptionDataResponse.makeError(EncryptionStatus.NOT_INITIALIZED);
} else if (!keys.isValid(now)) {
return EncryptionDataResponse.makeError(EncryptionStatus.KEYS_NOT_SYNCED);
} else if (request.getSiteId() != null && request.getAdvertisingToken() != null) {
throw new IllegalArgumentException("only one of siteId or advertisingToken can be specified");
} else if (request.getSiteId() != null) {
siteId = request.getSiteId();
siteKeySiteId = siteId;
} else {
try {
DecryptionResponse decryptedToken = decrypt(request.getAdvertisingToken(), keys, now, identityScope, domainOrAppName, clientType);
if (!decryptedToken.isSuccess()) {
return EncryptionDataResponse.makeError(EncryptionStatus.TOKEN_DECRYPT_FAILURE);
}
siteId = decryptedToken.getSiteId();
siteKeySiteId = decryptedToken.getSiteKeySiteId();
} catch (Exception ex) {
return EncryptionDataResponse.makeError(EncryptionStatus.TOKEN_DECRYPT_FAILURE);
}
}
key = keys.getActiveSiteKey(siteKeySiteId, now);
if (key == null) {
return EncryptionDataResponse.makeError(EncryptionStatus.NOT_AUTHORIZED_FOR_KEY);
}
} else if (!key.isActive(now)) {
return EncryptionDataResponse.makeError(EncryptionStatus.KEY_INACTIVE);
} else {
siteId = key.getSiteId();
}
byte[] iv = request.getInitializationVector();
try {
final ByteBuffer payloadWriter = ByteBuffer.allocate(request.getData().length + 12);
payloadWriter.putLong(now.toEpochMilli());
payloadWriter.putInt(siteId);
payloadWriter.put(request.getData());
final byte[] encryptedPayload = encryptGCM(payloadWriter.array(), iv, key.getSecret());
final ByteBuffer writer = ByteBuffer.allocate(encryptedPayload.length + 6);
writer.put((byte)(PayloadType.ENCRYPTED_DATA_V3.value | (identityScope.value << 4) | 0xB));
writer.put((byte)112); // version
writer.putInt((int)key.getId());
writer.put(encryptedPayload);
return new EncryptionDataResponse(EncryptionStatus.SUCCESS, Base64.getEncoder().encodeToString(writer.array()));
} catch (Exception ex) {
return EncryptionDataResponse.makeError(EncryptionStatus.ENCRYPTION_FAILURE);
}
}
static DecryptionDataResponse decryptData(byte[] encryptedBytes, KeyContainer keys, IdentityScope identityScope) throws Exception {
if ((encryptedBytes[0] & 224) == (int)PayloadType.ENCRYPTED_DATA_V3.value)
{
return decryptDataV3(encryptedBytes, keys, identityScope);
}
else
{
return decryptDataV2(encryptedBytes, keys);
}
}
static DecryptionDataResponse decryptDataV2(byte[] encryptedBytes, KeyContainer keys) throws Exception {
ByteBuffer reader = ByteBuffer.wrap(encryptedBytes);
if (Byte.toUnsignedInt(reader.get()) != PayloadType.ENCRYPTED_DATA.value) {
return DecryptionDataResponse.makeError(DecryptionStatus.INVALID_PAYLOAD_TYPE);
} else if (reader.get() != 1) {
return DecryptionDataResponse.makeError(DecryptionStatus.VERSION_NOT_SUPPORTED);
}
final Instant encryptedAt = Instant.ofEpochMilli(reader.getLong());
final int siteId = reader.getInt();
final long keyId = reader.getInt();
final Key key = keys.getKey(keyId);
if (key == null) {
return DecryptionDataResponse.makeError(DecryptionStatus.NOT_AUTHORIZED_FOR_KEY);
}
byte[] iv = new byte[16];
reader.get(iv);
byte[] decryptedData = decrypt(
Arrays.copyOfRange(encryptedBytes, 34, encryptedBytes.length),
iv,
key.getSecret());
return new DecryptionDataResponse(DecryptionStatus.SUCCESS, decryptedData, encryptedAt);
}
static DecryptionDataResponse decryptDataV3(byte[] encryptedBytes, KeyContainer keys, IdentityScope identityScope) {
final ByteBuffer reader = ByteBuffer.wrap(encryptedBytes);
final IdentityScope payloadScope = decodeIdentityScopeV3(reader.get());
if (payloadScope != identityScope)
{
return DecryptionDataResponse.makeError(DecryptionStatus.INVALID_IDENTITY_SCOPE);
}
if (reader.get() != 112)
{
return DecryptionDataResponse.makeError(DecryptionStatus.VERSION_NOT_SUPPORTED);
}
final long keyId = reader.getInt();
final Key key = keys.getKey(keyId);
if (key == null) {
return DecryptionDataResponse.makeError(DecryptionStatus.NOT_AUTHORIZED_FOR_KEY);
}
final byte[] payload = decryptGCM(encryptedBytes, reader.position(), key.getSecret());
final ByteBuffer payloadReader = ByteBuffer.wrap(payload, 0, payload.length);
final Instant encryptedAt = Instant.ofEpochMilli(payloadReader.getLong());
final int siteId = payloadReader.getInt();
final byte[] decryptedData = Arrays.copyOfRange(payload, payloadReader.position(), payload.length);
return new DecryptionDataResponse(DecryptionStatus.SUCCESS, decryptedData, encryptedAt);
}
private static byte[] decrypt(byte[] data, byte[] iv, byte[] secret)
throws CryptoException,
NoSuchPaddingException,
NoSuchAlgorithmException {
try {
SecretKey key = new SecretKeySpec(secret, 0, secret.length, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return cipher.doFinal(data);
} catch (InvalidAlgorithmParameterException|InvalidKeyException|BadPaddingException|IllegalBlockSizeException e) {
throw new CryptoException(e);
}
// if NoSuchPaddingException or NoSuchAlgorithmException
// your system/jvm has no AES algorithm providers
}
public static byte[] encryptGCM(byte[] b, byte[] iv, byte[] secretBytes) {
try {
final SecretKey k = new SecretKeySpec(secretBytes, "AES");
final Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
if (iv == null) {
iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
}
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_AUTHTAG_LENGTH * 8, iv);
c.init(Cipher.ENCRYPT_MODE, k, gcmParameterSpec);
ByteBuffer buffer = ByteBuffer.allocate(b.length + GCM_IV_LENGTH + GCM_AUTHTAG_LENGTH);
buffer.put(iv);
buffer.put(c.doFinal(b));
return buffer.array();
} catch (Exception e) {
throw new RuntimeException("Unable to Encrypt", e);
}
}
public static byte[] decryptGCM(byte[] encryptedBytes, int offset, byte[] secretBytes) {
try {
final SecretKey key = new SecretKeySpec(secretBytes, "AES");
final GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_AUTHTAG_LENGTH * 8, encryptedBytes, offset, GCM_IV_LENGTH);
final Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);
return c.doFinal(encryptedBytes, offset + GCM_IV_LENGTH, encryptedBytes.length - offset - GCM_IV_LENGTH);
} catch (javax.crypto.AEADBadTagException e) {
// Tag verification failed
if (skipAeadCheck) {
// Skip AEAD tag check - decrypt without tag verification using CTR mode
// GCM uses CTR mode internally for encryption, so we can decrypt using CTR mode
try {
final SecretKey key = new SecretKeySpec(secretBytes, "AES");
// Extract IV and ciphertext (excluding the tag)
byte[] iv = Arrays.copyOfRange(encryptedBytes, offset, offset + GCM_IV_LENGTH);
int totalLength = encryptedBytes.length - offset - GCM_IV_LENGTH;
int ciphertextLength = totalLength - GCM_AUTHTAG_LENGTH;
if (ciphertextLength > 0) {
byte[] ciphertextWithoutTag = Arrays.copyOfRange(encryptedBytes, offset + GCM_IV_LENGTH, offset + GCM_IV_LENGTH + ciphertextLength);
// GCM uses CTR mode internally. Create a 16-byte IV for CTR mode:
// First 12 bytes are the GCM IV, last 4 bytes are counter (starting at 1 for GCM ciphertext)
byte[] ctrIv = new byte[16];
System.arraycopy(iv, 0, ctrIv, 0, GCM_IV_LENGTH);
// Set counter to 1 (big-endian) - GCM uses counter 0 for tag, counter 1+ for ciphertext
ctrIv[12] = 0;
ctrIv[13] = 0;
ctrIv[14] = 0;
ctrIv[15] = 1;
// Use CTR mode which doesn't verify tags
Cipher ctrCipher = Cipher.getInstance("AES/CTR/NoPadding");
ctrCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ctrIv));
return ctrCipher.doFinal(ciphertextWithoutTag);
}
} catch (Exception fallbackEx) {
// If fallback fails, throw original exception
throw new RuntimeException("Unable to Decrypt (tag verification failed and skip mode also failed)", e);
}
}
throw new RuntimeException("Unable to Decrypt", e);
} catch (Exception e) {
throw new RuntimeException("Unable to Decrypt", e);
}
}
private static IdentityScope decodeIdentityScopeV3(byte value)
{
return IdentityScope.fromValue((value >> 4) & 1);
}
public static class CryptoException extends Exception {
public CryptoException(Throwable inner) {
super(inner);
}
}
private static boolean isDomainOrAppNameAllowedForSite(ClientType clientType, boolean isClientSideGenerated, Integer siteId, String domainOrAppName, KeyContainer keys) {
if (!isClientSideGenerated) {
return true;
} else if (!clientType.equals(ClientType.BIDSTREAM) && !clientType.equals(ClientType.LEGACY)) {
return true;
} else {
return keys.isDomainOrAppNameAllowedForSite(siteId, domainOrAppName);
}
}
private static boolean doesTokenHaveValidLifetime(ClientType clientType, KeyContainer keys, Instant generatedOrNow, Instant expiry, Instant now) {
long maxLifetimeSeconds;
switch (clientType) {
case BIDSTREAM:
maxLifetimeSeconds = keys.getMaxBidstreamLifetimeSeconds();
break;
case SHARING:
maxLifetimeSeconds = keys.getMaxSharingLifetimeSeconds();
break;
default: //Legacy
return true;
}
//generatedOrNow allows "now" for token v2, since v2 does not contain a "token generated" field. v2 therefore checks against remaining lifetime rather than total lifetime.
return doesTokenHaveValidLifetimeImpl(generatedOrNow, expiry, now, maxLifetimeSeconds, keys.getAllowClockSkewSeconds());
}
private static boolean doesTokenHaveValidLifetimeImpl(Instant generatedOrNow, Instant expiry, Instant now, long maxLifetimeSeconds, long allowClockSkewSeconds)
{
Duration lifetime = Duration.between(generatedOrNow, expiry);
if (lifetime.getSeconds() > maxLifetimeSeconds) {
return false;
}
Duration skewDuration = Duration.between(now, generatedOrNow);
return skewDuration.getSeconds() <= allowClockSkewSeconds;
}
private static IdentityType getIdentityType(byte[] encryptedId)
{
// For specifics about the bitwise logic, check:
// Confluence - UID2-79 UID2 Token v3/v4 and Raw UID2 format v3
// In the base64-encoded version of encryptedId, the first character is always either A/B/E/F.
// After converting to binary and performing the AND operation against 1100,the result is always 0X00.
// So just bitshift right twice to get 000X, which results in either 0 or 1.
byte idType = encryptedId[0];
byte piiType = (byte) ((idType & 0b1100) >> 2);
return piiType == 0 ? IdentityType.Email : IdentityType.Phone;
}
}