findfamily: shorten share links via a seeded ML-KEM link key
- Commit
efc28647c699b7816c7db0f509204e062b6b2f43- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-20 20:06 UTC (3 months ago)
- Parents
665902a
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 16e8ff3668..2555edc161 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -911,6 +911,7 @@ dependencies = [ "jni", "rand_core 0.6.4", "sha2 0.10.9",+ "sha3", ] [[package]]
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 9cafef1108..0631416acb 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -110,6 +110,9 @@ flate2 = "1.1.4" # Crypto / PQC (features preserved – no feature loss) sha2 = { version = "0.10.9", features = ["oid"] }+# SHAKE256 for FindFamily link-seed expansion. Already in the lock file transitively+# via fips203/fips204, so this only promotes it to a direct dependency.+sha3 = "0.10" aes = "0.8.4" md-5 = "0.10.6" keepass = { version = "0.13.17", default-features = false, features = ["save_kdbx4"] }
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 d61da0e3ab..bc66b75671 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -149,7 +149,7 @@ interface TemporaryLinkDao { suspend fun delete(value: TemporaryLink): Int } -@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 10, exportSchema = false)+@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 11, exportSchema = false) @TypeConverters(DefaultConverters::class) abstract class FFDatabase : RoomDatabase() { abstract fun userDao(): UserDao@@ -216,6 +216,26 @@ abstract class FFDatabase : RoomDatabase() { // tracker. Room stores the enum as its name; existing rows default to PERSON. androidx.room.migration.Migration(9, 10) { it.execSQL("ALTER TABLE `User` ADD COLUMN `kind` TEXT NOT NULL DEFAULT 'PERSON'")+ },+ // Share links carry a 32-byte ML-KEM seed (`pqcSeed`) instead of a full private+ // bundle, so `pqcKey` becomes nullable and only legacy rows keep it. SQLite cannot+ // drop NOT NULL in place, so rebuild the table as in Migration(7, 8). Rows keep+ // their ids — those URLs are already shared.+ androidx.room.migration.Migration(10, 11) {+ it.execSQL(+ "CREATE TABLE IF NOT EXISTS `TemporaryLink_new` (" ++ "`name` TEXT NOT NULL, `deleteAt` INTEGER NOT NULL, " ++ "`pqcPublicKey` TEXT NOT NULL, `pqcKey` TEXT, `pqcSeed` TEXT, " ++ "`id` INTEGER NOT NULL, PRIMARY KEY(`id`))"+ )+ it.execSQL(+ "INSERT INTO `TemporaryLink_new` " ++ "(`name`, `deleteAt`, `pqcPublicKey`, `pqcKey`, `pqcSeed`, `id`) " ++ "SELECT `name`, `deleteAt`, `pqcPublicKey`, `pqcKey`, NULL, `id` " ++ "FROM `TemporaryLink`"+ )+ it.execSQL("DROP TABLE `TemporaryLink`")+ it.execSQL("ALTER TABLE `TemporaryLink_new` RENAME TO `TemporaryLink`") } ) }
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 7b56a25341..2c3e04d315 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/TemporaryLink.kt@@ -23,8 +23,7 @@ fun newTemporaryLinkId(): Long = Random.nextLong(from = 1, until = Long.MAX_VALU /** * An anonymous location-sharing link. Post-quantum only: there is no RSA keypair and no- * classic fallback, so a link either has a usable ML-KEM/ML-DSA bundle or it is not created- * at all. Both key fields are non-null for that reason.+ * classic fallback, so a link either has a usable ML-KEM bundle or it is not created at all. */ @Serializable @Entity@@ -35,11 +34,18 @@ data class TemporaryLink( /** PQC ephemeral public bundle (base64 [4B kemLen][kemPub][dsaPub]) — what we encrypt to. */ val pqcPublicKey: String, /**- * PQC ephemeral private bundle (base64 [4B kemLen][kemPriv][dsaPriv] — kemPriv =- * seed+expanded via BC compat). Handed to the recipient in the URL fragment; never sent- * to the server.+ * Legacy: the full PQC private bundle (base64 [4B kemLen][kemPriv][dsaPriv]) that older+ * builds put in the URL fragment as `#pqc_key=`. Only set on links created before links+ * moved to [pqcSeed]; those URLs are already in the wild, so it is kept so they can still+ * be re-copied. Null on every new link. */- val pqcKey: String,+ val pqcKey: String? = null,+ /**+ * The 32-byte ML-KEM link seed, base64url without padding — what goes in the URL fragment+ * as `#s=`. This is the link's entire secret: the recipient's browser expands it to an+ * ML-KEM keypair, so nothing else needs storing or transmitting. Null on legacy links.+ */+ val pqcSeed: String? = null, @PrimaryKey override val id: Long = newTemporaryLinkId(), ): DatabaseItem\ No newline at end of file
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 80048de3e5..2c471aad30 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt@@ -2,6 +2,7 @@ package com.vayunmathur.findfamily.intents import com.vayunmathur.findfamily.data.FindFamilyRepository import com.vayunmathur.findfamily.data.TemporaryLink+import com.vayunmathur.findfamily.ui.dialogs.encodeBase26 import com.vayunmathur.findfamily.util.Networking import com.vayunmathur.library.util.AssistantIntent import kotlinx.serialization.InternalSerializationApi@@ -16,10 +17,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- * 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.+ * link. Reuses FindFamily's temporary-link mechanism: generate an ML-KEM link key,+ * 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. */ @OptIn(InternalSerializationApi::class) class CreateLinkIntent : AssistantIntent<CreateLinkData, String>(@@ -29,17 +30,17 @@ class CreateLinkIntent : AssistantIntent<CreateLinkData, String>( override suspend fun performCalculation(input: CreateLinkData): String { // Links are post-quantum only — with no classic fallback, a PQC keygen failure has to // fail the whole call rather than hand back a link that can never publish.- val pqcPair = Networking.generatePqcKeyPair()+ val linkKey = Networking.generatePqcLinkKey() val link = TemporaryLink( name = input.name, deleteAt = Clock.System.now() + input.expiryMillis.milliseconds,- pqcPublicKey = pqcPair.publicBundleB64,- pqcKey = pqcPair.privateBundleB64,+ pqcPublicKey = linkKey.publicBundleB64,+ pqcSeed = linkKey.seedB64Url, ) FindFamilyRepository.get(this).upsertTemporaryLink(link) // The id is generated with the link (newTemporaryLinkId), not handed back by the // insert, so read it off the entity — @Upsert returns -1 on the update path. // Must match the URL format produced by TemporaryLinkCard in MainPage.- return "https://findfamily.cc/view/${link.id}#pqc_key=${link.pqcKey}"+ return "https://findfamily.cc/view/${link.id.encodeBase26()}#s=${linkKey.seedB64Url}" } }
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.ktindex fed0c00d38..7e290f6cc8 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt@@ -39,7 +39,7 @@ object TrackerBinder { val repository = FindFamilyRepository.get(context) val store = TrackerStore(DataStoreUtils.getInstance(context)) - val keys = Networking.generatePqcKeyPair()+ val keys = Networking.generatePqcIdentityKeyPair() val publicBundle = decodeB64(keys.publicBundleB64) val privateBundle = decodeB64(keys.privateBundleB64) val secret = ByteArray(TrackerProtocol.SECRET_LEN).also { SecureRandom().nextBytes(it) }
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.ktindex 486181e2f8..2b4a54ce17 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt@@ -87,7 +87,7 @@ object TrackerProtocol { /** * Owner side: decrypt a crowd report [ciphertext] with the tracker's private * bundle ([privateBundle], layout `[4B kemPrivLen][kemPriv][dsaPriv]`, as- * produced by `Networking.generatePqcKeyPair`) and stamp it with the tracker's+ * produced by `Networking.generatePqcIdentityKeyPair`) and stamp it with the tracker's * [trackerUserId] so it flows through the normal incoming-location pipeline. */ fun openReport(privateBundle: ByteArray, ciphertext: ByteArray, trackerUserId: Long): LocationValue {
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 13321a5522..27baa98703 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -216,9 +216,14 @@ fun MainPage( } override fun copyLink(link: TemporaryLink) {- // Links are post-quantum only, so the fragment carries just the PQC- // private bundle — no classic `#key=`. The fragment never hits the server.- platform.copy("https://findfamily.cc/view/${link.id}#pqc_key=${link.pqcKey}")+ // The fragment carries the link's secret and never hits the server. New links+ // send just the 32-byte ML-KEM seed (`#s=`) with a Base26 id, which fits in an+ // SMS; links minted before that still carry their full private bundle.+ val seed = link.pqcSeed+ platform.copy(+ if (seed != null) "https://findfamily.cc/view/${link.id.encodeBase26()}#s=$seed"+ else "https://findfamily.cc/view/${link.id}#pqc_key=${link.pqcKey}"+ ) } } }
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 9335aa345d..bfee03eab9 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt@@ -416,8 +416,8 @@ class FindFamilyViewModel( // ------------------------------------------------------------------ /**- * 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).+ * Generate an ML-KEM link key and persist a [TemporaryLink] for sharing. The link's whole+ * secret is a 32-byte seed; the public bundle is what locations get encrypted to. * Calls [onDone] on the main thread once the upsert completes. */ fun createTemporaryLink(name: String, expiry: Duration, onDone: (success: Boolean) -> Unit = {}) {@@ -425,18 +425,18 @@ class FindFamilyViewModel( // Links are post-quantum only: if the PQC keygen fails (native lib unavailable) // there is nothing to fall back to, so report failure instead of minting a link // that can never publish.- val pqcPair = runCatching { Networking.generatePqcKeyPair() }+ val linkKey = runCatching { Networking.generatePqcLinkKey() } .onFailure { Log.w("FindFamilyViewModel", "createTemporaryLink: PQC keygen failed", it) } .getOrNull()- if (pqcPair == null) {+ if (linkKey == null) { withContext(Dispatchers.Main) { onDone(false) } return@launch } val newLink = TemporaryLink( name = name, deleteAt = Clock.System.now() + expiry,- pqcPublicKey = pqcPair.publicBundleB64,- pqcKey = pqcPair.privateBundleB64,+ pqcPublicKey = linkKey.publicBundleB64,+ pqcSeed = linkKey.seedB64Url, ) repository.upsertTemporaryLink(newLink) withContext(Dispatchers.Main) { onDone(true) }
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 11af8ca530..957f1d6cd6 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -590,22 +590,40 @@ object Networking { } /**- * Generates a fresh PQC key bundle for an ephemeral temporary link.- * Returns (publicBundleBase64, privateBundleBase64) where the private bundle is- * [4B kemPrivLen][kemPrivDer][dsaPrivDer] — DERs, BC-compatible, same KDF as Office.+ * Generates a fresh share-link key. The link is ML-KEM only and derived from a+ * 32-byte seed, which is the whole secret handed to the recipient in the URL+ * fragment — short enough to fit in an SMS. The private key is never stored:+ * the sender only ever encrypts, and the recipient re-derives it from the seed. */- fun generatePqcKeyPair(): PqcLinkKeyPair {+ fun generatePqcLinkKey(): PqcLinkKey {+ val key = Pqc.generateLinkKey()+ return PqcLinkKey(+ seedB64Url = Base64.UrlSafe.encode(key.seed).trimEnd('='),+ publicBundleB64 = Base64.encode(key.publicBundle)+ )+ }++ data class PqcLinkKey(val seedB64Url: String, val publicBundleB64: String)++ /**+ * Generates a full PQC identity (ML-KEM + ML-DSA) for a device we own but that cannot+ * run keygen itself — currently only UWB trackers, whose private bundle we hold on+ * their behalf. Returns (publicBundleBase64, privateBundleBase64) where the private+ * bundle is [4B kemPrivLen][kemPrivDer][dsaPrivDer] — DERs, BC-compatible, same KDF+ * as Office. Share links use [generatePqcLinkKey] instead.+ */+ fun generatePqcIdentityKeyPair(): PqcIdentityKeyPair { val (kemPub, kemPriv) = Pqc.generateKem() val (dsaPub, dsaPriv) = Pqc.generateDsa() val pubBundle = Pqc.bundle(kemPub, dsaPub) val privBundle = buildPrivBundle(kemPriv, dsaPriv)- return PqcLinkKeyPair(+ return PqcIdentityKeyPair( publicBundleB64 = Base64.encode(pubBundle), privateBundleB64 = Base64.encode(privBundle) ) } - data class PqcLinkKeyPair(val publicBundleB64: String, val privateBundleB64: String)+ data class PqcIdentityKeyPair(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 {
findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt
diff --git a/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt b/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.ktindex 879a6e01a0..d7cac7f738 100644--- a/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt+++ b/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt@@ -118,7 +118,7 @@ class MetadataPreviews { name = "Dog walker", deleteAt = now + 45.minutes, pqcPublicKey = "",- pqcKey = "",+ pqcSeed = "", id = 91, ), ),
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.ktindex 5a9cc7d2f6..96482caa43 100644--- a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pqc.kt@@ -10,8 +10,10 @@ package com.vayunmathur.e2ee * with the previously-deployed Bouncy Castle encoding — including BC's SHA-256 * single-step KDF over the ML-KEM shared secret — so existing identities and * ciphertexts keep working. A device's public identity is a [bundle] of its- * ML-KEM and ML-DSA public keys. FindFamily keeps using RSA (see [E2ee]); only- * Office uses this.+ * ML-KEM and ML-DSA public keys.+ *+ * FindFamily additionally uses [generateLinkKey] for share links: ML-KEM only,+ * derived from a 32-byte seed small enough to fit in a URL fragment. */ object Pqc { /** Generate an ML-KEM keypair. Returns (kemPubDer, kemPrivDer). */@@ -20,6 +22,25 @@ object Pqc { return kp[0] to kp[1] } + /**+ * A FindFamily share-link key. [seed] is the only secret — the ML-KEM keypair is+ * derived from it, so the seed alone is what travels in the link and what needs+ * storing. [publicBundle] has an empty ML-DSA half; nothing signs link data.+ */+ class LinkKey(val seed: ByteArray, val publicBundle: ByteArray)++ /** Generate a fresh share-link key. */+ fun generateLinkKey(): LinkKey {+ val kp = PqcNative.nativeMlkemLinkKeygen() ?: error("ML-KEM link keygen failed")+ return LinkKey(kp[0], bundle(kp[1], ByteArray(0)))+ }++ /** Re-derive a share-link public bundle from a stored 32-byte seed. */+ fun linkPublicFromSeed(seed: ByteArray): ByteArray {+ val kemPub = PqcNative.nativeMlkemLinkPubFromSeed(seed) ?: error("ML-KEM link derive failed")+ return bundle(kemPub, ByteArray(0))+ }+ /** Generate an ML-DSA keypair. Returns (dsaPubDer, dsaPrivDer). */ fun generateDsa(): Pair<ByteArray, ByteArray> { val kp = PqcNative.nativeMldsaKeygen() ?: error("ML-DSA keygen failed")
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcNative.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcNative.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcNative.ktindex 6df2819c79..184dd9eeb5 100644--- a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcNative.kt+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcNative.kt@@ -8,6 +8,8 @@ package com.vayunmathur.e2ee */ internal object PqcNative { external fun nativeMlkemKeygen(): Array<ByteArray>?+ external fun nativeMlkemLinkKeygen(): Array<ByteArray>?+ external fun nativeMlkemLinkPubFromSeed(seed: ByteArray): ByteArray? external fun nativeMldsaKeygen(): Array<ByteArray>? external fun nativeMlkemEncaps(pubDer: ByteArray): Array<ByteArray>? external fun nativeMlkemDecaps(privDer: ByteArray, ct: ByteArray): ByteArray?
library/e2ee-p2p/src/main/rust/Cargo.toml
diff --git a/library/e2ee-p2p/src/main/rust/Cargo.toml b/library/e2ee-p2p/src/main/rust/Cargo.tomlindex 43dd76f2a5..35d0fdb89d 100644--- a/library/e2ee-p2p/src/main/rust/Cargo.toml+++ b/library/e2ee-p2p/src/main/rust/Cargo.toml@@ -13,6 +13,7 @@ crate-type = ["cdylib", "rlib"] fips203.workspace = true fips204.workspace = true sha2.workspace = true+sha3.workspace = true jni.workspace = true rand_core = { version = "0.6", features = ["getrandom"] }
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.rsindex 6f83d76f7f..f6817a2cfb 100644--- a/library/e2ee-p2p/src/main/rust/src/c_bridge.rs+++ b/library/e2ee-p2p/src/main/rust/src/c_bridge.rs@@ -187,6 +187,64 @@ pub unsafe extern "C" fn pqc_identity_keygen( 1 } +// ---------------------------------------------------------------------------+// FindFamily link keys — ML-KEM only, derived from a 32-byte seed.+// The public bundle keeps the [4B kemLen][kem][dsa] layout with an empty DSA+// half, so pqc_bundle_split / encryptTo need no special casing.+// ---------------------------------------------------------------------------++/// Generates a fresh link seed and its ML-KEM-only public bundle.+/// Out params filled on success (caller must free via pqc_free; zero the seed first).+#[no_mangle]+pub unsafe extern "C" fn pqc_link_keygen(+ seed_out: *mut *mut u8,+ seed_len_out: *mut usize,+ pub_bundle_out: *mut *mut u8,+ pub_bundle_len_out: *mut usize,+) -> i32 {+ if seed_out.is_null()+ || seed_len_out.is_null()+ || pub_bundle_out.is_null()+ || pub_bundle_len_out.is_null()+ {+ return 0;+ }+ let seed = crate::mlkem_link_seed_new();+ let (kem_pub, _) = match crate::mlkem_link_keygen_from_seed(&seed) {+ Some(p) => p,+ None => return 0,+ };+ let (seed_ptr, seed_len) = alloc_bytes(seed.to_vec());+ let (bundle_ptr, bundle_len) = alloc_bytes(len_prefix(&kem_pub, &[]));+ ptr::write(seed_out, seed_ptr);+ ptr::write(seed_len_out, seed_len);+ ptr::write(pub_bundle_out, bundle_ptr);+ ptr::write(pub_bundle_len_out, bundle_len);+ 1+}++/// Re-derives the ML-KEM-only public bundle from a stored link seed.+#[no_mangle]+pub unsafe extern "C" fn pqc_link_pub_from_seed(+ seed: *const u8,+ seed_len: usize,+ pub_bundle_out: *mut *mut u8,+ pub_bundle_len_out: *mut usize,+) -> i32 {+ if seed.is_null() || pub_bundle_out.is_null() || pub_bundle_len_out.is_null() {+ return 0;+ }+ let s = slice::from_raw_parts(seed, seed_len);+ let (kem_pub, _) = match crate::mlkem_link_keygen_from_seed(s) {+ Some(p) => p,+ None => return 0,+ };+ let (bundle_ptr, bundle_len) = alloc_bytes(len_prefix(&kem_pub, &[]));+ ptr::write(pub_bundle_out, bundle_ptr);+ ptr::write(pub_bundle_len_out, bundle_len);+ 1+}+ // --------------------------------------------------------------------------- // Bundle helper (iOS builds bundle same way as Pqc.kt) // ---------------------------------------------------------------------------
library/e2ee-p2p/src/main/rust/src/jni_bridge.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/jni_bridge.rs b/library/e2ee-p2p/src/main/rust/src/jni_bridge.rsindex b8545f3142..e98792a4c0 100644--- a/library/e2ee-p2p/src/main/rust/src/jni_bridge.rs+++ b/library/e2ee-p2p/src/main/rust/src/jni_bridge.rs@@ -51,6 +51,34 @@ pub extern "system" fn Java_com_vayunmathur_e2ee_PqcNative_nativeMlkemKeygen<'l> pair_out(&mut env, &pub_der, &priv_der) } +#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PqcNative_nativeMlkemLinkKeygen<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+) -> jobjectArray {+ let seed = mlkem_link_seed_new();+ match mlkem_link_keygen_from_seed(&seed) {+ Some((pub_der, _)) => pair_out(&mut env, &seed, &pub_der),+ None => std::ptr::null_mut(),+ }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PqcNative_nativeMlkemLinkPubFromSeed<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ seed: JByteArray<'l>,+) -> jbyteArray {+ let s = match bytes_in(&mut env, &seed) {+ Some(s) => s,+ None => return std::ptr::null_mut(),+ };+ match mlkem_link_keygen_from_seed(&s) {+ Some((pub_der, _)) => bytes_out(&env, &pub_der),+ None => std::ptr::null_mut(),+ }+}+ #[no_mangle] pub extern "system" fn Java_com_vayunmathur_e2ee_PqcNative_nativeMldsaKeygen<'l>( mut env: JNIEnv<'l>,
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 5eeefd89a0..c996ac966b 100644--- a/library/e2ee-p2p/src/main/rust/src/lib.rs+++ b/library/e2ee-p2p/src/main/rust/src/lib.rs@@ -20,6 +20,8 @@ const KEM_EK: usize = 1184; // encapsulation (public) key const KEM_DK: usize = 2400; // decapsulation (private, expanded) key const KEM_CT: usize = 1088; // ciphertext const KEM_SEED: usize = 64; // d || z+/// FindFamily share-link seed: the 32 bytes that travel in the URL fragment.+pub const LINK_SEED: usize = 32; // ---- ML-DSA-65 sizes ---- const DSA_PK: usize = 1952;@@ -151,6 +153,46 @@ pub fn mlkem_decaps_der(priv_der: &[u8], ct: &[u8]) -> Option<Vec<u8>> { Some(concat_kdf_sha256(&ssk.into_bytes(), 32)) } +// ---------- FindFamily link keys (ML-KEM only, seed-derived) ----------++/// Domain-separation string for link-seed expansion. **Wire format**: the browser+/// share page derives the same key from the same seed, so this string cannot change+/// without breaking every link already handed out.+const LINK_SEED_DOMAIN: &[u8] = b"ff-link-v1";++/// SHAKE256(LINK_SEED_DOMAIN || seed) -> 64 bytes, used as ML-KEM's `d || z`.+fn link_seed_expand(seed: &[u8]) -> [u8; KEM_SEED] {+ use sha3::digest::{ExtendableOutput, Update, XofReader};+ let mut h = sha3::Shake256::default();+ h.update(LINK_SEED_DOMAIN);+ h.update(seed);+ let mut out = [0u8; KEM_SEED];+ h.finalize_xof().read(&mut out);+ out+}++/// Fresh random link seed.+pub fn mlkem_link_seed_new() -> [u8; LINK_SEED] {+ let mut seed = [0u8; LINK_SEED];+ OsRng.fill_bytes(&mut seed);+ seed+}++/// Deterministically derive an ML-KEM keypair from a 32-byte link seed.+/// Returns (spkiPubDer, pkcs8PrivDer) in the same encoding as `mlkem_keygen_der`.+pub fn mlkem_link_keygen_from_seed(seed: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {+ if seed.len() != LINK_SEED {+ return None;+ }+ let dz = link_seed_expand(seed);+ let d: [u8; 32] = to_arr(&dz[..32])?;+ let z: [u8; 32] = to_arr(&dz[32..])?;+ let (ek, dk) = ml_kem_768::KG::keygen_from_seed(d, z);+ let pub_der = spki_wrap(&KEM_PUB_PREFIX, &ek.into_bytes());+ let priv_der = kem_priv_der(&dz, &dk.into_bytes());+ Some((pub_der, priv_der))+}+ // ---------- ML-DSA-65 ---------- pub fn mldsa_keygen_der() -> (Vec<u8>, Vec<u8>) {
library/e2ee-p2p/src/main/rust/src/tests.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/tests.rs b/library/e2ee-p2p/src/main/rust/src/tests.rsindex 8053a24b0b..dd8c593bb9 100644--- a/library/e2ee-p2p/src/main/rust/src/tests.rs+++ b/library/e2ee-p2p/src/main/rust/src/tests.rs@@ -87,3 +87,139 @@ fn our_generated_privkey_decaps() { let (ct, ss1) = mlkem_encaps_der(&pub_der).unwrap(); assert_eq!(mlkem_decaps_der(&priv_der, &ct).unwrap(), ss1); }++// ---------- FindFamily link keys ----------++fn sha256_hex(b: &[u8]) -> String {+ use sha2::{Digest, Sha256};+ let mut h = Sha256::new();+ h.update(b);+ h.finalize().iter().map(|x| format!("{:02x}", x)).collect()+}++/// The KAT seed shared with the browser share page (`decapsKeyFromSeed`).+const KAT_SEED: [u8; LINK_SEED] = [+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,+];++/// Cross-implementation known-answer test. The browser share page implements ML-KEM+/// KeyGen independently in JS; these digests are what proves the two agree. A mismatch+/// means every new share link silently fails to decrypt, so do not "fix" this test by+/// updating the digests — fix whichever side changed.+#[test]+fn link_kat_matches_js_implementation() {+ let (pub_der, priv_der) = mlkem_link_keygen_from_seed(&KAT_SEED).unwrap();+ let ek = spki_raw(&pub_der, KEM_EK).unwrap();+ let dk = pkcs8_expanded(&priv_der, KEM_DK).unwrap();+ assert_eq!(+ sha256_hex(ek),+ "27c74a3d979e6fcbdaea5a6b87968d38f60ab4f75cfeef7d521859c54865e6b3",+ "ML-KEM encapsulation key for KAT_SEED"+ );+ assert_eq!(+ sha256_hex(dk),+ "1e4c02fb2d2c6dcd292a6291d13feee8bc1307073409c460e6bdbfc64c93f03e",+ "ML-KEM decapsulation key for KAT_SEED"+ );+}++#[test]+fn link_keygen_is_deterministic() {+ let seed = mlkem_link_seed_new();+ let (p1, s1) = mlkem_link_keygen_from_seed(&seed).unwrap();+ let (p2, s2) = mlkem_link_keygen_from_seed(&seed).unwrap();+ assert_eq!(p1, p2);+ assert_eq!(s1, s2);+ // Distinct seeds must give distinct keys.+ let (p3, _) = mlkem_link_keygen_from_seed(&mlkem_link_seed_new()).unwrap();+ assert_ne!(p1, p3);+}++#[test]+fn link_keys_use_the_same_der_encoding_as_identity_keys() {+ let (pub_der, priv_der) = mlkem_link_keygen_from_seed(&KAT_SEED).unwrap();+ assert_eq!(pub_der.len(), KEM_PUB_PREFIX.len() + KEM_EK);+ assert_eq!(priv_der.len(), 2498);+ assert!(pub_der.starts_with(&KEM_PUB_PREFIX));+ assert!(priv_der.starts_with(&KEM_PRIV_PREFIX));+}++#[test]+fn link_key_roundtrip() {+ let seed = mlkem_link_seed_new();+ let (pub_der, priv_der) = mlkem_link_keygen_from_seed(&seed).unwrap();+ let (ct, ss1) = mlkem_encaps_der(&pub_der).expect("encaps");+ let ss2 = mlkem_decaps_der(&priv_der, &ct).expect("decaps");+ assert_eq!(ss1, ss2);+ // A private key re-derived from the seed alone decapsulates the same ciphertext.+ let (_, priv_again) = mlkem_link_keygen_from_seed(&seed).unwrap();+ assert_eq!(mlkem_decaps_der(&priv_again, &ct).unwrap(), ss1);+}++#[test]+fn link_keygen_rejects_wrong_seed_lengths() {+ assert!(mlkem_link_keygen_from_seed(&[]).is_none());+ assert!(mlkem_link_keygen_from_seed(&[0u8; 31]).is_none());+ assert!(mlkem_link_keygen_from_seed(&[0u8; 33]).is_none());+ assert!(mlkem_link_keygen_from_seed(&[0u8; 64]).is_none());+}++/// The C bridge (iOS) must produce exactly the bundle the core keygen implies:+/// [4B kemPubLen][kemPub] with an empty DSA half.+#[test]+fn c_bridge_link_pub_matches_core_keygen() {+ let (expected_pub, _) = mlkem_link_keygen_from_seed(&KAT_SEED).unwrap();+ let mut bundle: *mut u8 = std::ptr::null_mut();+ let mut bundle_len: usize = 0;+ let bundle = unsafe {+ assert_eq!(+ crate::c_bridge::pqc_link_pub_from_seed(+ KAT_SEED.as_ptr(),+ KAT_SEED.len(),+ &mut bundle,+ &mut bundle_len,+ ),+ 1+ );+ let v = std::slice::from_raw_parts(bundle, bundle_len).to_vec();+ crate::c_bridge::pqc_free(bundle, bundle_len);+ v+ };+ assert_eq!(bundle.len(), 4 + expected_pub.len());+ assert_eq!(+ u32::from_be_bytes([bundle[0], bundle[1], bundle[2], bundle[3]]) as usize,+ expected_pub.len()+ );+ assert_eq!(&bundle[4..], &expected_pub[..]);+ // The public bundle must still round-trip through the normal encaps path.+ let (ct, ss1) = mlkem_encaps_der(&bundle[4..]).unwrap();+ let (_, priv_der) = mlkem_link_keygen_from_seed(&KAT_SEED).unwrap();+ assert_eq!(mlkem_decaps_der(&priv_der, &ct).unwrap(), ss1);+}++#[test]+fn c_bridge_link_keygen_seed_is_usable() {+ let mut seed: *mut u8 = std::ptr::null_mut();+ let mut seed_len: usize = 0;+ let mut bundle: *mut u8 = std::ptr::null_mut();+ let mut bundle_len: usize = 0;+ unsafe {+ assert_eq!(+ crate::c_bridge::pqc_link_keygen(+ &mut seed,+ &mut seed_len,+ &mut bundle,+ &mut bundle_len,+ ),+ 1+ );+ let seed_v = std::slice::from_raw_parts(seed, seed_len).to_vec();+ let bundle_v = std::slice::from_raw_parts(bundle, bundle_len).to_vec();+ crate::c_bridge::pqc_free(seed, seed_len);+ crate::c_bridge::pqc_free(bundle, bundle_len);+ assert_eq!(seed_v.len(), LINK_SEED);+ let (pub_der, _) = mlkem_link_keygen_from_seed(&seed_v).unwrap();+ assert_eq!(&bundle_v[4..], &pub_der[..]);+ }+}