Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / e2e / WhatsAppE2E.kt
WhatsAppE2E.kt472 lines · 20.4 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp.e2e |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData |
| 5 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase |
| 6 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppE2EPreKey |
| 7 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppE2ESenderKey |
| 8 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppE2ESession |
| 9 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol |
| 10 | import kotlinx.coroutines.runBlocking |
| 11 | import kotlin.io.encoding.Base64 |
| 12 | import kotlin.io.encoding.ExperimentalEncodingApi |
| 13 | |
| 14 | /** |
| 15 | * Rust-backed E2E crypto for WhatsApp (X3DH + Double Ratchet + Sender Keys). |
| 16 | * Kotlin owns persistence (Room) and passes opaque session/sender-key blobs to Rust. |
| 17 | * |
| 18 | * Record format is Rust's own versioned encoding (RECORD_VERSION=1), not Java's |
| 19 | * SignalRecord. Migration 6->7 clears the E2E tables, forcing a re-link. |
| 20 | */ |
| 21 | @OptIn(ExperimentalEncodingApi::class) |
| 22 | class WhatsAppE2E( |
| 23 | private val db: WhatsAppDatabase, |
| 24 | private val auth: WhatsAppAuthData, |
| 25 | ) { |
| 26 | |
| 27 | /** Raw 32-byte identity public key for upload. */ |
| 28 | val ownIdentityPublicKey: ByteArray = b64(auth.identityPublicKey) |
| 29 | |
| 30 | private val ownIdentityPrivate: ByteArray = b64(auth.identityPrivateKey) |
| 31 | private val ownSignedPreKeyPrivate: ByteArray = b64(auth.signedPreKeyPrivate) |
| 32 | private val ownSignedPreKeyPublic: ByteArray = b64(auth.signedPreKeyPublic) |
| 33 | |
| 34 | private val ownUser: String = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".") |
| 35 | private val ownDeviceId: Int = auth.deviceId |
| 36 | |
| 37 | // ----------------------------------------------------------------------- |
| 38 | // JID parsing — matches whatsmeow JID.SignalAddress: name=user, deviceId=device |
| 39 | // ----------------------------------------------------------------------- |
| 40 | |
| 41 | private fun parseJid(jid: String): Pair<String, Int> { |
| 42 | val local = jid.substringBefore("@") |
| 43 | val user = local.substringBefore(":").substringBefore(".") |
| 44 | val device = local.substringAfter(":", "0").toIntOrNull() ?: 0 |
| 45 | return user to device |
| 46 | } |
| 47 | |
| 48 | fun signalAddress(jid: String): Pair<String, Int> = parseJid(jid) |
| 49 | |
| 50 | fun hasSession(jid: String): Boolean { |
| 51 | val (name, dev) = parseJid(jid) |
| 52 | return runBlocking { db.e2eSessionDao().exists(name, dev) } |
| 53 | } |
| 54 | |
| 55 | fun deleteSession(jid: String) { |
| 56 | val (name, dev) = parseJid(jid) |
| 57 | runBlocking { db.e2eSessionDao().delete(name, dev) } |
| 58 | } |
| 59 | |
| 60 | // -- 1:1 encrypt / decrypt ------------------------------------------------ |
| 61 | |
| 62 | /** An encrypted 1:1 message: wire type (pkmsg/msg) and ciphertext. */ |
| 63 | data class EncResult(val type: String, val data: ByteArray) |
| 64 | |
| 65 | fun encryptDM(jid: String, paddedPlaintext: ByteArray): EncResult { |
| 66 | val (name, dev) = parseJid(jid) |
| 67 | val entity = runBlocking { db.e2eSessionDao().get(name, dev) } |
| 68 | ?: throw IllegalStateException("No session for $jid") |
| 69 | val result = RustWhatsAppCrypto.encryptSplit(entity.record, paddedPlaintext) |
| 70 | runBlocking { |
| 71 | db.e2eSessionDao().insert(WhatsAppE2ESession(name, dev, result.newSession)) |
| 72 | } |
| 73 | return EncResult(if (result.isPreKey) "pkmsg" else "msg", result.body) |
| 74 | } |
| 75 | |
| 76 | fun decryptDM(jid: String, isPreKey: Boolean, ciphertext: ByteArray): ByteArray { |
| 77 | val (name, dev) = parseJid(jid) |
| 78 | return if (isPreKey) { |
| 79 | // Inbound pkmsg: X3DH bob side + first message. |
| 80 | val preKeyId = parsePreKeyIdFromMessage(ciphertext) |
| 81 | val oneTimePriv: ByteArray? = if (preKeyId != null) { |
| 82 | val entity = runBlocking { db.e2ePreKeyDao().get(preKeyId) } |
| 83 | entity?.let { rec -> |
| 84 | // record = private(32) || public(32) |
| 85 | if (rec.record.size >= IDENTITY_KEY_SIZE) { |
| 86 | rec.record.copyOfRange(0, IDENTITY_KEY_SIZE) |
| 87 | } else { |
| 88 | null |
| 89 | } |
| 90 | } |
| 91 | } else null |
| 92 | |
| 93 | val decrypted = RustWhatsAppCrypto.decryptPreKeySplit( |
| 94 | localIdentityPrivate = ownIdentityPrivate, |
| 95 | localIdentityPublic = ownIdentityPublicKey, |
| 96 | signedPreKeyPrivate = ownSignedPreKeyPrivate, |
| 97 | oneTimePrivate = oneTimePriv, |
| 98 | preKeyMessageBytes = ciphertext, |
| 99 | ) |
| 100 | runBlocking { |
| 101 | db.e2eSessionDao().insert(WhatsAppE2ESession(name, dev, decrypted.newSession)) |
| 102 | if (preKeyId != null) { |
| 103 | try { db.e2ePreKeyDao().delete(preKeyId) } catch (_: Exception) {} |
| 104 | } |
| 105 | } |
| 106 | decrypted.plaintext |
| 107 | } else { |
| 108 | val entity = runBlocking { db.e2eSessionDao().get(name, dev) } |
| 109 | ?: throw IllegalStateException("No session for $jid (msg)") |
| 110 | val decrypted = RustWhatsAppCrypto.decryptMessageSplit(entity.record, ciphertext) |
| 111 | runBlocking { |
| 112 | db.e2eSessionDao().insert(WhatsAppE2ESession(name, dev, decrypted.newSession)) |
| 113 | } |
| 114 | decrypted.plaintext |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // -- Parsed bundle -------------------------------------------------------- |
| 119 | |
| 120 | /** A peers pre-key bundle parsed off the wire: registration id, pre-keys and identity key. */ |
| 121 | data class ParsedPreKeyBundle( |
| 122 | val registrationId: Int, |
| 123 | val preKeyId: Int?, // null if absent |
| 124 | val preKeyPublic: ByteArray?, // 32 bytes or null |
| 125 | val signedPreKeyId: Int, |
| 126 | val signedPreKeyPublic: ByteArray, // 32 |
| 127 | val signedPreKeySignature: ByteArray, // 64 |
| 128 | val identityKey: ByteArray, // 32 |
| 129 | ) |
| 130 | |
| 131 | fun processPreKeyBundle(jid: String, bundle: ParsedPreKeyBundle) { |
| 132 | val (name, dev) = parseJid(jid) |
| 133 | val sessionBytes = RustWhatsAppCrypto.processPreKeyBundle( |
| 134 | localIdentityPrivate = ownIdentityPrivate, |
| 135 | localIdentityPublic = ownIdentityPublicKey, |
| 136 | localRegistrationId = auth.registrationId, |
| 137 | registrationId = bundle.registrationId, |
| 138 | preKeyId = bundle.preKeyId ?: -1, |
| 139 | preKeyPublic = bundle.preKeyPublic, |
| 140 | signedPreKeyId = bundle.signedPreKeyId, |
| 141 | signedPreKeyPublic = bundle.signedPreKeyPublic, |
| 142 | signedPreKeySignature = bundle.signedPreKeySignature, |
| 143 | identityKey = bundle.identityKey, |
| 144 | ) ?: throw IllegalStateException("Rust processPreKeyBundle returned null") |
| 145 | runBlocking { |
| 146 | db.e2eSessionDao().insert(WhatsAppE2ESession(name, dev, sessionBytes)) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // -- Group (sender key) --------------------------------------------------- |
| 151 | |
| 152 | fun createSenderKeyDistribution(groupJid: String): ByteArray { |
| 153 | // Always mint a new sender key (matches GroupSessionBuilder.create overwriting). |
| 154 | val created = RustWhatsAppCrypto.createSenderKeySplit() |
| 155 | runBlocking { |
| 156 | db.e2eSenderKeyDao().insert( |
| 157 | WhatsAppE2ESenderKey(ownUser, ownDeviceId, groupJid, created.state) |
| 158 | ) |
| 159 | } |
| 160 | return created.skdm |
| 161 | } |
| 162 | |
| 163 | fun processSenderKeyDistribution(groupJid: String, senderJid: String, skdmBytes: ByteArray) { |
| 164 | val (sName, sDev) = parseJid(senderJid) |
| 165 | val stateBytes = RustWhatsAppCrypto.processSenderKey(skdmBytes) |
| 166 | ?: throw IllegalStateException("processSenderKey returned null") |
| 167 | runBlocking { |
| 168 | db.e2eSenderKeyDao().insert( |
| 169 | WhatsAppE2ESenderKey(sName, sDev, groupJid, stateBytes) |
| 170 | ) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | fun encryptGroup(groupJid: String, paddedPlaintext: ByteArray): ByteArray { |
| 175 | var stateEntity = runBlocking { db.e2eSenderKeyDao().get(ownUser, ownDeviceId, groupJid) } |
| 176 | if (stateEntity == null) { |
| 177 | // No sender key yet — create one (first group message). |
| 178 | val created = RustWhatsAppCrypto.createSenderKeySplit() |
| 179 | runBlocking { |
| 180 | db.e2eSenderKeyDao().insert( |
| 181 | WhatsAppE2ESenderKey(ownUser, ownDeviceId, groupJid, created.state) |
| 182 | ) |
| 183 | } |
| 184 | stateEntity = runBlocking { db.e2eSenderKeyDao().get(ownUser, ownDeviceId, groupJid) } |
| 185 | ?: throw IllegalStateException("Failed to create sender key") |
| 186 | } |
| 187 | val encrypted = RustWhatsAppCrypto.encryptGroupSplit(stateEntity.record, paddedPlaintext) |
| 188 | runBlocking { |
| 189 | db.e2eSenderKeyDao().insert( |
| 190 | WhatsAppE2ESenderKey(ownUser, ownDeviceId, groupJid, encrypted.newState) |
| 191 | ) |
| 192 | } |
| 193 | return encrypted.data |
| 194 | } |
| 195 | |
| 196 | fun decryptGroup(groupJid: String, senderJid: String, ciphertext: ByteArray): ByteArray { |
| 197 | val (sName, sDev) = parseJid(senderJid) |
| 198 | val entity = runBlocking { db.e2eSenderKeyDao().get(sName, sDev, groupJid) } |
| 199 | ?: throw IllegalStateException("No sender key for $senderJid in $groupJid") |
| 200 | val decrypted = RustWhatsAppCrypto.decryptGroupSplit(entity.record, ciphertext) |
| 201 | runBlocking { |
| 202 | db.e2eSenderKeyDao().insert( |
| 203 | WhatsAppE2ESenderKey(sName, sDev, groupJid, decrypted.newState) |
| 204 | ) |
| 205 | } |
| 206 | return decrypted.data |
| 207 | } |
| 208 | |
| 209 | // -- Prekey seeding & upload --------------------------------------------- |
| 210 | |
| 211 | /** |
| 212 | * Previously seeded the signed prekey into the Java store for inbound pkmsg. |
| 213 | * With Rust we use the raw keys from auth directly, so this is now a no-op |
| 214 | * kept for call-site compatibility. |
| 215 | */ |
| 216 | fun ensureSignedPreKeyStored() { |
| 217 | // no-op |
| 218 | } |
| 219 | |
| 220 | private data class LocalPreKey(val id: Int, val publicKey: ByteArray) |
| 221 | |
| 222 | private fun generatePreKeys(count: Int): List<LocalPreKey> { |
| 223 | val maxId = runBlocking { db.e2ePreKeyDao().getMaxId() } |
| 224 | val entities = ArrayList<WhatsAppE2EPreKey>(count) |
| 225 | val locals = ArrayList<LocalPreKey>(count) |
| 226 | for (i in 1..count) { |
| 227 | val id = maxId + i |
| 228 | val kp = RustWhatsAppCrypto.generateKeyPairSplit() |
| 229 | // Store as private||public (64 bytes) — private needed for inbound pkmsg. |
| 230 | val record = kp.privateKey + kp.publicKey |
| 231 | entities.add(WhatsAppE2EPreKey(id, record, uploaded = false)) |
| 232 | locals.add(LocalPreKey(id, kp.publicKey)) |
| 233 | } |
| 234 | runBlocking { db.e2ePreKeyDao().insertAll(entities) } |
| 235 | return locals |
| 236 | } |
| 237 | |
| 238 | fun buildPreKeyUploadContent(initialUpload: Boolean): List<WhatsAppProtocol.Node> { |
| 239 | val wanted = if (initialUpload) INITIAL_PREKEY_UPLOAD else REFILL_PREKEY_COUNT |
| 240 | val records = generatePreKeys(wanted) |
| 241 | |
| 242 | val regBytes = ByteArray(REGISTRATION_ID_SIZE) |
| 243 | regBytes[0] = (auth.registrationId ushr SHIFT_BYTE3).toByte() |
| 244 | regBytes[1] = (auth.registrationId ushr SHIFT_BYTE2).toByte() |
| 245 | regBytes[2] = (auth.registrationId ushr SHIFT_BYTE1).toByte() |
| 246 | regBytes[REGISTRATION_ID_SIZE - 1] = auth.registrationId.toByte() |
| 247 | |
| 248 | val listNode = WhatsAppProtocol.Node( |
| 249 | tag = "list", |
| 250 | content = records.map { preKeyToNode(it.id, it.publicKey, null) }, |
| 251 | ) |
| 252 | val signedNode = preKeyToNode( |
| 253 | auth.signedPreKeyId, |
| 254 | b64(auth.signedPreKeyPublic), |
| 255 | b64(auth.signedPreKeySignature), |
| 256 | ) |
| 257 | |
| 258 | return listOf( |
| 259 | WhatsAppProtocol.Node(tag = "registration", data = regBytes), |
| 260 | WhatsAppProtocol.Node(tag = "type", data = byteArrayOf(PREKEY_VERSION_BYTE)), |
| 261 | WhatsAppProtocol.Node(tag = "identity", data = ownIdentityPublicKey), |
| 262 | listNode, |
| 263 | signedNode, |
| 264 | ) |
| 265 | } |
| 266 | |
| 267 | fun markPreKeysUploaded() { |
| 268 | val maxId = runBlocking { db.e2ePreKeyDao().getMaxId() } |
| 269 | runBlocking { db.e2ePreKeyDao().markUploadedUpTo(maxId) } |
| 270 | } |
| 271 | |
| 272 | fun buildRetryReceiptKeysNode(accountDeviceIdentity: ByteArray?): WhatsAppProtocol.Node { |
| 273 | val oneTime = generatePreKeys(1).first() |
| 274 | val children = mutableListOf( |
| 275 | WhatsAppProtocol.Node(tag = "type", data = byteArrayOf(PREKEY_VERSION_BYTE)), |
| 276 | WhatsAppProtocol.Node(tag = "identity", data = ownIdentityPublicKey), |
| 277 | preKeyToNode(oneTime.id, oneTime.publicKey, null), |
| 278 | preKeyToNode(auth.signedPreKeyId, b64(auth.signedPreKeyPublic), b64(auth.signedPreKeySignature)), |
| 279 | ) |
| 280 | if (accountDeviceIdentity != null) { |
| 281 | children.add(WhatsAppProtocol.Node(tag = "device-identity", data = accountDeviceIdentity)) |
| 282 | } |
| 283 | return WhatsAppProtocol.Node(tag = "keys", content = children) |
| 284 | } |
| 285 | |
| 286 | private fun preKeyToNode(id: Int, pub32: ByteArray, signature: ByteArray?): WhatsAppProtocol.Node { |
| 287 | val idBytes = byteArrayOf( |
| 288 | (id ushr SHIFT_BYTE2).toByte(), |
| 289 | (id ushr SHIFT_BYTE1).toByte(), |
| 290 | id.toByte(), |
| 291 | ) |
| 292 | val children = mutableListOf( |
| 293 | WhatsAppProtocol.Node(tag = "id", data = idBytes), |
| 294 | WhatsAppProtocol.Node(tag = "value", data = pub32), |
| 295 | ) |
| 296 | return if (signature != null) { |
| 297 | children.add(WhatsAppProtocol.Node(tag = "signature", data = signature)) |
| 298 | WhatsAppProtocol.Node(tag = "skey", content = children) |
| 299 | } else { |
| 300 | WhatsAppProtocol.Node(tag = "key", content = children) |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | fun parsePreKeyBundleNode(deviceId: Int, userNode: WhatsAppProtocol.Node): ParsedPreKeyBundle? { |
| 305 | return try { |
| 306 | if (userNode.getChildByTag("error") != null) { |
| 307 | Log.status(TAG, "prekey response error for device $deviceId") |
| 308 | return null |
| 309 | } |
| 310 | val registrationId = readRegistrationId(userNode) ?: return null |
| 311 | val keysNode = userNode.getChildByTag("keys") ?: userNode |
| 312 | val identityRaw = keysNode.getChildByTag("identity")?.data ?: return null |
| 313 | if (identityRaw.size != IDENTITY_KEY_SIZE) return null |
| 314 | val (preKeyId, preKeyPublic) = readPreKey(keysNode) ?: (null to null) |
| 315 | val signed = readSignedPreKey(keysNode) ?: return null |
| 316 | ParsedPreKeyBundle( |
| 317 | registrationId = registrationId, |
| 318 | preKeyId = preKeyId, |
| 319 | preKeyPublic = preKeyPublic, |
| 320 | signedPreKeyId = signed.first, |
| 321 | signedPreKeyPublic = signed.second, |
| 322 | signedPreKeySignature = signed.third, |
| 323 | identityKey = identityRaw, |
| 324 | ) |
| 325 | } catch (expected: Exception) { |
| 326 | Log.status(TAG, "Failed to parse prekey bundle", expected) |
| 327 | null |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | private fun readRegistrationId(userNode: WhatsAppProtocol.Node): Int? { |
| 332 | val regBytes = userNode.getChildByTag("registration")?.data ?: return null |
| 333 | if (regBytes.size != REGISTRATION_ID_SIZE) return null |
| 334 | return ((regBytes[0].toInt() and BYTE_MASK) shl SHIFT_BYTE3) or |
| 335 | ((regBytes[1].toInt() and BYTE_MASK) shl SHIFT_BYTE2) or |
| 336 | ((regBytes[2].toInt() and BYTE_MASK) shl SHIFT_BYTE1) or |
| 337 | (regBytes[REGISTRATION_ID_SIZE - 1].toInt() and BYTE_MASK) |
| 338 | } |
| 339 | |
| 340 | /** Optional one-time prekey (id + public key), or null pair when absent. */ |
| 341 | private fun readPreKey(keysNode: WhatsAppProtocol.Node): Pair<Int?, ByteArray?>? { |
| 342 | val keyNode = keysNode.getChildByTag("key") ?: return null to null |
| 343 | val preKeyId = readKeyId(keyNode) ?: return null |
| 344 | val pub = keyNode.getChildByTag("value")?.data ?: return null |
| 345 | if (pub.size != IDENTITY_KEY_SIZE) return null |
| 346 | return preKeyId to pub |
| 347 | } |
| 348 | |
| 349 | /** Signed prekey triple (id, public, signature), or null when malformed. */ |
| 350 | private fun readSignedPreKey( |
| 351 | keysNode: WhatsAppProtocol.Node, |
| 352 | ): Triple<Int, ByteArray, ByteArray>? { |
| 353 | val skey = keysNode.getChildByTag("skey") ?: return null |
| 354 | val signedPreKeyId = readKeyId(skey) ?: return null |
| 355 | val signedPub = skey.getChildByTag("value")?.data |
| 356 | ?.takeIf { it.size == IDENTITY_KEY_SIZE } ?: return null |
| 357 | val signedSig = skey.getChildByTag("signature")?.data |
| 358 | ?.takeIf { it.size == SIGNATURE_SIZE } ?: return null |
| 359 | return Triple(signedPreKeyId, signedPub, signedSig) |
| 360 | } |
| 361 | |
| 362 | private fun readKeyId(node: WhatsAppProtocol.Node): Int? { |
| 363 | val idBytes = node.getChildByTag("id")?.data ?: return null |
| 364 | if (idBytes.size != KEY_ID_SIZE) return null |
| 365 | return ((idBytes[0].toInt() and BYTE_MASK) shl SHIFT_BYTE2) or |
| 366 | ((idBytes[1].toInt() and BYTE_MASK) shl SHIFT_BYTE1) or |
| 367 | (idBytes[2].toInt() and BYTE_MASK) |
| 368 | } |
| 369 | |
| 370 | /** Crypto size constants and logging tag for [WhatsAppE2E]. */ |
| 371 | companion object { |
| 372 | private const val TAG = "WhatsAppE2E" |
| 373 | private const val IDENTITY_KEY_SIZE = 32 |
| 374 | private const val SIGNATURE_SIZE = 64 |
| 375 | private const val SIGNED_MESSAGE_SIZE = 33 |
| 376 | private const val INITIAL_PREKEY_UPLOAD = 812 |
| 377 | private const val REFILL_PREKEY_COUNT = 50 |
| 378 | private const val REGISTRATION_ID_SIZE = 4 |
| 379 | private const val KEY_ID_SIZE = 3 |
| 380 | private const val BYTE_MASK = 0xFF |
| 381 | private const val VARINT_MASK = 0x7F |
| 382 | private const val VARINT_CONT = 0x80 |
| 383 | private const val VARINT_BITS = 7 |
| 384 | private const val FIELD_SHIFT = 3 |
| 385 | private const val WIRE_TYPE_MASK = 7 |
| 386 | private const val SHIFT_BYTE1 = 8 |
| 387 | private const val SHIFT_BYTE2 = 16 |
| 388 | private const val SHIFT_BYTE3 = 24 |
| 389 | private const val PREKEY_VERSION_BYTE: Byte = 0x05 |
| 390 | |
| 391 | private fun b64(s: String): ByteArray = Base64.Default.decode(s) |
| 392 | |
| 393 | /** |
| 394 | * Parse the optional preKeyId from a PreKeySignalMessage (version || protobuf). |
| 395 | * Minimal protobuf scan for field 1 varint. |
| 396 | */ |
| 397 | fun parsePreKeyIdFromMessage(data: ByteArray): Int? { |
| 398 | if (data.isEmpty()) return null |
| 399 | // Skip version byte (high nibble version) |
| 400 | var pos = 1 |
| 401 | while (pos < data.size) { |
| 402 | val field = readFieldKey(data, pos) ?: return null |
| 403 | pos = field.nextPos |
| 404 | if (field.wireType == 0) { |
| 405 | // varint |
| 406 | val (value, after) = readVarint(data, pos) |
| 407 | if (after == pos) return null // truncated |
| 408 | pos = after |
| 409 | if (field.number == 1) return value?.toInt() |
| 410 | } else { |
| 411 | pos = skipField(data, pos, field.wireType) ?: return null |
| 412 | } |
| 413 | } |
| 414 | return null |
| 415 | } |
| 416 | |
| 417 | private data class FieldKey(val number: Int, val wireType: Int, val nextPos: Int) |
| 418 | |
| 419 | /** Read a varint field key; null when truncated. */ |
| 420 | private fun readFieldKey(data: ByteArray, pos: Int): FieldKey? { |
| 421 | var keyVal = 0L |
| 422 | var shift = 0 |
| 423 | var idx = pos |
| 424 | var b: Int |
| 425 | do { |
| 426 | if (idx >= data.size) return null |
| 427 | b = data[idx].toInt() and BYTE_MASK |
| 428 | keyVal = keyVal or ((b and VARINT_MASK).toLong() shl shift) |
| 429 | shift += VARINT_BITS |
| 430 | idx++ |
| 431 | } while (b and VARINT_CONT != 0) |
| 432 | return FieldKey((keyVal shr FIELD_SHIFT).toInt(), (keyVal and WIRE_TYPE_MASK.toLong()).toInt(), idx) |
| 433 | } |
| 434 | |
| 435 | /** Read a varint value; null value when truncated. Returns (value, nextPos). */ |
| 436 | private fun readVarint(data: ByteArray, pos: Int): Pair<Long?, Int> { |
| 437 | var v = 0L |
| 438 | var shift = 0 |
| 439 | var p = pos |
| 440 | while (p < data.size) { |
| 441 | val b = data[p].toInt() and BYTE_MASK |
| 442 | v = v or ((b and VARINT_MASK).toLong() shl shift) |
| 443 | p++ |
| 444 | if (b and VARINT_CONT == 0) break |
| 445 | shift += VARINT_BITS |
| 446 | } |
| 447 | return (if (p > pos) v else null) to p |
| 448 | } |
| 449 | |
| 450 | /** Skip one field payload; null when truncated/unsupported. */ |
| 451 | private fun skipField(data: ByteArray, pos: Int, wireType: Int): Int? { |
| 452 | if (wireType != 2) return null // only length-delimited expected here |
| 453 | val (len, after) = readVarint(data, pos) |
| 454 | val length = len ?: return null |
| 455 | val end = after + length.toInt() |
| 456 | if (end > data.size) return null |
| 457 | return end |
| 458 | } |
| 459 | |
| 460 | /** |
| 461 | * XEdDSA signature over 0x05||signedPreKeyPub using raw 32-byte identity private. |
| 462 | * Uses Rust for constant-time signing. |
| 463 | */ |
| 464 | fun signSignedPreKey(identityPrivate32: ByteArray, signedPreKeyPublic32: ByteArray): ByteArray { |
| 465 | val message = ByteArray(SIGNED_MESSAGE_SIZE) |
| 466 | message[0] = PREKEY_VERSION_BYTE |
| 467 | System.arraycopy(signedPreKeyPublic32, 0, message, 1, IDENTITY_KEY_SIZE) |
| 468 | return RustWhatsAppCrypto.sign(identityPrivate32, message) |
| 469 | ?: throw IllegalStateException("Rust sign returned null") |
| 470 | } |
| 471 | } |
| 472 | } |