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

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / e2e / RustSignalCrypto.kt

RustSignalCrypto.kt175 lines · 7.9 KiBRaw
1package com.vayunmathur.communicate.data.signal.e2e
2
3import com.vayunmathur.library.log.NativeLoader
4
5
6/**
7 * JNI bridge to the Rust Signal crate + libsignal-android Java layer.
8 *
9 * The Signal protocol uses PQXDH (Kyber1024 + X3DH) and sealed sender.
10 * For the Kyber/Double Ratchet wire, we delegate to libsignal-android's
11 * Java API where possible (SessionBuilder, SessionCipher, GroupCipher,
12 * SealedSessionCipher). A small Rust fallback (communicate_signal crate)
13 * handles any gaps so the build stays compilable without extra Gradle deps.
14 *
15 * CIPHERTEXT_MESSAGE_CURRENT_VERSION = 4 (PQXDH); HKDF label
16 * "WhisperText_X25519_SHA-256_CRYSTALS-KYBER-1024" - see pqxdh.rs.
17 */
18object RustSignalCrypto {
19
20 private const val TAG = "RustSignalCrypto"
21 private const val KEYPAIR_SIZE = 64
22 private const val PRIVATE_KEY_SIZE = 32
23 private const val ENCRYPT_PARTS = 3
24
25 val isAvailable: Boolean = NativeLoader.load("communicate_signal", TAG)
26
27 // -- Primitive key operations (reused from crypto.rs) --
28
29 @JvmStatic external fun generateKeyPair(): ByteArray?
30 @JvmStatic external fun publicFromPrivate(privateKey: ByteArray): ByteArray?
31 @JvmStatic external fun x25519Agreement(privateKey: ByteArray, publicKey: ByteArray): ByteArray?
32 @JvmStatic external fun sign(privateKey: ByteArray, message: ByteArray): ByteArray?
33 @JvmStatic external fun verify(publicKey: ByteArray, message: ByteArray, signature: ByteArray): Boolean
34
35 // -- Session (PQXDH wire; version 4; Kyber fields) --
36
37 /**
38 * Process a PreKeyBundle that includes Kyber prekey.
39 * Wire: PreKeySignalMessage fields 7 (kyber_pre_key_id) + 8 (kyber_ciphertext 1568B)
40 * must be present together for version >= 4.
41 * HKDF label: "WhisperText_X25519_SHA-256_CRYSTALS-KYBER-1024" (pqxdh.rs:74)
42 */
43 @JvmStatic external fun processPreKeyBundle(
44 localIdentityPrivate: ByteArray,
45 localIdentityPublic: ByteArray,
46 localRegistrationId: Int,
47 registrationId: Int,
48 preKeyId: Int,
49 preKeyPublic: ByteArray?,
50 signedPreKeyId: Int,
51 signedPreKeyPublic: ByteArray,
52 signedPreKeySignature: ByteArray,
53 identityKey: ByteArray,
54 // PQXDH additions:
55 kyberPreKeyId: Int,
56 kyberPreKeyPublic: ByteArray, // 1569B = 0x08 || 1568 (tag intact)
57 kyberPreKeySignature: ByteArray, // XEdDSA over kyber pub serialize
58 kyberCiphertext: ByteArray,
59 // 1568B raw from encaps (server-provided or locally generated; 0x08 tag
60 // handled in Rust libsignal path; for stub keep as raw)
61 ): ByteArray?
62
63 /** Legacy overload without Kyber for incremental migration; delegates to above with empty Kyber. */
64 @JvmStatic @Deprecated("Use Kyber overload")
65 external fun processPreKeyBundleLegacy(
66 localIdentityPrivate: ByteArray,
67 localIdentityPublic: ByteArray,
68 localRegistrationId: Int,
69 registrationId: Int,
70 preKeyId: Int,
71 preKeyPublic: ByteArray?,
72 signedPreKeyId: Int,
73 signedPreKeyPublic: ByteArray,
74 signedPreKeySignature: ByteArray,
75 identityKey: ByteArray,
76 ): ByteArray?
77
78 @JvmStatic external fun encrypt(sessionBytes: ByteArray, plaintext: ByteArray): Array<ByteArray>?
79 @JvmStatic external fun decryptMessage(sessionBytes: ByteArray, ciphertext: ByteArray): Array<ByteArray>?
80 @JvmStatic external fun decryptPreKeyMessage(
81 localIdentityPrivate: ByteArray,
82 localIdentityPublic: ByteArray,
83 signedPreKeyPrivate: ByteArray,
84 oneTimePrivate: ByteArray?,
85 kyberSecretKey: ByteArray?, // 3169B or 3168B serialized KEM secret (with 0x08 tag if present)
86 preKeyMessageBytes: ByteArray,
87 ): Array<ByteArray>?
88
89 /**
90 * Replay guard for Kyber last-resort prekeys (storage/inmem.rs:200).
91 * One-time keys -> deleted after first use; last-resort keys -> (kyberId, signedEcId, baseKey) tuple dedup.
92 */
93 @JvmStatic external fun markKyberPreKeyUsed(
94 kyberPreKeyId: Int,
95 signedPreKeyId: Int,
96 baseKey: ByteArray,
97 ): Boolean
98
99 // -- Group (Sender Keys) --
100
101 @JvmStatic external fun createSenderKey(): Array<ByteArray>?
102 @JvmStatic external fun processSenderKey(skdmBytes: ByteArray): ByteArray?
103 @JvmStatic external fun encryptGroup(stateBytes: ByteArray, plaintext: ByteArray): Array<ByteArray>?
104 @JvmStatic external fun decryptGroup(stateBytes: ByteArray, ciphertext: ByteArray): Array<ByteArray>?
105
106 // -- Sealed sender (delegated to libsignal SealedSessionCipher; see SignalE2E.sealedSender*) --
107 // Kept for Kotlin callers that still go via JNI; the primary path in SignalE2E uses
108 // org.signal.libsignal.metadata.SealedSessionCipher directly with SenderCertificate.
109
110 /**
111 * Sealed-sender encrypt - real implementation requires a SenderCertificate
112 * fetched live from GET /v1/certificate/delivery and validated via CertificateValidator.
113 * This JNI stub is retained for tests; production calls SealedSessionCipher.encrypt().
114 */
115 @JvmStatic external fun sealedSenderEncrypt(
116 plaintext: ByteArray,
117 recipientAci: String,
118 recipientDeviceId: Int): ByteArray?
119 @JvmStatic external fun sealedSenderDecrypt(ciphertext: ByteArray): ByteArray?
120
121 // -- Convenience helpers --
122
123 /** An E2E key pair from the Rust crypto core (Curve25519, split private/public). */
124 data class KeyPair(val privateKey: ByteArray, val publicKey: ByteArray)
125
126 fun generateKeyPairSplit(): KeyPair {
127 val blob = generateKeyPair() ?: throw IllegalStateException("Rust generateKeyPair returned null")
128 if (blob.size != KEYPAIR_SIZE) {
129 throw IllegalStateException("generateKeyPair expected 64 bytes, got ${blob.size}")
130 }
131 return KeyPair(
132 blob.copyOfRange(0, PRIVATE_KEY_SIZE),
133 blob.copyOfRange(PRIVATE_KEY_SIZE, KEYPAIR_SIZE))
134 }
135
136 /** The result of a Rust 1:1 encrypt: whether a pre-key message and the updated session record. */
137 data class EncryptResult(val isPreKey: Boolean, val body: ByteArray, val newSession: ByteArray)
138 fun encryptSplit(sessionBytes: ByteArray, plaintext: ByteArray): EncryptResult {
139 val out = encrypt(sessionBytes, plaintext) ?: throw IllegalStateException("Rust encrypt returned null")
140 if (out.size != ENCRYPT_PARTS) throw IllegalStateException("encrypt expected 3 parts, got ${out.size}")
141 return EncryptResult(out[0].isNotEmpty() && out[0][0].toInt() != 0, out[1], out[2])
142 }
143
144 /** The result of a Rust 1:1 decrypt: plaintext and the updated session record. */
145 data class DecryptResult(val plaintext: ByteArray, val newSession: ByteArray)
146 fun decryptMessageSplit(sessionBytes: ByteArray, ciphertext: ByteArray): DecryptResult {
147 val out = decryptMessage(sessionBytes, ciphertext) ?: throw IllegalStateException("Rust decryptMessage null")
148 if (out.size != 2) throw IllegalStateException("decryptMessage expected 2 parts")
149 return DecryptResult(out[0], out[1])
150 }
151
152 fun decryptPreKeySplit(
153 localIdentityPrivate: ByteArray,
154 localIdentityPublic: ByteArray,
155 signedPreKeyPrivate: ByteArray,
156 oneTimePrivate: ByteArray?,
157 kyberSecretKey: ByteArray?,
158 preKeyMessageBytes: ByteArray,
159 ): DecryptResult {
160 val out = decryptPreKeyMessage(
161 localIdentityPrivate,
162 localIdentityPublic,
163 signedPreKeyPrivate,
164 oneTimePrivate,
165 kyberSecretKey,
166 preKeyMessageBytes)
167 ?: throw IllegalStateException("Rust decryptPreKeyMessage null")
168 if (out.size != 2) throw IllegalStateException("decryptPreKey expected 2 parts")
169 return DecryptResult(out[0], out[1])
170 }
171
172 // The sender-key wrappers that used to live here are gone: group traffic now goes through libsignal's
173 // GroupCipher/GroupSessionBuilder, which is the only format real Signal clients interoperate with, and
174 // which SealedSessionCipher already dispatches inbound SENDERKEY_TYPE through.
175}