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 / e2e / RustWhatsAppCrypto.kt

RustWhatsAppCrypto.kt182 lines · 7.3 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp.e2e
2
3import com.vayunmathur.library.log.NativeLoader
4
5
6/**
7 * JNI wrapper around `libwhatsapp_signal.so` (Rust crate `whatsapp_signal`).
8 * All methods are pure — Kotlin owns Room persistence and passes opaque blobs.
9 *
10 * The nativelib is loaded once; [isAvailable] is false when the `.so` is missing
11 * (e.g. on unsupported ABI) so callers can degrade gracefully.
12 */
13object RustWhatsAppCrypto {
14
15 private const val TAG = "RustWhatsAppCrypto"
16 private const val KEYPAIR_SIZE = 64
17 private const val PRIVATE_KEY_SIZE = 32
18 private const val ENCRYPT_PARTS = 3
19
20 val isAvailable: Boolean = NativeLoader.load("communicate_signal", TAG)
21 // -- Primitive key operations --
22
23 /**
24 * Generate a fresh X25519 key pair.
25 * @return 64 bytes: private(32) || public(32), or null.
26 */
27 @JvmStatic
28 external fun generateKeyPair(): ByteArray?
29
30 @JvmStatic
31 external fun publicFromPrivate(privateKey: ByteArray): ByteArray?
32
33 @JvmStatic
34 external fun x25519Agreement(privateKey: ByteArray, publicKey: ByteArray): ByteArray?
35
36 @JvmStatic
37 external fun sign(privateKey: ByteArray, message: ByteArray): ByteArray?
38
39 @JvmStatic
40 external fun verify(publicKey: ByteArray, message: ByteArray, signature: ByteArray): Boolean
41
42 // -- Session --
43
44 /**
45 * X3DH initiator: process a peer bundle.
46 *
47 * @param preKeyId -1 if no one-time prekey, else its id.
48 * @param preKeyPublic null / empty when absent, else 32 bytes.
49 * @return serialized SessionState bytes (Rust record version 1), or null on error.
50 */
51 @JvmStatic
52 external fun processPreKeyBundle(
53 localIdentityPrivate: ByteArray,
54 localIdentityPublic: ByteArray,
55 localRegistrationId: Int,
56 registrationId: Int,
57 preKeyId: Int,
58 preKeyPublic: ByteArray?,
59 signedPreKeyId: Int,
60 signedPreKeyPublic: ByteArray,
61 signedPreKeySignature: ByteArray,
62 identityKey: ByteArray,
63 ): ByteArray?
64
65 /**
66 * Encrypt with an existing session.
67 * @return Array[3] = [isPreKey(1 byte 0/1), ciphertextBody, newSessionBytes] or null.
68 */
69 @JvmStatic
70 external fun encrypt(sessionBytes: ByteArray, plaintext: ByteArray): Array<ByteArray>?
71
72 /**
73 * Decrypt a normal `msg`.
74 * @return Array[2] = [plaintext, newSessionBytes] or null.
75 */
76 @JvmStatic
77 external fun decryptMessage(sessionBytes: ByteArray, ciphertext: ByteArray): Array<ByteArray>?
78
79 /**
80 * Decrypt an inbound `pkmsg`: X3DH (Bob) + first Double-Ratchet message.
81 * @param oneTimePrivate null / empty if the bundle had no one-time prekey.
82 * @return Array[2] = [plaintext, newSessionBytes] or null.
83 */
84 @JvmStatic
85 external fun decryptPreKeyMessage(
86 localIdentityPrivate: ByteArray,
87 localIdentityPublic: ByteArray,
88 signedPreKeyPrivate: ByteArray,
89 oneTimePrivate: ByteArray?,
90 preKeyMessageBytes: ByteArray,
91 ): Array<ByteArray>?
92
93 // -- Group (Sender Keys) --
94
95 /** @return Array[2] = [stateBytes, skdmBytes] */
96 @JvmStatic
97 external fun createSenderKey(): Array<ByteArray>?
98
99 @JvmStatic
100 external fun processSenderKey(skdmBytes: ByteArray): ByteArray?
101
102 /** @return Array[2] = [ciphertext, newStateBytes] */
103 @JvmStatic
104 external fun encryptGroup(stateBytes: ByteArray, plaintext: ByteArray): Array<ByteArray>?
105
106 /** @return Array[2] = [plaintext, newStateBytes] */
107 @JvmStatic
108 external fun decryptGroup(stateBytes: ByteArray, ciphertext: ByteArray): Array<ByteArray>?
109
110 // -- Convenience helpers used by callers --
111
112 /** An E2E key pair from the Rust crypto core (Curve25519, split private/public). */
113 data class KeyPair(val privateKey: ByteArray, val publicKey: ByteArray)
114
115 fun generateKeyPairSplit(): KeyPair {
116 val blob = generateKeyPair() ?: throw IllegalStateException("Rust generateKeyPair returned null")
117 if (blob.size != KEYPAIR_SIZE) {
118 throw IllegalStateException("generateKeyPair expected 64 bytes, got ${blob.size}")
119 }
120 return KeyPair(
121 privateKey = blob.copyOfRange(0, PRIVATE_KEY_SIZE),
122 publicKey = blob.copyOfRange(PRIVATE_KEY_SIZE, KEYPAIR_SIZE),
123 )
124 }
125
126 /** The result of a Rust 1:1 encrypt: whether a pre-key message and the updated session record. */
127 data class EncryptResult(val isPreKey: Boolean, val body: ByteArray, val newSession: ByteArray)
128 fun encryptSplit(sessionBytes: ByteArray, plaintext: ByteArray): EncryptResult {
129 val out = encrypt(sessionBytes, plaintext) ?: throw IllegalStateException("Rust encrypt returned null")
130 if (out.size != ENCRYPT_PARTS) throw IllegalStateException("encrypt expected 3 parts, got ${out.size}")
131 return EncryptResult(
132 isPreKey = out[0].isNotEmpty() && out[0][0].toInt() != 0,
133 body = out[1],
134 newSession = out[2],
135 )
136 }
137
138 /** The result of a Rust 1:1 decrypt: plaintext and the updated session record. */
139 data class DecryptResult(val plaintext: ByteArray, val newSession: ByteArray)
140 fun decryptMessageSplit(sessionBytes: ByteArray, ciphertext: ByteArray): DecryptResult {
141 val out = decryptMessage(sessionBytes, ciphertext) ?: throw IllegalStateException("Rust decryptMessage null")
142 if (out.size != 2) throw IllegalStateException("decryptMessage expected 2 parts")
143 return DecryptResult(out[0], out[1])
144 }
145
146 fun decryptPreKeySplit(
147 localIdentityPrivate: ByteArray,
148 localIdentityPublic: ByteArray,
149 signedPreKeyPrivate: ByteArray,
150 oneTimePrivate: ByteArray?,
151 preKeyMessageBytes: ByteArray,
152 ): DecryptResult {
153 val out = decryptPreKeyMessage(
154 localIdentityPrivate, localIdentityPublic, signedPreKeyPrivate,
155 oneTimePrivate, preKeyMessageBytes,
156 ) ?: throw IllegalStateException("Rust decryptPreKeyMessage null")
157 if (out.size != 2) throw IllegalStateException("decryptPreKey expected 2 parts")
158 return DecryptResult(out[0], out[1])
159 }
160
161 /** A new group sender-key state plus its distribution message (SKDM). */
162 data class SenderKeyCreateResult(val state: ByteArray, val skdm: ByteArray)
163 fun createSenderKeySplit(): SenderKeyCreateResult {
164 val out = createSenderKey() ?: throw IllegalStateException("Rust createSenderKey null")
165 if (out.size != 2) throw IllegalStateException("createSenderKey expected 2 parts")
166 return SenderKeyCreateResult(out[0], out[1])
167 }
168
169 /** A group ciphertext plus the updated sender-key state. */
170 data class GroupCipherResult(val data: ByteArray, val newState: ByteArray)
171 fun encryptGroupSplit(stateBytes: ByteArray, plaintext: ByteArray): GroupCipherResult {
172 val out = encryptGroup(stateBytes, plaintext) ?: throw IllegalStateException("Rust encryptGroup null")
173 if (out.size != 2) throw IllegalStateException("encryptGroup expected 2 parts")
174 return GroupCipherResult(out[0], out[1])
175 }
176
177 fun decryptGroupSplit(stateBytes: ByteArray, ciphertext: ByteArray): GroupCipherResult {
178 val out = decryptGroup(stateBytes, ciphertext) ?: throw IllegalStateException("Rust decryptGroup null")
179 if (out.size != 2) throw IllegalStateException("decryptGroup expected 2 parts")
180 return GroupCipherResult(out[0], out[1])
181 }
182}