Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppProtocolCrypto.kt
WhatsAppProtocolCrypto.kt310 lines · 12.4 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import java.nio.ByteBuffer |
| 5 | import java.security.SecureRandom |
| 6 | import javax.crypto.Cipher |
| 7 | import javax.crypto.Mac |
| 8 | import javax.crypto.spec.GCMParameterSpec |
| 9 | import javax.crypto.spec.IvParameterSpec |
| 10 | import javax.crypto.spec.SecretKeySpec |
| 11 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.MediaEncryptResult |
| 12 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.MediaKeys |
| 13 | |
| 14 | // -- Cryptography helpers: app-state, media, message-ID, padding, poll votes -- |
| 15 | // (Primitive helpers x25519 / hkdfSha256 / sha256 / hmacSha256 stay in |
| 16 | // WhatsAppProtocol.kt: NoiseHandshake depends on them as object members.) |
| 17 | |
| 18 | private const val APP_STATE_KEY_SIZE = 32 |
| 19 | private const val APP_STATE_EXPANDED_SIZE = 160 |
| 20 | private const val KEY_OFFSET_0 = 0 |
| 21 | private const val KEY_OFFSET_1 = APP_STATE_KEY_SIZE |
| 22 | private const val KEY_OFFSET_2 = APP_STATE_KEY_SIZE * 2 |
| 23 | private const val KEY_OFFSET_3 = APP_STATE_KEY_SIZE * 3 |
| 24 | private const val KEY_OFFSET_4 = APP_STATE_KEY_SIZE * 4 |
| 25 | private const val IV_SIZE = 16 |
| 26 | private const val VALUE_MAC_SIZE = 32 |
| 27 | private const val MEDIA_EXPANDED_SIZE = 112 |
| 28 | private const val CIPHER_KEY_SIZE = 32 |
| 29 | private const val MAC_KEY_SIZE = 32 |
| 30 | private const val REF_KEY_SIZE = 32 |
| 31 | private const val GCM_TAG_BITS = 128 |
| 32 | private const val PAD_BLOCK_SIZE = 16 |
| 33 | private const val TIMESTAMP_GRANULARITY_MS = 1000L |
| 34 | |
| 35 | /** |
| 36 | * Expand a 32-byte app-state sync key into the 5 sub-keys via HKDF-SHA256 with info |
| 37 | * "WhatsApp Mutation Keys" (160 bytes). Order: index, valueEncryption, valueMac, |
| 38 | * snapshotMac, patchMac. Ref whatsmeow appstate/keys.go expandAppStateKeys. |
| 39 | */ |
| 40 | fun WhatsAppProtocol.expandAppStateKeys(keyData: ByteArray): Array<ByteArray> { |
| 41 | val out = hkdfSha256(keyData, null, "WhatsApp Mutation Keys".toByteArray(Charsets.UTF_8), APP_STATE_EXPANDED_SIZE) |
| 42 | return arrayOf( |
| 43 | out.copyOfRange(KEY_OFFSET_0, KEY_OFFSET_1), |
| 44 | out.copyOfRange(KEY_OFFSET_1, KEY_OFFSET_2), |
| 45 | out.copyOfRange(KEY_OFFSET_2, KEY_OFFSET_3), |
| 46 | out.copyOfRange(KEY_OFFSET_3, KEY_OFFSET_4), |
| 47 | out.copyOfRange(KEY_OFFSET_4, APP_STATE_EXPANDED_SIZE), |
| 48 | ) |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Decrypt an app-state mutation/record value blob: [iv(16)][ciphertext][valueMac(32)] using |
| 53 | * the valueEncryption sub-key (AES-256-CBC). MAC is not verified. Ref whatsmeow decodeMutation. |
| 54 | */ |
| 55 | fun WhatsAppProtocol.decryptAppStateValue(valueBlob: ByteArray, valueEncryptionKey: ByteArray): ByteArray? { |
| 56 | if (valueBlob.size < IV_SIZE + VALUE_MAC_SIZE) return null |
| 57 | val content = valueBlob.copyOfRange(0, valueBlob.size - VALUE_MAC_SIZE) // strip 32-byte valueMac |
| 58 | val iv = content.copyOfRange(0, IV_SIZE) |
| 59 | val ciphertext = content.copyOfRange(IV_SIZE, content.size) |
| 60 | return try { |
| 61 | val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") |
| 62 | cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(valueEncryptionKey, "AES"), IvParameterSpec(iv)) |
| 63 | cipher.doFinal(ciphertext) |
| 64 | } catch (ignored: Exception) { |
| 65 | null |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Derive media encryption keys from a media key using HKDF. |
| 71 | * Returns (iv, cipherKey, macKey, refKey) — each used in media encrypt/decrypt. |
| 72 | * From whatsmeow/download.go getMediaKeys() |
| 73 | */ |
| 74 | fun WhatsAppProtocol.getMediaKeys(mediaKey: ByteArray, mediaType: String): MediaKeys { |
| 75 | val expanded = hkdfSha256(mediaKey, null, mediaType.toByteArray(Charsets.UTF_8), MEDIA_EXPANDED_SIZE) |
| 76 | return MediaKeys( |
| 77 | iv = expanded.copyOfRange(0, IV_SIZE), |
| 78 | cipherKey = expanded.copyOfRange(IV_SIZE, IV_SIZE + CIPHER_KEY_SIZE), |
| 79 | macKey = expanded.copyOfRange(IV_SIZE + CIPHER_KEY_SIZE, IV_SIZE + CIPHER_KEY_SIZE + MAC_KEY_SIZE), |
| 80 | refKey = expanded.copyOfRange( |
| 81 | IV_SIZE + CIPHER_KEY_SIZE + MAC_KEY_SIZE, |
| 82 | IV_SIZE + CIPHER_KEY_SIZE + MAC_KEY_SIZE + REF_KEY_SIZE) |
| 83 | ) |
| 84 | } |
| 85 | |
| 86 | /** |
| 87 | * Encrypt media using AES-256-CBC + HMAC-SHA256. |
| 88 | * From whatsmeow/upload.go Upload() |
| 89 | */ |
| 90 | fun WhatsAppProtocol.encryptMedia(plaintext: ByteArray, mediaType: String): MediaEncryptResult { |
| 91 | val random = SecureRandom() |
| 92 | val mediaKey = ByteArray(APP_STATE_KEY_SIZE).also { random.nextBytes(it) } |
| 93 | val keys = getMediaKeys(mediaKey, mediaType) |
| 94 | |
| 95 | val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") |
| 96 | val keySpec = SecretKeySpec(keys.cipherKey, "AES") |
| 97 | val ivSpec = IvParameterSpec(keys.iv) |
| 98 | cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec) |
| 99 | val ciphertext = cipher.doFinal(plaintext) |
| 100 | |
| 101 | val mac = Mac.getInstance("HmacSHA256") |
| 102 | mac.init(SecretKeySpec(keys.macKey, "HmacSHA256")) |
| 103 | mac.update(keys.iv) |
| 104 | mac.update(ciphertext) |
| 105 | val macValue = mac.doFinal() |
| 106 | |
| 107 | val dataToUpload = ciphertext + macValue.copyOfRange(0, 10) |
| 108 | val fileSha256 = sha256(plaintext) |
| 109 | val fileEncSha256 = sha256(dataToUpload) |
| 110 | |
| 111 | return MediaEncryptResult( |
| 112 | mediaKey = mediaKey, |
| 113 | encryptedData = dataToUpload, |
| 114 | fileSha256 = fileSha256, |
| 115 | fileEncSha256 = fileEncSha256, |
| 116 | fileLength = plaintext.size.toLong() |
| 117 | ) |
| 118 | } |
| 119 | |
| 120 | /** |
| 121 | * Decrypt downloaded media. |
| 122 | * From whatsmeow/download.go |
| 123 | */ |
| 124 | fun WhatsAppProtocol.decryptMedia(ciphertextWithMac: ByteArray, mediaKey: ByteArray, mediaType: String): ByteArray { |
| 125 | val keys = getMediaKeys(mediaKey, mediaType) |
| 126 | |
| 127 | val macOffset = ciphertextWithMac.size - 10 |
| 128 | val ciphertext = ciphertextWithMac.copyOfRange(0, macOffset) |
| 129 | |
| 130 | // Verify HMAC |
| 131 | val mac = Mac.getInstance("HmacSHA256") |
| 132 | mac.init(SecretKeySpec(keys.macKey, "HmacSHA256")) |
| 133 | mac.update(keys.iv) |
| 134 | mac.update(ciphertext) |
| 135 | val expectedMac = mac.doFinal().copyOfRange(0, 10) |
| 136 | val actualMac = ciphertextWithMac.copyOfRange(macOffset, ciphertextWithMac.size) |
| 137 | if (!expectedMac.contentEquals(actualMac)) { |
| 138 | throw SecurityException("Media HMAC verification failed") |
| 139 | } |
| 140 | |
| 141 | val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") |
| 142 | val keySpec = SecretKeySpec(keys.cipherKey, "AES") |
| 143 | val ivSpec = IvParameterSpec(keys.iv) |
| 144 | cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec) |
| 145 | return cipher.doFinal(ciphertext) |
| 146 | } |
| 147 | |
| 148 | // -- Message ID generation -- |
| 149 | |
| 150 | /** |
| 151 | * Generate a message ID: "3EB0" + uppercase hex of sha256(unixSeconds ++ [email protected] ++ random16)[:9]. |
| 152 | * From whatsmeow/send.go Client.GenerateMessageID(). |
| 153 | */ |
| 154 | fun WhatsAppProtocol.generateMessageId(ownJid: String?): String { |
| 155 | val buf = java.io.ByteArrayOutputStream() |
| 156 | val ts = ByteArray(8) |
| 157 | ByteBuffer.wrap(ts).putLong(System.currentTimeMillis() / TIMESTAMP_GRANULARITY_MS) |
| 158 | buf.write(ts) |
| 159 | if (!ownJid.isNullOrEmpty()) { |
| 160 | val user = ownJid.substringBefore('@').substringBefore(':') |
| 161 | buf.write(user.toByteArray(Charsets.UTF_8)) |
| 162 | buf.write("@c.us".toByteArray(Charsets.UTF_8)) |
| 163 | } |
| 164 | val rand = ByteArray(16) |
| 165 | SecureRandom().nextBytes(rand) |
| 166 | buf.write(rand) |
| 167 | val hash = sha256(buf.toByteArray()) |
| 168 | val hex = hash.copyOfRange(0, 9).joinToString("") { "%02X".format(it) } |
| 169 | return WEB_MESSAGE_ID_PREFIX + hex |
| 170 | } |
| 171 | |
| 172 | // -- Message padding (Signal Protocol requirement) -- |
| 173 | |
| 174 | /** |
| 175 | * Pad message with random 1-15 bytes where each pad byte equals the pad count. |
| 176 | * From whatsmeow/message.go padMessage(): random byte masked to 0x0f, 0 -> 15. |
| 177 | */ |
| 178 | fun WhatsAppProtocol.padMessage(plaintext: ByteArray): ByteArray { |
| 179 | var padSize = SecureRandom().nextInt(PAD_BLOCK_SIZE) |
| 180 | if (padSize == 0) padSize = PAD_BLOCK_SIZE - 1 |
| 181 | val padded = ByteArray(plaintext.size + padSize) |
| 182 | System.arraycopy(plaintext, 0, padded, 0, plaintext.size) |
| 183 | for (i in plaintext.size until padded.size) { |
| 184 | padded[i] = padSize.toByte() |
| 185 | } |
| 186 | return padded |
| 187 | } |
| 188 | |
| 189 | fun WhatsAppProtocol.unpadMessage(padded: ByteArray): ByteArray { |
| 190 | if (padded.isEmpty()) return padded |
| 191 | val padSize = padded.last().toInt() and 0xFF |
| 192 | if (padSize == 0 || padSize > padded.size) return padded |
| 193 | return padded.copyOfRange(0, padded.size - padSize) |
| 194 | } |
| 195 | |
| 196 | /** |
| 197 | * Build an encrypted poll vote (PollUpdateMessage) as a Message proto, routed through the |
| 198 | * normal send path. Selected options are SHA-256 hashes of the chosen option names; the vote |
| 199 | * payload is AES-256-GCM encrypted with a key derived from the poll's messageSecret. |
| 200 | * Ref whatsmeow msgsecret.go BuildPollVote / EncryptPollVote. |
| 201 | */ |
| 202 | fun WhatsAppProtocol.buildPollVoteMessage( |
| 203 | chatJid: String, |
| 204 | pollMessageId: String, |
| 205 | pollCreatorJid: String, |
| 206 | pollFromMe: Boolean, |
| 207 | voterJid: String, |
| 208 | optionHashes: List<ByteArray>, |
| 209 | pollSecret: ByteArray, |
| 210 | ): com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message { |
| 211 | val vote = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.PollVoteMessage.newBuilder() |
| 212 | optionHashes.forEach { vote.addSelectedOptions(com.google.protobuf.ByteString.copyFrom(it)) } |
| 213 | val plaintext = vote.build().toByteArray() |
| 214 | |
| 215 | val (key, aad) = pollVoteKeyAndAad(pollSecret, pollMessageId, pollCreatorJid, voterJid) |
| 216 | val iv = ByteArray(12).also { java.security.SecureRandom().nextBytes(it) } |
| 217 | val ciphertext = aesGcm(Cipher.ENCRYPT_MODE, key, iv, plaintext, aad) |
| 218 | |
| 219 | val msgKey = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.MessageKey.newBuilder() |
| 220 | .setFromMe(pollFromMe) |
| 221 | .setId(pollMessageId) |
| 222 | .setRemoteJid(chatJid) |
| 223 | if (!pollFromMe && chatJid.contains("@g.us") && pollCreatorJid.isNotEmpty()) { |
| 224 | msgKey.setParticipant(pollCreatorJid) |
| 225 | } |
| 226 | val update = com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.PollUpdateMessage.newBuilder() |
| 227 | .setPollCreationMessageKey(msgKey.build()) |
| 228 | .setVote( |
| 229 | com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.PollEncValue.newBuilder() |
| 230 | .setEncPayload(com.google.protobuf.ByteString.copyFrom(ciphertext)) |
| 231 | .setEncIV(com.google.protobuf.ByteString.copyFrom(iv)) |
| 232 | ) |
| 233 | .setSenderTimestampMS(System.currentTimeMillis()) |
| 234 | return com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message.newBuilder() |
| 235 | .setPollUpdateMessage(update.build()) |
| 236 | .build() |
| 237 | } |
| 238 | |
| 239 | /** |
| 240 | * Decrypt an incoming poll vote, returning the SHA-256 option hashes the voter selected (or |
| 241 | * null on failure). The caller maps hashes back to option names via the stored poll options. |
| 242 | */ |
| 243 | fun WhatsAppProtocol.decryptPollVote( |
| 244 | update: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.PollUpdateMessage, |
| 245 | pollMessageId: String, |
| 246 | pollCreatorJid: String, |
| 247 | voterJid: String, |
| 248 | pollSecret: ByteArray, |
| 249 | ): List<ByteArray>? { |
| 250 | return try { |
| 251 | val (key, aad) = pollVoteKeyAndAad(pollSecret, pollMessageId, pollCreatorJid, voterJid) |
| 252 | val plaintext = aesGcm( |
| 253 | Cipher.DECRYPT_MODE, key, |
| 254 | update.vote.encIV.toByteArray(), |
| 255 | update.vote.encPayload.toByteArray(), |
| 256 | aad, |
| 257 | ) |
| 258 | com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.PollVoteMessage |
| 259 | .parseFrom(plaintext) |
| 260 | .selectedOptionsList |
| 261 | .map { it.toByteArray() } |
| 262 | } catch (expected: Exception) { |
| 263 | Log.status(TAG, "Poll vote decrypt failed", expected) |
| 264 | null |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /** |
| 269 | * Derive the poll-vote key + GCM additional-data, matching whatsmeow generateMsgSecretKey for |
| 270 | * the "Poll Vote" use case: |
| 271 | * key = HKDF-SHA256(pollSecret, salt=nil, info = pollMsgId + creatorJid + voterJid + "Poll Vote") |
| 272 | * aad = pollMsgId + 0x00 + voterJid |
| 273 | * JIDs are normalized to bare user@server (no device/agent) to match the peer. |
| 274 | */ |
| 275 | private fun WhatsAppProtocol.pollVoteKeyAndAad( |
| 276 | pollSecret: ByteArray, |
| 277 | pollMessageId: String, |
| 278 | pollCreatorJid: String, |
| 279 | voterJid: String, |
| 280 | ): Pair<ByteArray, ByteArray> { |
| 281 | val creator = normalizeJidForSecret(pollCreatorJid) |
| 282 | val voter = normalizeJidForSecret(voterJid) |
| 283 | val info = pollMessageId.toByteArray(Charsets.UTF_8) + |
| 284 | creator.toByteArray(Charsets.UTF_8) + |
| 285 | voter.toByteArray(Charsets.UTF_8) + |
| 286 | "Poll Vote".toByteArray(Charsets.UTF_8) |
| 287 | val key = hkdfSha256(pollSecret, null, info, 32) |
| 288 | val aad = pollMessageId.toByteArray(Charsets.UTF_8) + |
| 289 | byteArrayOf(0) + |
| 290 | voter.toByteArray(Charsets.UTF_8) |
| 291 | return key to aad |
| 292 | } |
| 293 | |
| 294 | private fun WhatsAppProtocol.normalizeJidForSecret(jid: String): String { |
| 295 | val user = jid.substringBefore("@").substringBefore(":").substringBefore(".") |
| 296 | val server = jid.substringAfter("@", "s.whatsapp.net") |
| 297 | return "$user@$server" |
| 298 | } |
| 299 | |
| 300 | private fun WhatsAppProtocol.aesGcm( |
| 301 | mode: Int, |
| 302 | key: ByteArray, |
| 303 | iv: ByteArray, |
| 304 | data: ByteArray, |
| 305 | aad: ByteArray): ByteArray { |
| 306 | val cipher = Cipher.getInstance("AES/GCM/NoPadding") |
| 307 | cipher.init(mode, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv)) |
| 308 | cipher.updateAAD(aad) |
| 309 | return cipher.doFinal(data) |
| 310 | } |