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

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

WhatsAppCallCrypto.kt108 lines · 4.8 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp.call
2
3import java.nio.ByteBuffer
4import java.security.SecureRandom
5import javax.crypto.Mac
6import javax.crypto.spec.SecretKeySpec
7
8/**
9 * WhatsApp call-key crypto (Phase D 3b, whatsapp-documentation.md:373 `CryptoCallback`).
10 *
11 * The 32-byte **call key** is generated by the caller and fanned out per-device via the same Signal
12 * `<enc>` path as messages (see [WhatsAppCallSignaling] / `WhatsAppClient.encryptForDevices`). From
13 * it, both sides derive symmetric **media keys** via HKDF-SHA256 + HMAC-SHA256 and a **secure SSRC**,
14 * matching the `CryptoCallback` contract, and support `call_rekey` (a new call key derived from the
15 * previous one for a rekey message id).
16 *
17 * All derivations are pure (java.security only) and deterministic, so the vectors are unit-testable.
18 *
19 * NB: our client-to-client media path uses WebRTC's own DTLS-SRTP; these keys model WhatsApp's
20 * native SRTP key schedule and are exchanged/verified alongside the SDP so the derivation is
21 * exercised and asserted, even though byte-level interop with WhatsApp's native relay isn't possible.
22 */
23object WhatsAppCallCrypto {
24
25 const val CALL_KEY_LEN = 32
26 private const val SRTP_KEY_LEN = 16 // AES-128
27 private const val SRTP_SALT_LEN = 14 // SRTP session salt
28 private const val AUTH_KEY_LEN = 32 // HMAC-SHA256 auth key
29
30 private const val INFO_MEDIA = "WhatsApp Call Media Keys"
31 private const val INFO_REKEY = "WhatsApp Call Rekey"
32 private const val INFO_SSRC = "WhatsApp Call SSRC"
33 private const val INT_POSITIVE_MASK = 0x7FFFFFFF
34
35 private val rng = SecureRandom()
36
37 /** Derived symmetric media material for one direction of a call. */
38 data class MediaKeys(
39 val encKey: ByteArray, // 16B SRTP AES-128 key
40 val salt: ByteArray, // 14B SRTP session salt
41 val authKey: ByteArray, // 32B HMAC-SHA256 auth key
42 val ssrc: Int, // secure (non-negative) synchronization source id
43 )
44
45 /** Generate a fresh 32-byte call key. */
46 fun generateCallKey(): ByteArray = ByteArray(CALL_KEY_LEN).also { rng.nextBytes(it) }
47
48 /**
49 * Derive the media keys + secure SSRC for [callId] from [callKey]. Deterministic: the same
50 * (callKey, callId) always yields the same keys, so both peers agree.
51 */
52 fun deriveMediaKeys(callKey: ByteArray, callId: String): MediaKeys {
53 val salt = callId.toByteArray(Charsets.UTF_8)
54 val out = hkdfSha256(callKey, salt, INFO_MEDIA.toByteArray(Charsets.UTF_8), SRTP_KEY_LEN + SRTP_SALT_LEN)
55 val encKey = out.copyOfRange(0, SRTP_KEY_LEN)
56 val srtpSalt = out.copyOfRange(SRTP_KEY_LEN, SRTP_KEY_LEN + SRTP_SALT_LEN)
57 val authKey = hmacSha256(callKey, encKey + srtpSalt).copyOf(AUTH_KEY_LEN)
58 val ssrc = deriveSsrc(callKey, callId)
59 return MediaKeys(encKey, srtpSalt, authKey, ssrc)
60 }
61
62 /** Secure SSRC: top 31 bits of HMAC-SHA256(callKey, "…SSRC"||callId), always non-negative. */
63 fun deriveSsrc(callKey: ByteArray, callId: String): Int {
64 val mac = hmacSha256(callKey, (INFO_SSRC + callId).toByteArray(Charsets.UTF_8))
65 val raw = ByteBuffer.wrap(mac, 0, 4).int
66
67 return raw and INT_POSITIVE_MASK
68 }
69
70 /**
71 * Derive a new call key for a `call_rekey` identified by [rekeyId], chained from the previous
72 * [prevCallKey]. Distinct from the original key so a compromised prior key can't decrypt after
73 * rekey. Ref whatsapp-documentation.md `call_rekey`.
74 */
75 fun rekey(prevCallKey: ByteArray, rekeyId: String): ByteArray =
76 hkdfSha256(
77 prevCallKey,
78 rekeyId.toByteArray(Charsets.UTF_8),
79 INFO_REKEY.toByteArray(Charsets.UTF_8),
80 CALL_KEY_LEN)
81
82 // -- primitives --
83
84 fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray {
85 val mac = Mac.getInstance("HmacSHA256")
86 mac.init(SecretKeySpec(key, "HmacSHA256"))
87 return mac.doFinal(data)
88 }
89
90 /** HKDF-SHA256 (RFC 5869). null/empty salt = 32 zero bytes. */
91 fun hkdfSha256(ikm: ByteArray, salt: ByteArray?, info: ByteArray, length: Int): ByteArray {
92 val actualSalt = if (salt == null || salt.isEmpty()) ByteArray(32) else salt
93 val prk = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(actualSalt, "HmacSHA256")) }.doFinal(ikm)
94 val out = ByteArray(length)
95 var t = ByteArray(0)
96 var pos = 0
97 var counter = 1
98 while (pos < length) {
99 val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(prk, "HmacSHA256")) }
100 mac.update(t); mac.update(info); mac.update(counter.toByte())
101 t = mac.doFinal()
102 val n = minOf(t.size, length - pos)
103 System.arraycopy(t, 0, out, pos, n)
104 pos += n; counter++
105 }
106 return out
107 }
108}