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

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

RegistrationKeys.kt130 lines · 6.7 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp.registration
2
3import android.util.Base64
4import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData
5import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto
6import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E
7import java.security.SecureRandom
8
9/**
10 * Generates and holds the client key material for a fresh primary registration: the Signal identity
11 * keypair, the Noise-static keypair, and a signed pre-key, plus `registrationId`/`signedPreKeyId`.
12 * Produces a [WhatsAppAuthData] scaffold to persist and the E2E-bundle wire fields.
13 *
14 * The E2E bundle fields (`authkey`, `e_ident`, `e_keytype`, `e_regid`, `e_skey_id`, `e_skey_val`,
15 * `e_skey_sig`) are **URL-safe base64, no padding** — matching the APK's `C34040Euf`→`A04`→`DIj.A0w`
16 * (flag 11). AuthData stores the same keys as STANDARD base64 for internal use, so [bundleFields]
17 * decodes and re-encodes to URL-safe base64 for the wire.
18 */
19class RegistrationKeys private constructor(
20 val authScaffold: WhatsAppAuthData,
21) {
22 /** URL-safe-base64 E2E bundle fields for `/v2/ endpoints` (from the freshly-generated scaffold). */
23 fun registerBundleFields(): Map<String, String> = bundleFields(authScaffold)
24
25 /** Registration key-bundle constants (whether the PQ bundle is attached). */
26 companion object {
27 /**
28 * DEFAULT **false** — do not attach the post-quantum `e_pq_last_resort_*` bundle to the
29 * `/v2` registration request. Restores the last live-verified param set (base commit
30 * `33dd602`, which returned `status:ok` with only the classic 7-field bundle); the PQ bundle
31 * added in `e7e120` was never validated live and its server acceptance is User-Agent-gated.
32 * Flip to `true` to generate + attach it (bundleFields still enforces all-or-none).
33 */
34 const val EMIT_PQ_LAST_RESORT = false
35 private const val MAX_REGISTRATION_ID = 0x3FFF
36 private const val BYTE_BITS = 8
37 private const val INT32_LEN = 4
38 private const val INT24_LEN = 3
39
40 fun generate(phoneNumber: String): RegistrationKeys {
41 val rng = SecureRandom()
42
43 val identity = RustWhatsAppCrypto.generateKeyPairSplit()
44 val noise = RustWhatsAppCrypto.generateKeyPairSplit()
45 val signedPreKey = RustWhatsAppCrypto.generateKeyPairSplit()
46
47 val registrationId = rng.nextInt(MAX_REGISTRATION_ID) + 1
48 val signedPreKeyId = 1
49
50 val signature = WhatsAppE2E.signSignedPreKey(identity.privateKey, signedPreKey.publicKey)
51
52 // Post-quantum last-resort prekey (Phase B 2d). DEFAULT OFF ([EMIT_PQ_LAST_RESORT]):
53 // this e_pq_* bundle was added in `e7e120` AFTER the last live-verified registration
54 // (whatsapp-documentation.md §2 sent only the classic 7-field bundle) and was never
55 // validated live; server PQ expectation is User-Agent-gated, so an unexpected/mismatched
56 // e_pq_* can draw bad_param. When off, the fields stay empty and bundleFields omits
57 // e_pq_* entirely (all-or-none), matching the verified param set. Best-effort even when
58 // enabled: a KEM/native-signer failure also leaves the fields empty.
59 val pq = if (EMIT_PQ_LAST_RESORT) {
60 try {
61 WhatsAppPqPreKey.generate(identity.privateKey, WhatsAppRegistrationConstants.PQ_LAST_RESORT_KEY_ID)
62 } catch (ignored: Throwable) {
63 null
64 }
65 } else {
66 null
67 }
68
69 val scaffold = WhatsAppAuthData(
70 phoneNumber = phoneNumber,
71 pushName = "",
72 wid = "", // filled from `new_jid` after /v2/register
73 noisePrivateKey = b64(noise.privateKey),
74 noisePublicKey = b64(noise.publicKey),
75 identityPrivateKey = b64(identity.privateKey),
76 identityPublicKey = b64(identity.publicKey),
77 registrationId = registrationId,
78 signedPreKeyId = signedPreKeyId,
79 signedPreKeyPublic = b64(signedPreKey.publicKey),
80 signedPreKeyPrivate = b64(signedPreKey.privateKey),
81 signedPreKeySignature = b64(signature),
82 deviceId = 0,
83 pqLastResortKeyId = pq?.keyId ?: 0,
84 pqLastResortPublic = pq?.let { b64(it.publicKey) } ?: "",
85 pqLastResortSecret = pq?.let { b64(it.secretKey) } ?: "",
86 pqLastResortSignature = pq?.let { b64(it.signature) } ?: "",
87 )
88 return RegistrationKeys(scaffold)
89 }
90
91 private fun b64(b: ByteArray): String = Base64.encodeToString(b, Base64.NO_WRAP)
92 private fun dec(s: String): ByteArray = Base64.decode(s, Base64.NO_WRAP)
93
94 /**
95 * The `/v2/ endpoints` E2E key bundle, URL-safe-base64 (A04), rebuilt from persisted [WhatsAppAuthData]
96 * so the same values are reused across the code→register calls.
97 */
98 fun bundleFields(auth: WhatsAppAuthData): Map<String, String> {
99 val map = linkedMapOf(
100 "e_regid" to RegEncoding.b64Url(intBe(auth.registrationId, INT32_LEN)),
101 "e_keytype" to RegEncoding.b64Url(byteArrayOf(WhatsAppRegistrationConstants.KEY_TYPE_CURVE25519)),
102 "e_ident" to RegEncoding.b64Url(dec(auth.identityPublicKey)),
103 "e_skey_id" to RegEncoding.b64Url(intBe(auth.signedPreKeyId, INT24_LEN)),
104 "e_skey_val" to RegEncoding.b64Url(dec(auth.signedPreKeyPublic)),
105 "e_skey_sig" to RegEncoding.b64Url(dec(auth.signedPreKeySignature)),
106 "authkey" to RegEncoding.b64Url(dec(auth.noisePublicKey)),
107 )
108 // Post-quantum last-resort prekey — all-or-none (w2.md §2.1). Only emit when the full
109 // triple is present; otherwise the server returns bad_param:e_pq_last_resort_*.
110 if (auth.pqLastResortKeyId != 0 &&
111 auth.pqLastResortPublic.isNotEmpty() &&
112 auth.pqLastResortSignature.isNotEmpty()
113 ) {
114 map["e_pq_last_resort_id"] = RegEncoding.b64Url(intBe(auth.pqLastResortKeyId, INT24_LEN))
115 map["e_pq_last_resort_val"] = RegEncoding.b64Url(dec(auth.pqLastResortPublic))
116 map["e_pq_last_resort_sig"] = RegEncoding.b64Url(dec(auth.pqLastResortSignature))
117 }
118 return map
119 }
120
121 /** Big-endian encode [value] into [len] bytes (len ≤ 4). */
122 private fun intBe(value: Int, len: Int): ByteArray {
123 val out = ByteArray(len)
124 for (i in 0 until len) {
125 out[len - 1 - i] = (value ushr (BYTE_BITS * i)).toByte()
126 }
127 return out
128 }
129 }
130}