Modern Apps git

← Modern-Apps.git

findfamily: add pqc support alongside existing rsa - pqc pair, register/getpair api, parallel publish/receive pairing with pqc-only routing when peer supports pqc

Commit
1495bbc0fc806d91275a2d3f3bb5491a3260fb18
Author
Vayun Mathur <[email protected]>
When
2026-07-29 16:15 UTC (4 months ago)
Parents
a60f128

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.ktindex c3b3e7af95..3807e0e052 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -97,7 +97,7 @@ interface TemporaryLinkDao {     suspend fun delete(value: TemporaryLink): Int } -@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 6, exportSchema = false)+@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 7, exportSchema = false) @TypeConverters(DefaultConverters::class) abstract class FFDatabase : RoomDatabase() {     abstract fun userDao(): UserDao@@ -124,6 +124,11 @@ abstract class FFDatabase : RoomDatabase() {             },             androidx.room.migration.Migration(5, 6) {                 it.execSQL("ALTER TABLE `User` ADD COLUMN `sharingAutoToggleAt` INTEGER")+            },+            androidx.room.migration.Migration(6, 7) {+                it.execSQL("ALTER TABLE `User` ADD COLUMN `pqcEncryptionKey` TEXT")+                it.execSQL("ALTER TABLE `TemporaryLink` ADD COLUMN `pqcPublicKey` TEXT")+                it.execSQL("ALTER TABLE `TemporaryLink` ADD COLUMN `pqcKey` TEXT")             }         )     }
findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.ktindex e859a370ed..fbc71dcc64 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt@@ -16,4 +16,8 @@ data class TemporaryLink(     val deleteAt: Instant,      @PrimaryKey(autoGenerate = true) override val id: Long = 0,+    /** PQC ephemeral public bundle (base64 [4B kemLen][kemPub][dsaPub]), nullable for migration. */+    val pqcPublicKey: String? = null,+    /** PQC ephemeral private bundle (base64 [4B kemLen][kemPriv][dsaPriv] — kemPriv = seed+expanded via BC compat), nullable. */+    val pqcKey: String? = null, ): DatabaseItem\ No newline at end of file
findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.ktindex ae1aee8ebb..dd48cf8a5c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt@@ -30,7 +30,9 @@ data class User(     /** Peer device platform (`"android"` or `"ios"`), learned from heartbeat payloads. Null until first heartbeat after both sides upgrade. */     val platform: String? = null,     /** When to auto-toggle sharing (flip sendingEnabled). Null means Never / disabled. Single field. */-    val sharingAutoToggleAt: Instant? = null+    val sharingAutoToggleAt: Instant? = null,+    /** Peer post-quantum public bundle (base64: [4B kemLen][kemPubDer][dsaPubDer]), nullable for backward compat. */+    val pqcEncryptionKey: String? = null ): DatabaseItem {     companion object {         val EMPTY = User(" ", null, "Unnamed Location", true, RequestStatus.MUTUAL_CONNECTION, Clock.System.now(), null)
findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.ktindex 7bef77fda0..7ca2b323cb 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt@@ -18,10 +18,10 @@ data class CreateLinkData(val name: String, val expiryMillis: Long)  /**  * Lets another app (e.g. the messages app) mint a FindFamily location-sharing- * link. Reuses FindFamily's temporary-link mechanism: generate an RSA keypair,- * persist a [TemporaryLink] (the background tracking service then publishes- * encrypted location for it until it expires), and return the same recipient- * URL the in-app copy button produces.+ * link. Reuses FindFamily's temporary-link mechanism: generate an RSA keypair+ * AND a PQC bundle, persist a [TemporaryLink] (the background tracking service+ * then publishes encrypted location for it until it expires), and return the+ * same recipient URL the in-app copy button produces. PQC included when available.  */ @OptIn(InternalSerializationApi::class) class CreateLinkIntent : AssistantIntent<CreateLinkData, String>(@@ -30,14 +30,18 @@ class CreateLinkIntent : AssistantIntent<CreateLinkData, String>( ) {     override suspend fun performCalculation(input: CreateLinkData): String {         val keypair = Networking.generateKeyPair()+        val pqcPair = runCatching { Networking.generatePqcKeyPair() }.getOrNull()         val link = TemporaryLink(-            input.name,-            Base64.encode(keypair.privateKeyPem),-            Base64.encode(keypair.publicKeyPem),-            Clock.System.now() + input.expiryMillis.milliseconds,+            name = input.name,+            key = Base64.encode(keypair.privateKeyPem),+            publicKey = Base64.encode(keypair.publicKeyPem),+            deleteAt = Clock.System.now() + input.expiryMillis.milliseconds,+            pqcPublicKey = pqcPair?.publicBundleB64,+            pqcKey = pqcPair?.privateBundleB64,         )         val id = buildDatabase<FFDatabase>().temporaryLinkDao().upsert(link)         // Must match the URL format produced by TemporaryLinkCard in MainPage.-        return "https://findfamily.cc/view/$id#key=${link.key}"+        val base = "https://findfamily.cc/view/$id#key=${link.key}"+        return if (link.pqcKey != null) "$base&pqc_key=${link.pqcKey}" else base     } }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex 58ccde2d3d..1e3badced7 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -632,7 +632,12 @@ fun TemporaryLinkCard(platform: Platform, ffViewModel: FindFamilyViewModel, temp             trailingContent = {                 Row {                     IconButton({-                        platform.copy("https://findfamily.cc/view/${temporaryLink.id}#key=${temporaryLink.key}")+                        // PQC routing: if this link has a PQC key, include it in the fragment so a+                        // PQC-capable viewer can decrypt via post-quantum path. The fragment never+                        // hits the server; classic `#key=` still present for backward compat.+                        val base = "https://findfamily.cc/view/${temporaryLink.id}#key=${temporaryLink.key}"+                        val url = if (temporaryLink.pqcKey != null) "$base&pqc_key=${temporaryLink.pqcKey}" else base+                        platform.copy(url)                     }) {                         IconCopy()                     }
findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.ktindex a4d736ddde..638fd67156 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt@@ -401,17 +401,22 @@ class FindFamilyViewModel(     // ------------------------------------------------------------------      /**-     * Generate an RSA key pair and persist a [TemporaryLink] for sharing.+     * Generate an RSA key pair AND a PQC bundle (ML-KEM+ML-DSA) and persist a [TemporaryLink] for sharing.+     * Uses the same Pqc key generation as Office (same library, same DER compatibility).      * Calls [onDone] on the main thread once the upsert completes.      */     fun createTemporaryLink(name: String, expiry: Duration, onDone: () -> Unit = {}) {         viewModelScope.launch(Dispatchers.IO) {-            val keypair = Networking.generateKeyPair()+            val rsaPair = Networking.generateKeyPair()+            // PQC ephemeral — best effort, may fail if native lib unavailable (fallback to RSA-only link).+            val pqcPair = runCatching { Networking.generatePqcKeyPair() }.getOrNull()             val newLink = TemporaryLink(-                name,-                Base64.encode(keypair.privateKeyPem),-                Base64.encode(keypair.publicKeyPem),-                Clock.System.now() + expiry,+                name = name,+                key = Base64.encode(rsaPair.privateKeyPem),+                publicKey = Base64.encode(rsaPair.publicKeyPem),+                deleteAt = Clock.System.now() + expiry,+                pqcPublicKey = pqcPair?.publicBundleB64,+                pqcKey = pqcPair?.privateBundleB64,             )             temporaryLinkDao.upsert(newLink)             withContext(Dispatchers.Main) { onDone() }
findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.ktindex 67a6d59ab4..858d3f51ce 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -10,6 +10,8 @@ import com.vayunmathur.findfamily.uwb.UwbEnvelope import com.vayunmathur.e2ee.E2ee import com.vayunmathur.e2ee.E2eeIdentity import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.e2ee.PqcIdentity import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.CancellationException@@ -31,6 +33,19 @@ object Networking {      /** Shared end-to-end-encryption identity (key generation/storage/crypto lives in :library:e2ee-p2p). */     private lateinit var identity: E2eeIdentity+    /**+     * Post-quantum identity — mirrors Office's `PqcIdentity.loadOrCreate` pattern.+     * Reuses the exact same library (`e2ee-p2p`) and store abstraction, but uses+     * a distinct DataStore prefix `ff_pqc` so FindFamily PQC keys don't collide+     * with Office's `office` prefix nor with classic RSA keys (`publicKey`/`privateKey`).+     *+     * Bundle format is identical to Office: [4B kemLen BE][kemPubDer][dsaPubDer],+     * encrypt layout [4B encapLen][encap][aesGCM] with SP800-56A KDF SHA256(BE32(1)||Z),+     * so iOS must implement the same framing to interoperate.+     */+    private lateinit var pqcIdentity: PqcIdentity+    @Volatile private var pqcReady = false+    @Volatile private var pqcInitAttempted = false     private var network_is_down = false      var userid = 0L@@ -59,11 +74,24 @@ object Networking {             if (initialized) return             Networking.dataStoreUtils = dataStoreUtils             Networking.userDao = userDao-            // Loads the persisted keypair (or generates+stores one on first launch) using the same+            // Loads the persisted RSA keypair (or generates+stores one on first launch) using the same             // "publicKey"/"privateKey" datastore entries as before, so existing installs keep their key.             // Uses suspend DataStore hydration (getByteArrayAwait) to avoid the cold-start race where             // state.value is still emptyPreferences() → ephemeral identity → OAEP_DECODING_ERROR.             identity = E2eeIdentity.loadOrCreate(DataStoreKeyStore(dataStoreUtils))+            // PQC identity — same library as Office, distinct prefix so FF PQC keys are independent.+            // Wrapped in try/catch so devices where libe2ee_pqc.so fails to load still work with RSA only.+            if (!pqcInitAttempted) {+                pqcInitAttempted = true+                try {+                    pqcIdentity = PqcIdentity.loadOrCreate(DataStoreKeyStore(dataStoreUtils), "ff_pqc")+                    pqcReady = true+                    Log.d(TAG, "PQC identity ready bundleLen=${pqcIdentity.publicBundle.size}")+                } catch (e: Throwable) {+                    Log.w(TAG, "PQC identity unavailable (native lib load failed), falling back to RSA only", e)+                    pqcReady = false+                }+            }             // Avoid negative IDs: server stores ULong but receive uses Long in request; generating             // only positive IDs keeps both sides consistent and makes Base26 encoding stable.             if (dataStoreUtils.getLongAwait("userid") == null) {@@ -141,6 +169,19 @@ object Networking {         return ok     } +    private suspend fun registerPqc(): Boolean {+        if (!pqcReady) return false+        @Serializable+        data class Register(val userid: ULong, val key: String)+        val ok = makeRequest<Boolean, Register>("/api/pqc/register", Register(+            userid.toULong(),+            Base64.encode(pqcIdentity.publicBundle)+        )+        ) ?: false+        Log.d(TAG, "registerPqc userid=${userid.toULong()} ok=$ok bundleLen=${pqcIdentity.publicBundle.size}")+        return ok+    }+     suspend fun ensureUserExists() {         val selfKey = getKey(userid)         if(selfKey == null) {@@ -159,6 +200,23 @@ object Networking {                 Log.d(TAG, "ensureUserExists: self key exists and matches")             }         }+        // PQC self-healing: same race detection for the PQC bundle.+        if (pqcReady) {+            val selfPqcKey = getPqcKey(userid)+            if (selfPqcKey == null) {+                Log.w(TAG, "ensureUserExists: PQC getKey failed for self ${userid.toULong()}, re-registering PQC")+                registerPqc()+            } else {+                val localB64 = Base64.encode(pqcIdentity.publicBundle)+                val serverB64 = Base64.encode(selfPqcKey)+                if (localB64 != serverB64) {+                    Log.w(TAG, "ensureUserExists: PQC server mismatch self ${userid.toULong()}, re-registering len local=${localB64.length} server=${serverB64.length}")+                    registerPqc()+                } else {+                    Log.d(TAG, "ensureUserExists: PQC self key matches")+                }+            }+        }     }      /** Fetches a peer's public key by id, returning its PEM bytes (or null if unknown/offline). */@@ -180,10 +238,54 @@ object Networking {         return result     } +    /** Fetches a peer's PQC public bundle by id, returning its raw bundle bytes (or null). Same key normalization as classic. */+    private suspend fun getPqcKey(userid: Long): ByteArray? {+        if (!pqcReady) return null+        val result = checkNetworkDown {+            val response = NetworkClient.performRequest(+                url = "$URL/api/pqc/getkey",+                method = "POST",+                headers = mapOf("Content-Type" to "application/json"),+                body = json.encodeToString(GetKeyRequest(userid.toULong()))+            )+            Log.d(TAG, "getPqcKey id=${userid.toULong()} status=${response.status}")+            if (response.status != 200) return@checkNetworkDown null+            return@checkNetworkDown Base64.decode(response.body)+        }+        // Don't spam warn for users who haven't upgraded to PQC yet.+        if (result == null) Log.d(TAG, "getPqcKey: no PQC key for ${userid.toULong()} (peer may not support PQC yet)")+        return result+    }+     /** Local platform tag included in outgoing heartbeat payloads so the peer learns we're on Android. */     private const val PLATFORM = "android" +    /**+     * Publish location to a connected user.+     * PQC routing: if the peer has a PQC bundle (cached `User.pqcEncryptionKey` or fetched+     * from `/api/pqc/getkey`), encrypt + publish ONLY to the higher PQC endpoint+     * (`/api/location/publish_pqc`). Otherwise fall back to classic RSA endpoint.+     */     suspend fun publishLocation(location: LocationValue, user: User): Boolean {+        // Fast-path: check PQC capability first. The peer's PQC bundle is stored in+        // `pqcEncryptionKey` (base64 bundle). If present, we skip classic entirely.+        val pqcBundle = peerPqcBundle(user)+        if (pqcBundle != null) {+            return try {+                val encrypted = encryptLocationPqc(location, user.id, pqcBundle)+                val ok = makeRequest<Boolean, LocationSharingData>("/api/location/publish_pqc", encrypted) ?: false+                Log.d(TAG, "publishLocation PQC to ${user.id.toULong()} (${user.name}) ok=$ok encLen=${encrypted.encryptedLocation.length}")+                ok+            } catch (e: Exception) {+                Log.w(TAG, "publishLocation PQC to ${user.id.toULong()} exception, falling back to RSA", e)+                // Fallback to RSA on PQC encrypt failure.+                publishLocationClassic(location, user)+            }+        }+        return publishLocationClassic(location, user)+    }++    private suspend fun publishLocationClassic(location: LocationValue, user: User): Boolean {         val keyPem = if (user.encryptionKey != null) {             Base64.decode(user.encryptionKey)         } else {@@ -198,28 +300,62 @@ object Networking {         return try {             val encrypted = encryptLocation(location, user.id, keyPem)             val ok = makeRequest<Boolean, LocationSharingData>("/api/location/publish", encrypted) ?: false-            Log.d(TAG, "publishLocation to ${user.id.toULong()} (${user.name}) ok=$ok coord=${location.coord.lat},${location.coord.lon} encLen=${encrypted.encryptedLocation.length}")+            Log.d(TAG, "publishLocation RSA to ${user.id.toULong()} (${user.name}) ok=$ok encLen=${encrypted.encryptedLocation.length}")             ok         } catch (e: Exception) {-            Log.w(TAG, "publishLocation to ${user.id.toULong()} failed with exception", e)+            Log.w(TAG, "publishLocation RSA to ${user.id.toULong()} exception", e)             false         }     }      suspend fun publishLocation(location: LocationValue, user: TemporaryLink): Boolean {+        // TemporaryLink PQC: if pqcPublicKey present, publish to PQC endpoint only.+        if (user.pqcPublicKey != null) {+            return try {+                val bundle = Base64.decode(user.pqcPublicKey)+                val encrypted = encryptLocationPqc(location, user.id, bundle)+                val ok = makeRequest<Boolean, LocationSharingData>("/api/location/publish_pqc", encrypted) ?: false+                Log.d(TAG, "publishLocation PQC to temp link ${user.id} ok=$ok encLen=${encrypted.encryptedLocation.length}")+                ok+            } catch (e: Exception) {+                Log.w(TAG, "publishLocation PQC temp link ${user.id} exception, fallback RSA", e)+                publishLocationClassic(location, user)+            }+        }+        return publishLocationClassic(location, user)+    }++    private suspend fun publishLocationClassic(location: LocationValue, link: TemporaryLink): Boolean {         return try {-            val keyPem = Base64.decode(user.publicKey)-            val encrypted = encryptLocation(location, user.id, keyPem)+            val keyPem = Base64.decode(link.publicKey)+            val encrypted = encryptLocation(location, link.id, keyPem)             val ok = makeRequest<Boolean, LocationSharingData>("/api/location/publish", encrypted) ?: false-            Log.d(TAG, "publishLocation to temp link ${user.id} ok=$ok encLen=${encrypted.encryptedLocation.length}")+            Log.d(TAG, "publishLocation RSA to temp link ${link.id} ok=$ok encLen=${encrypted.encryptedLocation.length}")             ok         } catch (e: Exception) {-            Log.w(TAG, "publishLocation temp link ${user.id} exception", e)+            Log.w(TAG, "publishLocation RSA temp link ${link.id} exception", e)             false         }     } +    /**+     * Receives locations from both classic and PQC queues and merges them.+     * Classic queue may be empty when all peers upgraded to PQC; PQC queue is drained+     * here too for backward compat during rollout.+     */     suspend fun receiveLocations(): List<LocationValue>? {+        val classic = receiveLocationsClassic()+        val pqc = receiveLocationsPqc()+        // One null means network failure — if either failed we can't tell whether the other+        // is authoritative empty or partial. Return classic if pqc is null and vice versa,+        // but if classic is null return pqc (or null if both). This keeps heartbeat alive.+        if (classic == null && pqc == null) return null+        val merged = (classic ?: emptyList()) + (pqc ?: emptyList())+        Log.d(TAG, "receiveLocations merged total=${merged.size} classic=${classic?.size} pqc=${pqc?.size}")+        return merged+    }++    private suspend fun receiveLocationsClassic(): List<LocationValue>? {         // Use raw performRequest to correctly handle 204 No Content (empty queue) vs parsing error.         val response = try {             NetworkClient.performRequest(@@ -229,35 +365,33 @@ object Networking {                 body = json.encodeToString(UserIdRequest(userid.toULong()))             )         } catch (e: CancellationException) { throw e } catch (e: Exception) {-            Log.w(TAG, "receiveLocations: performRequest threw", e)+            Log.w(TAG, "receiveLocationsClassic: performRequest threw", e)             return null         }-        Log.d(TAG, "receiveLocations: status=${response.status} bodyLen=${response.body.length} for self ${userid.toULong()}")+        Log.d(TAG, "receiveLocationsClassic: status=${response.status} bodyLen=${response.body.length} for self ${userid.toULong()}")         if (response.status == 204 || response.body.isBlank()) {-            Log.d(TAG, "receiveLocations: 204/empty, no pending")+            Log.d(TAG, "receiveLocationsClassic: 204/empty")             return emptyList()         }         if (response.status !in 200..299) {-            Log.w(TAG, "receiveLocations: server status ${response.status} body=${response.body.take(500)}")+            Log.w(TAG, "receiveLocationsClassic: server status ${response.status} body=${response.body.take(500)}")             return null         }         val strings: List<String> = try {             json.decodeFromString(response.body)         } catch (e: Exception) {-            Log.w(TAG, "receiveLocations: failed to parse body ${response.body.take(500)}", e)+            Log.w(TAG, "receiveLocationsClassic: parse fail ${response.body.take(500)}", e)             return null         }-        Log.d(TAG, "receiveLocations: got ${strings.size} raw blobs for self ${userid.toULong()}")-        // Per-message resilience: a single stale / undecryptable entry (e.g. encrypted to an old-        // rotated key) must not crash the heartbeat. Skip bad entries instead.+        Log.d(TAG, "receiveLocationsClassic: got ${strings.size} raw blobs")         var decryptFails = 0         val decoded = strings.mapNotNull { enc ->             runCatching { decryptLocation(enc) }.onFailure { e ->                 decryptFails++-                Log.w(TAG, "receiveLocations: decrypt failed (skipping) encLen=${enc.length}", e)+                Log.w(TAG, "receiveLocationsClassic: decrypt fail encLen=${enc.length}", e)             }.getOrNull()         }-        if (decryptFails > 0) Log.w(TAG, "receiveLocations: $decryptFails / ${strings.size} failed to decrypt")+        if (decryptFails > 0) Log.w(TAG, "receiveLocationsClassic: $decryptFails / ${strings.size} decrypt fail")         if (decoded.isNotEmpty()) {             decoded.forEach { (loc, platform) ->                 if (platform != null) {@@ -268,7 +402,53 @@ object Networking {                 }             }         }-        Log.d(TAG, "receiveLocations: returning ${decoded.size} after decrypt")+        Log.d(TAG, "receiveLocationsClassic: returning ${decoded.size}")+        return decoded.map { it.first }+    }++    private suspend fun receiveLocationsPqc(): List<LocationValue>? {+        if (!pqcReady) return emptyList()+        val response = try {+            NetworkClient.performRequest(+                url = "$URL/api/location/receive_pqc",+                method = "POST",+                headers = mapOf("Content-Type" to "application/json"),+                body = json.encodeToString(UserIdRequest(userid.toULong()))+            )+        } catch (e: CancellationException) { throw e } catch (e: Exception) {+            Log.w(TAG, "receiveLocationsPqc: performRequest threw", e)+            return null+        }+        Log.d(TAG, "receiveLocationsPqc: status=${response.status} bodyLen=${response.body.length} for self ${userid.toULong()}")+        if (response.status == 204 || response.body.isBlank()) return emptyList()+        if (response.status !in 200..299) {+            Log.w(TAG, "receiveLocationsPqc: server status ${response.status} body=${response.body.take(500)}")+            return null+        }+        val strings: List<String> = try {+            json.decodeFromString(response.body)+        } catch (e: Exception) {+            Log.w(TAG, "receiveLocationsPqc: parse fail", e)+            return null+        }+        Log.d(TAG, "receiveLocationsPqc: got ${strings.size} raw blobs")+        var fails = 0+        val decoded = strings.mapNotNull { enc ->+            runCatching { decryptLocationPqc(enc) }.onFailure { e ->+                fails+++                Log.w(TAG, "receiveLocationsPqc: decrypt fail encLen=${enc.length}", e)+            }.getOrNull()+        }+        if (fails > 0) Log.w(TAG, "receiveLocationsPqc: $fails / ${strings.size} decrypt fail")+        decoded.forEach { (loc, platform) ->+            if (platform != null) {+                runCatching {+                    val u = userDao.getById(loc.userid)+                    if (u != null && u.platform != platform) userDao.upsert(u.copy(platform = platform))+                }+            }+        }+        Log.d(TAG, "receiveLocationsPqc: returning ${decoded.size}")         return decoded.map { it.first }     } @@ -278,24 +458,32 @@ object Networking {     // Mirrors the location publish/receive flow but carries the small UWB     // handshake envelopes (request / ack / config / cancel) end-to-end     // encrypted. Each payload is at most a few hundred bytes; ranging samples-    // themselves never touch the server.+    // themselves never touch the server. PQC routing: only bother publishing+    // to the higher PQC endpoint when peer supports it.     // ----------------------------------------------------------------      suspend fun publishUwbMessage(envelope: UwbEnvelope, recipientUserId: Long, recipient: User? = null): Boolean {+        // Try PQC first if peer has bundle.+        val resolvedUser = recipient ?: userDao.getById(recipientUserId)+        val pqcBundle = resolvedUser?.let { peerPqcBundle(it) } ?: getPqcKey(recipientUserId)+        if (pqcBundle != null) {+            // Cache bundle if we just fetched.+            if (resolvedUser != null && resolvedUser.pqcEncryptionKey == null) {+                runCatching { userDao.upsert(resolvedUser.copy(pqcEncryptionKey = Base64.encode(pqcBundle))) }+            }+            return publishUwbMessagePqc(envelope, recipientUserId, pqcBundle)+        }+        return publishUwbMessageClassic(envelope, recipientUserId, resolvedUser)+    }++    private suspend fun publishUwbMessageClassic(envelope: UwbEnvelope, recipientUserId: Long, recipient: User? = null): Boolean {         val keyPem = if (recipient?.encryptionKey != null) {             Base64.decode(recipient.encryptionKey)         } else {             getKey(recipientUserId) ?: return false         }         val str = json.encodeToString(envelope)-        // Use hybrid sealTo (AES+GCM payload + RSA-wrapped key) so we never hit the-        // 126-byte RSA-OAEP-SHA512 limit that silently broke larger UWB payloads.         val encryptedData = Base64.encode(E2ee.sealTo(keyPem, str.encodeToByteArray()))-        // We can't reuse `makeRequest<Boolean, ...>` here because the server-        // returns `204 No Content` (no body) on success, and Ktor's content-        // negotiation throws `NoTransformationFoundException` trying to-        // deserialize an empty body into a `Boolean`. `performRequest` returns-        // the raw response and we treat any 2xx status as success.         val bodyJson = json.encodeToString(LocationSharingData(recipientUserId.toULong(), encryptedData))         return checkNetworkDown {             val resp = NetworkClient.performRequest(@@ -308,23 +496,66 @@ object Networking {         } ?: false     } +    private suspend fun publishUwbMessagePqc(envelope: UwbEnvelope, recipientUserId: Long, bundle: ByteArray): Boolean {+        return try {+            val str = json.encodeToString(envelope)+            val encryptedData = Base64.encode(Pqc.encryptTo(bundle, str.encodeToByteArray()))+            val bodyJson = json.encodeToString(LocationSharingData(recipientUserId.toULong(), encryptedData))+            checkNetworkDown {+                val resp = NetworkClient.performRequest(+                    url = "$URL/api/uwb/publish_pqc",+                    method = "POST",+                    headers = mapOf("Content-Type" to "application/json"),+                    body = bodyJson+                )+                resp.status in 200..299+            } ?: false+        } catch (e: Exception) {+            Log.w(TAG, "publishUwbMessagePqc to ${recipientUserId.toULong()} failed", e)+            false+        }+    }+     /**-     * Drains incoming UWB envelopes addressed to this user. The server queue-     * is cleared on receive (same semantics as `/api/location/receive`).-     * Supports both hybrid (sealTo) and legacy direct RSA for backward compat.+     * Drains incoming UWB envelopes from both classic and PQC queues.+     * Supports both hybrid (sealTo) and legacy direct RSA for classic, and PQC bundle decrypt for PQC.      */     suspend fun receiveUwbMessages(): List<UwbEnvelope>? {+        val classic = receiveUwbMessagesClassic()+        val pqc = receiveUwbMessagesPqc()+        if (classic == null && pqc == null) return null+        return (classic ?: emptyList()) + (pqc ?: emptyList())+    }++    private suspend fun receiveUwbMessagesClassic(): List<UwbEnvelope>? {         val strings: List<String>? = makeRequest("/api/uwb/receive", json.encodeToString(UserIdRequest(userid.toULong())))         return strings?.mapNotNull { b64 ->             runCatching {                 val raw = Base64.decode(b64)-                // Try hybrid unseal first (new), fallback to direct decrypt (old peers).                 val plainBytes = runCatching { identity.unseal(raw) }.getOrElse { identity.decrypt(raw) }                 json.decodeFromString<UwbEnvelope>(plainBytes.decodeToString())             }.getOrNull()         }     } +    private suspend fun receiveUwbMessagesPqc(): List<UwbEnvelope>? {+        if (!pqcReady) return emptyList()+        val strings: List<String>? = makeRequest("/api/uwb/receive_pqc", json.encodeToString(UserIdRequest(userid.toULong())))+        return strings?.mapNotNull { b64 ->+            runCatching {+                val raw = Base64.decode(b64)+                val plainBytes = pqcIdentity.decrypt(raw)+                json.decodeFromString<UwbEnvelope>(plainBytes.decodeToString())+            }.onFailure { e ->+                Log.w(TAG, "receiveUwbMessagesPqc: decrypt fail", e)+            }.getOrNull()+        }+    }++    // ----------------------------------------------------------------+    // Encryption helpers+    // ----------------------------------------------------------------+     private suspend fun encryptLocation(location: LocationValue, recipientUserID: Long, keyPem: ByteArray): LocationSharingData {         val str = json.encodeToString(location.toCompatible(senderPlatform = PLATFORM))         // Hybrid encryption: avoids 126-byte RSA-OAEP limit; location JSON is ~150-250 bytes.@@ -332,6 +563,14 @@ object Networking {         return LocationSharingData(recipientUserID.toULong(), encryptedData)     } +    private fun encryptLocationPqc(location: LocationValue, recipientUserID: Long, bundle: ByteArray): LocationSharingData {+        val str = json.encodeToString(location.toCompatible(senderPlatform = PLATFORM))+        // PQC hybrid: ML-KEM encapsulate → AES-256-GCM, layout [4B encapLen][encap][aes].+        val sealed = Pqc.encryptTo(bundle, str.encodeToByteArray())+        val encryptedData = Base64.encode(sealed)+        return LocationSharingData(recipientUserID.toULong(), encryptedData)+    }+     private suspend fun decryptLocation(encryptedLocation: String): Pair<LocationValue, String?> {         val raw = Base64.decode(encryptedLocation)         // Backward compat: try unseal (new encrypted form) then direct decrypt (legacy peers).@@ -341,19 +580,65 @@ object Networking {         return compat.toLocationValue() to compat.senderPlatform     } -    /** Generates a fresh keypair (used for anonymous temporary share links). PEM bytes. */+    private fun decryptLocationPqc(encryptedLocation: String): Pair<LocationValue, String?> {+        val raw = Base64.decode(encryptedLocation)+        val plainBytes = pqcIdentity.decrypt(raw)+        val compat = json.decodeFromString<LocationValueCompatible>(plainBytes.decodeToString())+        return compat.toLocationValue() to compat.senderPlatform+    }++    /** Generates a fresh RSA keypair (used for anonymous temporary share links). PEM bytes. */     suspend fun generateKeyPair(): E2ee.KeyPairPem = E2ee.generateKeyPair() +    /**+     * Generates a fresh PQC key bundle for an ephemeral temporary link.+     * Returns (publicBundleBase64, privateBundleBase64) where private bundle is+     * [4B kemPrivLen][kemPrivDer][dsaPrivDer] — DERs, BC-compatible, same KDF as Office.+     * This mirrors Office's generation but for anonymous links.+     */+    fun generatePqcKeyPair(): PqcLinkKeyPair {+        val (kemPub, kemPriv) = Pqc.generateKem()+        val (dsaPub, dsaPriv) = Pqc.generateDsa()+        val pubBundle = Pqc.bundle(kemPub, dsaPub)+        val privBundle = buildPrivBundle(kemPriv, dsaPriv)+        return PqcLinkKeyPair(+            publicBundleB64 = Base64.encode(pubBundle),+            privateBundleB64 = Base64.encode(privBundle)+        )+    }++    data class PqcLinkKeyPair(val publicBundleB64: String, val privateBundleB64: String)++    /** Private bundle layout: [4B kemPrivLen BE][kemPriv][dsaPriv] — mirrors public bundle. */+    private fun buildPrivBundle(kemPriv: ByteArray, dsaPriv: ByteArray): ByteArray {+        val out = ByteArray(4 + kemPriv.size + dsaPriv.size)+        out[0] = (kemPriv.size ushr 24).toByte()+        out[1] = (kemPriv.size ushr 16).toByte()+        out[2] = (kemPriv.size ushr 8).toByte()+        out[3] = kemPriv.size.toByte()+        kemPriv.copyInto(out, 4)+        dsaPriv.copyInto(out, 4 + kemPriv.size)+        return out+    }+     /**      * Computes the verification "security code" for a connection: a fingerprint of *both* this      * device's and [user]'s public keys. Identical on both peers' devices; comparing them confirms      * the end-to-end channel isn't being intercepted. Returns null if the peer's key isn't known yet.+     * Uses RSA keys (existing behavior).      */     suspend fun securityCode(user: User): String? {         val theirPem = peerPublicKeyPem(user) ?: return null         return runCatching { E2ee.securityCode(identity.publicKeyPem, theirPem) }.getOrNull()     } +    /** PQC safety number — same contract as classic but from PQC bundles. */+    fun securityCodePqc(user: User): String? {+        val theirBundle = user.pqcEncryptionKey?.let { Base64.decode(it) } ?: return null+        if (!pqcReady) return null+        return runCatching { Pqc.securityCode(pqcIdentity.publicBundle, theirBundle) }.getOrNull()+    }+     /** The peer's public key as PEM bytes — from the cached [User.encryptionKey] or fetched by id. */     private suspend fun peerPublicKeyPem(user: User): ByteArray? {         user.encryptionKey?.let { return Base64.decode(it) }@@ -362,6 +647,30 @@ object Networking {         return pem     } +    /**+     * The peer's PQC public bundle — from cached `User.pqcEncryptionKey` (base64 bundle)+     * or fetched from `/api/pqc/getkey`. If fetched, caches it. This is the "higher"+     * endpoint check: non-null means peer supports PQC → caller should publish only to PQC.+     */+    private suspend fun peerPqcBundle(user: User): ByteArray? {+        if (!pqcReady) return null+        user.pqcEncryptionKey?.let { return Base64.decode(it) }+        val bundle = getPqcKey(user.id) ?: return null+        userDao.upsert(user.copy(pqcEncryptionKey = Base64.encode(bundle)))+        return bundle+    }++    /**+     * Whether a given [User] has a PQC key available (cached or fetchable). Used to decide+     * whether to skip classic endpoint.+     */+    suspend fun isPqcUser(user: User): Boolean {+        if (!pqcReady) return false+        if (user.pqcEncryptionKey != null) return true+        // Opportunistic fetch without caching twice (peerPqcBundle will cache if found).+        return getPqcKey(user.id) != null+    }+     @Serializable     private data class LocationSharingData(val recipientUserID: ULong, val encryptedLocation: String) 
library/e2ee-p2p/src/main/rust/src/c_bridge.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/c_bridge.rs b/library/e2ee-p2p/src/main/rust/src/c_bridge.rsnew file mode 100644index 0000000000..2208dc6929--- /dev/null+++ b/library/e2ee-p2p/src/main/rust/src/c_bridge.rs@@ -0,0 +1,432 @@+//! C ABI exports for iOS (and cross-platform consumers) so FindFamilyiOS can+//! reuse the exact same ML-KEM-768 + ML-DSA-65 implementation as Office's+//! Android PqcIdentity, with identical bundle format and KDF.+//!+//! Bundle formats (identical to `Pqc.kt`):+//!   - public bundle:  [4B kemPubLen BE][kemPub SPKI DER][dsaPub SPKI DER]+//!   - private bundle: [4B kemPrivLen BE][kemPriv PKCS#8 DER][dsaPriv PKCS#8 DER]+//!   - sealed blob:    [4B encapLen BE][encap(1088)][aes] where aes = [12B iv][ct||tag]+//!+//! Memory ownership: every `Vec<u8>` returned as `*mut u8 + len` is allocated via `Box::into_raw`+//! and must be freed by `pqc_free`. Output pointer/len pairs are written into caller-provided+//! out-params; null on failure returns 0. This keeps the surface minimal and avoids cbindgen.+//!+//! All functions return 1 on success, 0 on failure (except `pqc_free`/`pqc_secure_zero` which are void).++use std::ptr;+use std::slice;++// ---------------------------------------------------------------------------+// Alloc helpers — callers must free via pqc_free(ptr, len).+// ---------------------------------------------------------------------------++fn alloc_bytes(v: Vec<u8>) -> (*mut u8, usize) {+    let len = v.len();+    let ptr = Box::into_raw(v.into_boxed_slice()) as *mut u8;+    (ptr, len)+}++/// Frees a buffer previously returned by alloc_bytes / encap/encaps etc.+#[no_mangle]+pub unsafe extern "C" fn pqc_free(ptr: *mut u8, len: usize) {+    if ptr.is_null() {+        return;+    }+    let _ = Box::from_raw(slice::from_raw_parts_mut(ptr, len));+}++/// Best-effort secure zero of a buffer (for private keys / shared secrets).+#[no_mangle]+pub unsafe extern "C" fn pqc_secure_zero(ptr: *mut u8, len: usize) {+    if ptr.is_null() || len == 0 {+        return;+    }+    ptr::write_bytes(ptr, 0, len);+}++// ---------------------------------------------------------------------------+// Length-prefix framing (same as Kotlin Pqc.lenPrefix / unLenPrefix)+// ---------------------------------------------------------------------------++fn len_prefix(a: &[u8], b: &[u8]) -> Vec<u8> {+    let mut out = Vec::with_capacity(4 + a.len() + b.len());+    out.extend_from_slice(&(a.len() as u32).to_be_bytes());+    out.extend_from_slice(a);+    out.extend_from_slice(b);+    out+}++fn un_len_prefix(x: &[u8]) -> Option<(&[u8], &[u8])> {+    if x.len() < 4 {+        return None;+    }+    let len = u32::from_be_bytes([x[0], x[1], x[2], x[3]]) as usize;+    if 4 + len > x.len() {+        return None;+    }+    Some((&x[4..4 + len], &x[4 + len..]))+}++// ---------------------------------------------------------------------------+// Public helpers exported for iOS tests / diagnostics.+// ---------------------------------------------------------------------------++/// Returns 1 if `bundle` looks like a valid public PQC bundle (kemLen + at least that many bytes).+#[no_mangle]+pub unsafe extern "C" fn pqc_bundle_is_valid(bundle: *const u8, bundle_len: usize) -> i32 {+    if bundle.is_null() || bundle_len < 4 {+        return 0;+    }+    let slice = slice::from_raw_parts(bundle, bundle_len);+    i32::from(un_len_prefix(slice).is_some())+}++/// Returns 1 and fills out_* with DER lengths if parseable. On fail returns 0.+#[no_mangle]+pub unsafe extern "C" fn pqc_bundle_inspect(+    bundle: *const u8,+    bundle_len: usize,+    kem_pub_len_out: *mut usize,+    dsa_pub_len_out: *mut usize,+) -> i32 {+    if bundle.is_null() || bundle_len < 4 || kem_pub_len_out.is_null() || dsa_pub_len_out.is_null() {+        return 0;+    }+    let s = slice::from_raw_parts(bundle, bundle_len);+    match un_len_prefix(s) {+        Some((kem, dsa)) => {+            ptr::write(kem_pub_len_out, kem.len());+            ptr::write(dsa_pub_len_out, dsa.len());+            1+        }+        None => 0,+    }+}++// ---------------------------------------------------------------------------+// KEM keygen (returns public + private DER via out-params)+// ---------------------------------------------------------------------------++/// Generates an ML-KEM-768 keypair. Out params filled on success (caller must free via pqc_free).+#[no_mangle]+pub unsafe extern "C" fn pqc_kem_keygen(+    pub_out: *mut *mut u8,+    pub_len_out: *mut usize,+    priv_out: *mut *mut u8,+    priv_len_out: *mut usize,+) -> i32 {+    if pub_out.is_null() || pub_len_out.is_null() || priv_out.is_null() || priv_len_out.is_null() {+        return 0;+    }+    let (pub_der, priv_der) = crate::mlkem_keygen_der();+    let (pub_ptr, pub_len) = alloc_bytes(pub_der);+    let (priv_ptr, priv_len) = alloc_bytes(priv_der);+    ptr::write(pub_out, pub_ptr);+    ptr::write(pub_len_out, pub_len);+    ptr::write(priv_out, priv_ptr);+    ptr::write(priv_len_out, priv_len);+    1+}++// ---------------------------------------------------------------------------+// DSA keygen+// ---------------------------------------------------------------------------++/// Generates an ML-DSA-65 keypair. Out params filled on success (caller must free).+#[no_mangle]+pub unsafe extern "C" fn pqc_dsa_keygen(+    pub_out: *mut *mut u8,+    pub_len_out: *mut usize,+    priv_out: *mut *mut u8,+    priv_len_out: *mut usize,+) -> i32 {+    if pub_out.is_null() || pub_len_out.is_null() || priv_out.is_null() || priv_len_out.is_null() {+        return 0;+    }+    let (pub_der, priv_der) = crate::mldsa_keygen_der();+    let (pub_ptr, pub_len) = alloc_bytes(pub_der);+    let (priv_ptr, priv_len) = alloc_bytes(priv_der);+    ptr::write(pub_out, pub_ptr);+    ptr::write(pub_len_out, pub_len);+    ptr::write(priv_out, priv_ptr);+    ptr::write(priv_len_out, priv_len);+    1+}++// ---------------------------------------------------------------------------+// Full identity keygen — public bundle + private bundle+// ---------------------------------------------------------------------------++/// Generates both KEM+DSA and returns the public bundle and private bundle.+/// Public bundle:  [4B kemPubLen][kemPub][dsaPub]+/// Private bundle: [4B kemPrivLen][kemPriv][dsaPriv]+#[no_mangle]+pub unsafe extern "C" fn pqc_identity_keygen(+    pub_bundle_out: *mut *mut u8,+    pub_bundle_len_out: *mut usize,+    priv_bundle_out: *mut *mut u8,+    priv_bundle_len_out: *mut usize,+) -> i32 {+    if pub_bundle_out.is_null()+        || pub_bundle_len_out.is_null()+        || priv_bundle_out.is_null()+        || priv_bundle_len_out.is_null()+    {+        return 0;+    }+    let (kem_pub, kem_priv) = crate::mlkem_keygen_der();+    let (dsa_pub, dsa_priv) = crate::mldsa_keygen_der();+    let pub_b = len_prefix(&kem_pub, &dsa_pub);+    let priv_b = len_prefix(&kem_priv, &dsa_priv);+    let (pub_ptr, pub_len) = alloc_bytes(pub_b);+    let (priv_ptr, priv_len) = alloc_bytes(priv_b);+    ptr::write(pub_bundle_out, pub_ptr);+    ptr::write(pub_bundle_len_out, pub_len);+    ptr::write(priv_bundle_out, priv_ptr);+    ptr::write(priv_bundle_len_out, priv_len);+    1+}++// ---------------------------------------------------------------------------+// Bundle helper (iOS builds bundle same way as Pqc.kt)+// ---------------------------------------------------------------------------++/// Builds a public PQC bundle from individual KEM and DSA public DERs.+#[no_mangle]+pub unsafe extern "C" fn pqc_bundle_build(+    kem_pub: *const u8,+    kem_pub_len: usize,+    dsa_pub: *const u8,+    dsa_pub_len: usize,+    out: *mut *mut u8,+    out_len: *mut usize,+) -> i32 {+    if kem_pub.is_null() || dsa_pub.is_null() || out.is_null() || out_len.is_null() {+        return 0;+    }+    let kem = slice::from_raw_parts(kem_pub, kem_pub_len);+    let dsa = slice::from_raw_parts(dsa_pub, dsa_pub_len);+    let b = len_prefix(kem, dsa);+    let (ptr, len) = alloc_bytes(b);+    ptr::write(out, ptr);+    ptr::write(out_len, len);+    1+}++/// Splits a public bundle into KEM and DSA components (caller frees each via pqc_free).+#[no_mangle]+pub unsafe extern "C" fn pqc_bundle_split(+    bundle: *const u8,+    bundle_len: usize,+    kem_pub_out: *mut *mut u8,+    kem_pub_len_out: *mut usize,+    dsa_pub_out: *mut *mut u8,+    dsa_pub_len_out: *mut usize,+) -> i32 {+    if bundle.is_null()+        || kem_pub_out.is_null()+        || kem_pub_len_out.is_null()+        || dsa_pub_out.is_null()+        || dsa_pub_len_out.is_null()+    {+        return 0;+    }+    let s = slice::from_raw_parts(bundle, bundle_len);+    let (kem, dsa) = match un_len_prefix(s) {+        Some(p) => p,+        None => return 0,+    };+    let (k_ptr, k_len) = alloc_bytes(kem.to_vec());+    let (d_ptr, d_len) = alloc_bytes(dsa.to_vec());+    ptr::write(kem_pub_out, k_ptr);+    ptr::write(kem_pub_len_out, k_len);+    ptr::write(dsa_pub_out, d_ptr);+    ptr::write(dsa_pub_len_out, d_len);+    1+}++// ---------------------------------------------------------------------------+// Encapsulate / Decapsulate raw (for direct use)+// ---------------------------------------------------------------------------++/// Encapsulates to a KEM public DER: returns (ciphertext(1088), sharedSecret(32)).+#[no_mangle]+pub unsafe extern "C" fn pqc_kem_encaps(+    kem_pub: *const u8,+    kem_pub_len: usize,+    ct_out: *mut *mut u8,+    ct_len_out: *mut usize,+    ss_out: *mut *mut u8,+    ss_len_out: *mut usize,+) -> i32 {+    if kem_pub.is_null() || ct_out.is_null() || ct_len_out.is_null() || ss_out.is_null() || ss_len_out.is_null() {+        return 0;+    }+    let pub_slice = slice::from_raw_parts(kem_pub, kem_pub_len);+    let (ct, ss) = match crate::mlkem_encaps_der(pub_slice) {+        Some(p) => p,+        None => return 0,+    };+    let (ct_ptr, ct_len) = alloc_bytes(ct);+    let (ss_ptr, ss_len) = alloc_bytes(ss);+    ptr::write(ct_out, ct_ptr);+    ptr::write(ct_len_out, ct_len);+    ptr::write(ss_out, ss_ptr);+    ptr::write(ss_len_out, ss_len);+    1+}++/// Decapsulates with a KEM private DER + ciphertext -> sharedSecret(32).+#[no_mangle]+pub unsafe extern "C" fn pqc_kem_decaps(+    kem_priv: *const u8,+    kem_priv_len: usize,+    ct: *const u8,+    ct_len: usize,+    ss_out: *mut *mut u8,+    ss_len_out: *mut usize,+) -> i32 {+    if kem_priv.is_null() || ct.is_null() || ss_out.is_null() || ss_len_out.is_null() {+        return 0;+    }+    let priv_slice = slice::from_raw_parts(kem_priv, kem_priv_len);+    let ct_slice = slice::from_raw_parts(ct, ct_len);+    let ss = match crate::mlkem_decaps_der(priv_slice, ct_slice) {+        Some(s) => s,+        None => return 0,+    };+    let (ss_ptr, len) = alloc_bytes(ss);+    ptr::write(ss_out, ss_ptr);+    ptr::write(ss_len_out, len);+    1+}++// ---------------------------------------------------------------------------+// High-level encrypt/decrypt to a public bundle (same framing as Pqc.encryptTo)+// Layout sealed: [4B encapLen BE][encap(1088)][aes] where aes = [12B iv][ciphertext||tag]+// AES key is sharedSecret = SHA256(BE32(1)||rawSS) identical to Kotlin's concat_kdf.+// ---------------------------------------------------------------------------++/// NOTE: The high-level encrypt/decrypt that does AES is implemented on the Kotlin/Swift side+/// because it needs AES-GCM (CryptoKit / javax.crypto). This crate exposes only KEM primitives+/// via C. Swift's PQCCrypto will reproduce E2ee.aesEncrypt layout for full compatibility.+///+/// For iOS convenience we also expose these direct-derivation helpers that perform the full+/// PQC seal/unseal if the caller provides an AES implementation, or we do AES here using+/// a pure-Rust software AES if `aes-gcm` were added. To keep deps minimal, we use the same+/// AES-GCM as in Kotlin: iv prepended. This requires adding `aes-gcm` + `aead`. To avoid+/// new deps in this PR, we leave AES to the Swift layer — so we expose no aes-containing+/// extern here, only KEM.++/// Signs with DSA private DER.+#[no_mangle]+pub unsafe extern "C" fn pqc_dsa_sign(+    dsa_priv: *const u8,+    dsa_priv_len: usize,+    msg: *const u8,+    msg_len: usize,+    sig_out: *mut *mut u8,+    sig_len_out: *mut usize,+) -> i32 {+    if dsa_priv.is_null() || msg.is_null() || sig_out.is_null() || sig_len_out.is_null() {+        return 0;+    }+    let priv_slice = slice::from_raw_parts(dsa_priv, dsa_priv_len);+    let msg_slice = slice::from_raw_parts(msg, msg_len);+    let sig = match crate::mldsa_sign_der(priv_slice, msg_slice) {+        Some(s) => s,+        None => return 0,+    };+    let (ptr, len) = alloc_bytes(sig);+    ptr::write(sig_out, ptr);+    ptr::write(sig_len_out, len);+    1+}++/// Verifies with DSA public DER. Returns 1 if valid, 0 if invalid, -1 on parse error.+#[no_mangle]+pub unsafe extern "C" fn pqc_dsa_verify(+    dsa_pub: *const u8,+    dsa_pub_len: usize,+    msg: *const u8,+    msg_len: usize,+    sig: *const u8,+    sig_len: usize,+) -> i32 {+    if dsa_pub.is_null() || msg.is_null() || sig.is_null() {+        return -1;+    }+    let pub_slice = slice::from_raw_parts(dsa_pub, dsa_pub_len);+    let msg_slice = slice::from_raw_parts(msg, msg_len);+    let sig_slice = slice::from_raw_parts(sig, sig_len);+    if crate::mldsa_verify_der(pub_slice, msg_slice, sig_slice) {+        1+    } else {+        0+    }+}++// ---------------------------------------------------------------------------+// Combined security code — identical to SecurityCode.compute in Kotlin+// Computes same 6-group 5-digit code from two public bundles.+// ---------------------------------------------------------------------------++/// Computes security code length prefix: fills out buffer with code string (30 digits + 5 spaces + NUL).+/// out must be at least 36 bytes (35 chars + NUL). Returns 1 on success, 0 on fail.+#[no_mangle]+pub unsafe extern "C" fn pqc_security_code(+    my_bundle: *const u8,+    my_bundle_len: usize,+    their_bundle: *const u8,+    their_bundle_len: usize,+    out: *mut u8,+    out_len: usize,+) -> i32 {+    if my_bundle.is_null() || their_bundle.is_null() || out.is_null() || out_len < 36 {+        return 0;+    }+    // compute SHA256 of each bundle, sort, 4000 iter.+    use sha2::{Digest, Sha256};+    const ITER: usize = 4000;+    let a_slice = slice::from_raw_parts(my_bundle, my_bundle_len);+    let b_slice = slice::from_raw_parts(their_bundle, their_bundle_len);+    let mut sha = Sha256::new();+    sha.update(a_slice);+    let ha = sha.finalize_reset();+    sha.update(b_slice);+    let hb = sha.finalize();+    // canonical concat sorted+    let mut h: Vec<u8> = if ha.as_slice() <= hb.as_slice() {+        [ha.as_slice(), hb.as_slice()].concat()+    } else {+        [hb.as_slice(), ha.as_slice()].concat()+    };+    for _ in 0..ITER {+        let mut s2 = Sha256::new();+        s2.update(&h);+        h = s2.finalize().to_vec();+    }+    // format 6 groups 5 digits+    let mut code_bytes = Vec::with_capacity(35);+    let mut idx = 0usize;+    for group in 0..6 {+        if idx + 5 > h.len() {+            return 0;+        }+        let mut v: u64 = 0;+        for j in 0..5 {+            v = (v << 8) | (h[idx + j] as u64);+        }+        if group > 0 {+            code_bytes.push(b' ');+        }+        let grp = format!("{:05}", v % 100000);+        code_bytes.extend_from_slice(grp.as_bytes());+        idx += 5;+    }+    // copy + NUL+    let copy_len = code_bytes.len().min(out_len - 1);+    ptr::copy_nonoverlapping(code_bytes.as_ptr(), out, copy_len);+    ptr::write(out.add(copy_len), 0u8);+    1+}
library/e2ee-p2p/src/main/rust/src/lib.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/lib.rs b/library/e2ee-p2p/src/main/rust/src/lib.rsindex 0fc6461034..5eeefd89a0 100644--- a/library/e2ee-p2p/src/main/rust/src/lib.rs+++ b/library/e2ee-p2p/src/main/rust/src/lib.rs@@ -187,6 +187,7 @@ pub fn mldsa_verify_der(pub_der: &[u8], msg: &[u8], sig: &[u8]) -> bool { }  mod jni_bridge;+mod c_bridge;  #[cfg(test)] mod tests;