Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / registration / WhatsAppDeviceFingerprint.kt

WhatsAppDeviceFingerprint.kt69 lines · 2.8 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp.registration
2
3import android.content.Context
4import android.util.Base64
5import androidx.core.content.edit
6import java.security.SecureRandom
7import java.util.UUID
8
9/**
10 * Stable per-install device identifiers required by the `/v2/ endpoints. Generated ONCE and
11 * persisted, then replayed on every registration call so retries/verification line up server-side.
12 *
13 * Encodings mirror the APK (`C34244EyE`, see [RegEncoding]):
14 * - [fdid] → `fdid` : the UUID STRING as-is (A01 plain).
15 * - [expid] → `expid` : a UUID whose 16 bytes are URL-safe-base64 encoded (A03).
16 * - [recoveryToken] → `id` : raw bytes, percent-encoded (A05).
17 * - [backupToken] → `backup_token` : raw bytes, percent-encoded (A05).
18 * - [attestationKey] keys the optional `H` HMAC.
19 */
20class WhatsAppDeviceFingerprint private constructor(
21 val fdid: String,
22 val expid: String,
23 val recoveryToken: ByteArray,
24 val backupToken: ByteArray,
25 val attestationKey: ByteArray,
26) {
27 /** Preference keys and factories for the WhatsApp device fingerprint. */
28 companion object {
29 private const val PREFS = "communicate_whatsapp_fingerprint"
30 private const val K_FDID = "fdid"
31 private const val K_EXPID = "expid_uuid"
32 private const val K_ID = "recovery_id"
33 private const val K_BACKUP = "backup_token"
34 private const val K_ATTEST = "attest_key"
35 private const val RECOVERY_TOKEN_BYTES = 16
36 private const val BACKUP_TOKEN_BYTES = 20
37 private const val ATTESTATION_KEY_BYTES = 32
38
39 fun getOrCreate(context: Context): WhatsAppDeviceFingerprint {
40 val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
41 val rng = SecureRandom()
42
43 fun bytes(key: String, len: Int): ByteArray {
44 val existing = prefs.getString(key, null)
45 if (existing != null) return Base64.decode(existing, Base64.NO_WRAP)
46 val b = ByteArray(len).also { rng.nextBytes(it) }
47 prefs.edit { putString(key, Base64.encodeToString(b, Base64.NO_WRAP)) }
48 return b
49 }
50
51 fun uuid(key: String): String =
52 prefs.getString(key, null) ?: UUID.randomUUID().toString().also {
53 prefs.edit { putString(key, it) }
54 }
55
56 return WhatsAppDeviceFingerprint(
57 fdid = uuid(K_FDID),
58 expid = uuid(K_EXPID),
59 recoveryToken = bytes(K_ID, RECOVERY_TOKEN_BYTES),
60 backupToken = bytes(K_BACKUP, BACKUP_TOKEN_BYTES),
61 attestationKey = bytes(K_ATTEST, ATTESTATION_KEY_BYTES),
62 )
63 }
64
65 fun clear(context: Context) {
66 context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { clear() }
67 }
68 }
69}