new version
- Commit
b19b6663339f56a68b726b536ce98ca7abfee736- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-25 17:56 UTC (3 months ago)
- Parents
083b976
Diff
FindFamilyiOS.xcodeproj/project.pbxproj
diff --git a/FindFamilyiOS.xcodeproj/project.pbxproj b/FindFamilyiOS.xcodeproj/project.pbxprojindex 6cf0ff2586..b5d3b7df5c 100644--- a/FindFamilyiOS.xcodeproj/project.pbxproj+++ b/FindFamilyiOS.xcodeproj/project.pbxproj@@ -250,7 +250,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 2;+ CURRENT_PROJECT_VERSION = 3; DEVELOPMENT_ASSET_PATHS = "\"FindFamilyiOS/Preview Content\""; DEVELOPMENT_TEAM = M42H545N93; ENABLE_PREVIEWS = YES;@@ -263,7 +263,7 @@ "$(inherited)", "@executable_path/Frameworks", );- MARKETING_VERSION = 2.0;+ MARKETING_VERSION = 3.0; PRODUCT_BUNDLE_IDENTIFIER = cc.findfamily.app.1; PRODUCT_NAME = "Find Family"; PROVISIONING_PROFILE_SPECIFIER = "";@@ -284,7 +284,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 2;+ CURRENT_PROJECT_VERSION = 3; DEVELOPMENT_ASSET_PATHS = "\"FindFamilyiOS/Preview Content\""; DEVELOPMENT_TEAM = M42H545N93; ENABLE_PREVIEWS = YES;@@ -297,7 +297,7 @@ "$(inherited)", "@executable_path/Frameworks", );- MARKETING_VERSION = 2.0;+ MARKETING_VERSION = 3.0; PRODUCT_BUNDLE_IDENTIFIER = cc.findfamily.app.1; PRODUCT_NAME = "Find Family"; PROVISIONING_PROFILE_SPECIFIER = "";
FindFamilyiOS.xcodeproj/project.xcworkspace/xcuserdata/vayun.xcuserdatad/UserInterfaceState.xcuserstate
diff --git a/FindFamilyiOS.xcodeproj/project.xcworkspace/xcuserdata/vayun.xcuserdatad/UserInterfaceState.xcuserstate b/FindFamilyiOS.xcodeproj/project.xcworkspace/xcuserdata/vayun.xcuserdatad/UserInterfaceState.xcuserstateindex bbf1860e90..db3a2d7c86 100644Binary files a/FindFamilyiOS.xcodeproj/project.xcworkspace/xcuserdata/vayun.xcuserdatad/UserInterfaceState.xcuserstate and b/FindFamilyiOS.xcodeproj/project.xcworkspace/xcuserdata/vayun.xcuserdatad/UserInterfaceState.xcuserstate differ
FindFamilyiOS/.DS_Store
diff --git a/FindFamilyiOS/.DS_Store b/FindFamilyiOS/.DS_Storenew file mode 100644index 0000000000..b09bbc9bebBinary files /dev/null and b/FindFamilyiOS/.DS_Store differ
FindFamilyiOS/Crypto/Keccak.swift
diff --git a/FindFamilyiOS/Crypto/Keccak.swift b/FindFamilyiOS/Crypto/Keccak.swiftnew file mode 100644index 0000000000..4f0c645896--- /dev/null+++ b/FindFamilyiOS/Crypto/Keccak.swift@@ -0,0 +1,175 @@+import Foundation++// Keccak-f[1600] and the SHA-3 / SHAKE functions that FIPS 203 (ML-KEM) and+// FIPS 204 (ML-DSA) are built on.+//+// CryptoKit exposes neither SHA-3 nor SHAKE below iOS 26, and the deployment+// target here is iOS 18, so the post-quantum code brings its own. This is a+// straight transcription of FIPS 202 — no shortcuts, no platform assumptions.++enum Keccak {+ // MARK: - Keccak-f[1600] permutation++ private static let roundConstants: [UInt64] = [+ 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000,+ 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,+ 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a,+ 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003,+ 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a,+ 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,+ ]++ /// Rotation offsets ρ, indexed as `x + 5*y`.+ private static let rotationOffsets: [UInt64] = [+ 0, 1, 62, 28, 27,+ 36, 44, 6, 55, 20,+ 3, 10, 43, 25, 39,+ 41, 45, 15, 21, 8,+ 18, 2, 61, 56, 14,+ ]++ @inline(__always)+ private static func rotl(_ x: UInt64, _ n: UInt64) -> UInt64 {+ n == 0 ? x : (x << n) | (x >> (64 - n))+ }++ /// In-place Keccak-f[1600] on a 25-lane state.+ static func permute(_ a: inout [UInt64]) {+ var b = [UInt64](repeating: 0, count: 25)+ var c = [UInt64](repeating: 0, count: 5)+ var d = [UInt64](repeating: 0, count: 5)++ for round in 0..<24 {+ // θ+ for x in 0..<5 {+ c[x] = a[x] ^ a[x + 5] ^ a[x + 10] ^ a[x + 15] ^ a[x + 20]+ }+ for x in 0..<5 {+ d[x] = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1)+ }+ for y in 0..<5 {+ for x in 0..<5 { a[x + 5 * y] ^= d[x] }+ }+ // ρ and π: B[y, 2x+3y] = rotl(A[x, y], r[x, y])+ for y in 0..<5 {+ for x in 0..<5 {+ b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(a[x + 5 * y], rotationOffsets[x + 5 * y])+ }+ }+ // χ+ for y in 0..<5 {+ for x in 0..<5 {+ a[x + 5 * y] = b[x + 5 * y] ^ (~b[(x + 1) % 5 + 5 * y] & b[(x + 2) % 5 + 5 * y])+ }+ }+ // ι+ a[0] ^= roundConstants[round]+ }+ }++ // MARK: - Sponge++ /// Absorbs a complete message, then squeezes on demand. Every use here knows its+ /// input up front, so there's no incremental-absorb path to get wrong.+ struct Sponge {+ private var state = [UInt64](repeating: 0, count: 25)+ private let rate: Int // bytes+ private var block: [UInt8] // current squeeze block+ private var offset: Int // read position within `block`++ init(rate: Int, padByte: UInt8, input: [UInt8]) {+ self.rate = rate+ self.block = []+ self.offset = 0++ // Absorb full blocks, then the padded remainder.+ var padded = input+ let remainder = padded.count % rate+ var tail = [UInt8](repeating: 0, count: rate - remainder)+ tail[0] = padByte+ tail[tail.count - 1] |= 0x80+ padded.append(contentsOf: tail)++ var i = 0+ while i < padded.count {+ absorbBlock(Array(padded[i..<(i + rate)]))+ i += rate+ }+ squeezeBlock()+ }++ private mutating func absorbBlock(_ bytes: [UInt8]) {+ for j in 0..<(rate / 8) {+ var lane: UInt64 = 0+ for b in 0..<8 {+ lane |= UInt64(bytes[j * 8 + b]) << UInt64(8 * b)+ }+ state[j] ^= lane+ }+ Keccak.permute(&state)+ }++ private mutating func squeezeBlock() {+ var out = [UInt8](repeating: 0, count: rate)+ for j in 0..<(rate / 8) {+ let lane = state[j]+ for b in 0..<8 {+ out[j * 8 + b] = UInt8(truncatingIfNeeded: lane >> UInt64(8 * b))+ }+ }+ block = out+ offset = 0+ }++ /// Squeezes exactly `count` bytes, permuting as needed.+ mutating func squeeze(_ count: Int) -> [UInt8] {+ var out = [UInt8]()+ out.reserveCapacity(count)+ var remaining = count+ while remaining > 0 {+ if offset == rate {+ Keccak.permute(&state)+ squeezeBlock()+ }+ let take = min(remaining, rate - offset)+ out.append(contentsOf: block[offset..<(offset + take)])+ offset += take+ remaining -= take+ }+ return out+ }+ }++ // MARK: - Named functions++ static func shake128(_ input: [UInt8], outputCount: Int) -> [UInt8] {+ var s = Sponge(rate: 168, padByte: 0x1F, input: input)+ return s.squeeze(outputCount)+ }++ static func shake256(_ input: [UInt8], outputCount: Int) -> [UInt8] {+ var s = Sponge(rate: 136, padByte: 0x1F, input: input)+ return s.squeeze(outputCount)+ }++ /// Incremental SHAKE128 reader — ML-KEM's matrix sampling rejects candidates,+ /// so it can't know its output length in advance.+ static func shake128Reader(_ input: [UInt8]) -> Sponge {+ Sponge(rate: 168, padByte: 0x1F, input: input)+ }++ /// Incremental SHAKE256 reader — used by ML-DSA rejection sampling.+ static func shake256Reader(_ input: [UInt8]) -> Sponge {+ Sponge(rate: 136, padByte: 0x1F, input: input)+ }++ static func sha3_256(_ input: [UInt8]) -> [UInt8] {+ var s = Sponge(rate: 136, padByte: 0x06, input: input)+ return s.squeeze(32)+ }++ static func sha3_512(_ input: [UInt8]) -> [UInt8] {+ var s = Sponge(rate: 72, padByte: 0x06, input: input)+ return s.squeeze(64)+ }+}
FindFamilyiOS/Crypto/MLDSA65.swift
diff --git a/FindFamilyiOS/Crypto/MLDSA65.swift b/FindFamilyiOS/Crypto/MLDSA65.swiftnew file mode 100644index 0000000000..ff55fd7364--- /dev/null+++ b/FindFamilyiOS/Crypto/MLDSA65.swift@@ -0,0 +1,297 @@+import Foundation++// ML-DSA-65 (FIPS 204) key generation, matching the `fips204` Rust crate used by+// Android's `libe2ee_pqc.so`.+//+// Only KeyGen is implemented: a device's public identity bundle is+// [kemPub ‖ dsaPub], so the ML-DSA half has to be a real, correctly-encoded key+// even though FindFamily itself never signs or verifies with it (the signature+// half exists for Office's roster authentication and is carried here for format+// compatibility). If signing is ever needed on iOS, Sign/Verify go here.+//+// Parameter set ML-DSA-65: q=8380417, n=256, k=6, l=5, eta=4, d=13.++enum MLDSAError: Error {+ case badLength(String)+}++enum MLDSA65 {+ // MARK: - Parameters++ static let n = 256+ static let q: Int32 = 8_380_417+ static let k = 6+ static let l = 5+ static let eta: Int32 = 4+ static let d = 13++ /// 32 + 32*k*(bitlen(q-1) - d) = 32 + 32*6*10.+ static let publicKeyLength = 1952+ /// 128 + 32*(l*4 + k*4 + k*13).+ static let privateKeyLength = 4032+ static let seedLength = 32++ // MARK: - Modular arithmetic++ @inline(__always) private static func addMod(_ a: Int32, _ b: Int32) -> Int32 {+ let s = a + b+ return s >= q ? s - q : s+ }++ @inline(__always) private static func subMod(_ a: Int32, _ b: Int32) -> Int32 {+ let s = a - b+ return s < 0 ? s + q : s+ }++ @inline(__always) private static func mulMod(_ a: Int32, _ b: Int32) -> Int32 {+ Int32((Int(a) * Int(b)) % Int(q))+ }++ private static func powMod(_ base: Int32, _ exp: Int) -> Int32 {+ var result: Int32 = 1+ var b = base+ var e = exp+ while e > 0 {+ if e & 1 == 1 { result = mulMod(result, b) }+ b = mulMod(b, b)+ e >>= 1+ }+ return result+ }++ /// Reverses 8 bits.+ private static func bitRev8(_ x: Int) -> Int {+ var r = 0+ for i in 0..<8 where (x >> i) & 1 == 1 { r |= 1 << (7 - i) }+ return r+ }++ /// zetas[i] = 1753^BitRev8(i) mod q.+ private static let zetas: [Int32] = (0..<256).map { powMod(1753, bitRev8($0)) }++ // MARK: - NTT (full 256-point, so multiplication is plain pointwise)++ /// FIPS 204 Algorithm 41.+ static func ntt(_ w: inout [Int32]) {+ var i = 0+ var len = 128+ while len >= 1 {+ var start = 0+ while start < n {+ i += 1+ let z = zetas[i]+ for j in start..<(start + len) {+ let t = mulMod(z, w[j + len])+ w[j + len] = subMod(w[j], t)+ w[j] = addMod(w[j], t)+ }+ start += 2 * len+ }+ len /= 2+ }+ }++ /// FIPS 204 Algorithm 42.+ static func inverseNTT(_ w: inout [Int32]) {+ var i = 256+ var len = 1+ while len < n {+ var start = 0+ while start < n {+ i -= 1+ let z = q - zetas[i] // -zeta^BitRev8(i)+ for j in start..<(start + len) {+ let t = w[j]+ w[j] = addMod(t, w[j + len])+ w[j + len] = mulMod(z, subMod(t, w[j + len]))+ }+ start += 2 * len+ }+ len *= 2+ }+ // 256^-1 mod q+ for j in 0..<n { w[j] = mulMod(w[j], 8_347_681) }+ }++ // MARK: - Sampling++ /// FIPS 204 Algorithm 30: rejection sampling of a uniform polynomial in NTT form.+ private static func rejNTTPoly(_ seed: [UInt8]) -> [Int32] {+ var xof = Keccak.shake128Reader(seed)+ var a = [Int32](repeating: 0, count: n)+ var j = 0+ while j < n {+ let b = xof.squeeze(3)+ let z = Int32(b[0]) | (Int32(b[1]) << 8) | (Int32(b[2] & 0x7F) << 16)+ if z < q {+ a[j] = z+ j += 1+ }+ }+ return a+ }++ /// FIPS 204 Algorithm 31 with eta = 4: coefficients in [-4, 4].+ private static func rejBoundedPoly(_ seed: [UInt8]) -> [Int32] {+ var xof = Keccak.shake256Reader(seed)+ var a = [Int32](repeating: 0, count: n)+ var j = 0+ // CoeffFromHalfByte for eta=4: b < 9 -> 4 - b, else reject.+ while j < n {+ let z = xof.squeeze(1)[0]+ let lo = Int32(z & 0x0F)+ let hi = Int32(z >> 4)+ if lo < 9 {+ a[j] = 4 - lo+ j += 1+ }+ if hi < 9 && j < n {+ a[j] = 4 - hi+ j += 1+ }+ }+ return a+ }++ /// FIPS 204 Algorithm 32. Note the index order: Â[r,s] from ρ‖s‖r.+ private static func expandA(_ rho: [UInt8]) -> [[[Int32]]] {+ var a = [[[Int32]]]()+ a.reserveCapacity(k)+ for r in 0..<k {+ var row = [[Int32]]()+ row.reserveCapacity(l)+ for s in 0..<l {+ row.append(rejNTTPoly(rho + [UInt8(s), UInt8(r)]))+ }+ a.append(row)+ }+ return a+ }++ /// FIPS 204 Algorithm 33.+ private static func expandS(_ rhoPrime: [UInt8]) -> (s1: [[Int32]], s2: [[Int32]]) {+ var s1 = [[Int32]]()+ for r in 0..<l {+ s1.append(rejBoundedPoly(rhoPrime + [UInt8(r & 0xFF), UInt8((r >> 8) & 0xFF)]))+ }+ var s2 = [[Int32]]()+ for r in 0..<k {+ let idx = r + l+ s2.append(rejBoundedPoly(rhoPrime + [UInt8(idx & 0xFF), UInt8((idx >> 8) & 0xFF)]))+ }+ return (s1, s2)+ }++ // MARK: - Rounding++ /// FIPS 204 Algorithm 35: r -> (r1, r0) with r = r1*2^d + r0, r0 centered.+ private static func power2Round(_ r: Int32) -> (r1: Int32, r0: Int32) {+ let rPlus = r % q+ var r0 = rPlus & ((1 << Int32(d)) - 1)+ if r0 > (1 << Int32(d - 1)) { r0 -= (1 << Int32(d)) }+ let r1 = (rPlus - r0) >> Int32(d)+ return (r1, r0)+ }++ // MARK: - Bit packing++ /// FIPS 204 Algorithm 16: pack coefficients directly in `bits` bits each.+ private static func simpleBitPack(_ w: [Int32], bits: Int) -> [UInt8] {+ packLSBFirst(w.map { UInt32(bitPattern: $0) }, bits: bits)+ }++ /// FIPS 204 Algorithm 17: pack (b - w[i]) in `bits` bits each.+ private static func bitPack(_ w: [Int32], b: Int32, bits: Int) -> [UInt8] {+ packLSBFirst(w.map { UInt32(bitPattern: b - $0) }, bits: bits)+ }++ private static func packLSBFirst(_ values: [UInt32], bits: Int) -> [UInt8] {+ var out = [UInt8](repeating: 0, count: (values.count * bits + 7) / 8)+ var acc: UInt64 = 0+ var accBits = 0+ var pos = 0+ for v in values {+ acc |= UInt64(v & ((1 << UInt32(bits)) - 1)) << UInt64(accBits)+ accBits += bits+ while accBits >= 8 {+ out[pos] = UInt8(acc & 0xFF)+ pos += 1+ acc >>= 8+ accBits -= 8+ }+ }+ if accBits > 0 { out[pos] = UInt8(acc & 0xFF) }+ return out+ }++ // MARK: - KeyGen++ /// FIPS 204 Algorithm 6 (KeyGen_internal). Returns the raw FIPS-encoded key pair.+ static func keyGen(seed xi: [UInt8]) throws -> (publicKey: [UInt8], privateKey: [UInt8]) {+ guard xi.count == seedLength else {+ throw MLDSAError.badLength("ML-DSA seed must be \(seedLength) bytes, got \(xi.count)")+ }+ // (rho, rho', K) <- H(xi ‖ k ‖ l, 128)+ let h = Keccak.shake256(xi + [UInt8(k), UInt8(l)], outputCount: 128)+ let rho = Array(h[0..<32])+ let rhoPrime = Array(h[32..<96])+ let bigK = Array(h[96..<128])++ let aHat = expandA(rho)+ let (s1, s2) = expandS(rhoPrime)++ // t = NTT^-1(Â ∘ NTT(s1)) + s2+ var s1Hat = s1.map { poly -> [Int32] in+ var p = poly.map { $0 < 0 ? $0 + q : $0 }+ ntt(&p)+ return p+ }+ var t = [[Int32]]()+ for r in 0..<k {+ var acc = [Int32](repeating: 0, count: n)+ for s in 0..<l {+ for i in 0..<n {+ acc[i] = addMod(acc[i], mulMod(aHat[r][s][i], s1Hat[s][i]))+ }+ }+ inverseNTT(&acc)+ for i in 0..<n {+ let s2c = s2[r][i] < 0 ? s2[r][i] + q : s2[r][i]+ acc[i] = addMod(acc[i], s2c)+ }+ t.append(acc)+ }+ s1Hat.removeAll()++ // (t1, t0) = Power2Round(t)+ var t1 = [[Int32]]()+ var t0 = [[Int32]]()+ for r in 0..<k {+ var hi = [Int32](repeating: 0, count: n)+ var lo = [Int32](repeating: 0, count: n)+ for i in 0..<n {+ let (a, b) = power2Round(t[r][i])+ hi[i] = a+ lo[i] = b+ }+ t1.append(hi)+ t0.append(lo)+ }++ // pkEncode: rho ‖ SimpleBitPack(t1[i], 10 bits)+ var pk = rho+ for r in 0..<k { pk += simpleBitPack(t1[r], bits: 10) }++ // skEncode: rho ‖ K ‖ tr ‖ BitPack(s1, eta) ‖ BitPack(s2, eta) ‖ BitPack(t0, 2^(d-1))+ let tr = Keccak.shake256(pk, outputCount: 64)+ var sk = rho + bigK + tr+ for r in 0..<l { sk += bitPack(s1[r], b: eta, bits: 4) }+ for r in 0..<k { sk += bitPack(s2[r], b: eta, bits: 4) }+ for r in 0..<k { sk += bitPack(t0[r], b: 1 << Int32(d - 1), bits: d) }++ guard pk.count == publicKeyLength, sk.count == privateKeyLength else {+ throw MLDSAError.badLength("ML-DSA encode produced pk=\(pk.count) sk=\(sk.count)")+ }+ return (pk, sk)+ }+}
FindFamilyiOS/Crypto/MLKEM768.swift
diff --git a/FindFamilyiOS/Crypto/MLKEM768.swift b/FindFamilyiOS/Crypto/MLKEM768.swiftnew file mode 100644index 0000000000..11dbe2aaa5--- /dev/null+++ b/FindFamilyiOS/Crypto/MLKEM768.swift@@ -0,0 +1,462 @@+import Foundation+import Security++// ML-KEM-768 (FIPS 203), matching the `fips203` Rust crate that Android's+// `libe2ee_pqc.so` uses, so ciphertexts and keys interoperate byte-for-byte.+//+// Written out here because CryptoKit's MLKEM768 needs iOS 26 and this app+// targets iOS 18. Parameter set: n=256, q=3329, k=3, eta1=eta2=2, du=10, dv=4.+//+// Naming follows FIPS 203 so the code can be read against the spec:+// K-PKE.KeyGen / K-PKE.Encrypt / K-PKE.Decrypt are the underlying PKE,+// ML-KEM.KeyGen / Encaps / Decaps add the Fujisaki-Okamoto transform.++enum MLKEMError: Error {+ case badLength(String)+}++enum MLKEM768 {+ // MARK: - Parameters++ static let n = 256+ static let q: Int32 = 3329+ static let k = 3+ static let eta1 = 2+ static let eta2 = 2+ static let du = 10+ static let dv = 4++ /// Encapsulation (public) key: 384*k + 32.+ static let ekLength = 1184+ /// Decapsulation (private) key: 768*k + 96.+ static let dkLength = 2400+ /// Ciphertext: 32*(du*k + dv).+ static let ctLength = 1088+ /// Key-generation seed d‖z.+ static let seedLength = 64++ // MARK: - Modular arithmetic (values kept in [0, q))++ @inline(__always) private static func addMod(_ a: Int32, _ b: Int32) -> Int32 {+ let s = a + b+ return s >= q ? s - q : s+ }++ @inline(__always) private static func subMod(_ a: Int32, _ b: Int32) -> Int32 {+ let s = a - b+ return s < 0 ? s + q : s+ }++ @inline(__always) private static func mulMod(_ a: Int32, _ b: Int32) -> Int32 {+ Int32((Int(a) * Int(b)) % Int(q))+ }++ private static func powMod(_ base: Int32, _ exp: Int) -> Int32 {+ var result: Int32 = 1+ var b = base+ var e = exp+ while e > 0 {+ if e & 1 == 1 { result = mulMod(result, b) }+ b = mulMod(b, b)+ e >>= 1+ }+ return result+ }++ /// Reverses the low 7 bits — the NTT's zeta ordering.+ private static func bitRev7(_ x: Int) -> Int {+ var r = 0+ for i in 0..<7 where (x >> i) & 1 == 1 { r |= 1 << (6 - i) }+ return r+ }++ /// zetas[i] = 17^BitRev7(i) mod q.+ private static let zetas: [Int32] = (0..<128).map { powMod(17, bitRev7($0)) }++ // MARK: - Number-theoretic transform++ /// FIPS 203 Algorithm 9.+ static func ntt(_ f: inout [Int32]) {+ var i = 1+ var len = 128+ while len >= 2 {+ var start = 0+ while start < n {+ let zeta = zetas[i]+ i += 1+ for j in start..<(start + len) {+ let t = mulMod(zeta, f[j + len])+ f[j + len] = subMod(f[j], t)+ f[j] = addMod(f[j], t)+ }+ start += 2 * len+ }+ len /= 2+ }+ }++ /// FIPS 203 Algorithm 10.+ static func inverseNTT(_ f: inout [Int32]) {+ var i = 127+ var len = 2+ while len <= 128 {+ var start = 0+ while start < n {+ let zeta = zetas[i]+ i -= 1+ for j in start..<(start + len) {+ let t = f[j]+ f[j] = addMod(t, f[j + len])+ f[j + len] = mulMod(zeta, subMod(f[j + len], t))+ }+ start += 2 * len+ }+ len *= 2+ }+ // 128^-1 mod q+ for j in 0..<n { f[j] = mulMod(f[j], 3303) }+ }++ /// FIPS 203 Algorithms 11 + 12: pointwise product in the NTT domain.+ static func multiplyNTTs(_ a: [Int32], _ b: [Int32]) -> [Int32] {+ var c = [Int32](repeating: 0, count: n)+ for i in 0..<128 {+ // gamma = zeta^(2*BitRev7(i)+1)+ let gamma = mulMod(mulMod(zetas[i], zetas[i]), 17)+ let a0 = a[2 * i], a1 = a[2 * i + 1]+ let b0 = b[2 * i], b1 = b[2 * i + 1]+ c[2 * i] = addMod(mulMod(a0, b0), mulMod(mulMod(a1, b1), gamma))+ c[2 * i + 1] = addMod(mulMod(a0, b1), mulMod(a1, b0))+ }+ return c+ }++ private static func polyAdd(_ a: [Int32], _ b: [Int32]) -> [Int32] {+ var out = [Int32](repeating: 0, count: n)+ for i in 0..<n { out[i] = addMod(a[i], b[i]) }+ return out+ }++ private static func polySub(_ a: [Int32], _ b: [Int32]) -> [Int32] {+ var out = [Int32](repeating: 0, count: n)+ for i in 0..<n { out[i] = subMod(a[i], b[i]) }+ return out+ }++ // MARK: - Compression and serialization++ @inline(__always) static func compress(_ x: Int32, _ d: Int) -> Int32 {+ Int32(((Int(x) << d) + 1664) / Int(q)) & Int32((1 << d) - 1)+ }++ @inline(__always) static func decompress(_ y: Int32, _ d: Int) -> Int32 {+ Int32((Int(y) * Int(q) + (1 << (d - 1))) >> d)+ }++ /// FIPS 203 Algorithm 5: pack 256 d-bit coefficients little-endian.+ static func byteEncode(_ f: [Int32], _ d: Int) -> [UInt8] {+ var out = [UInt8](repeating: 0, count: 32 * d)+ var acc: UInt32 = 0+ var accBits = 0+ var pos = 0+ for i in 0..<n {+ acc |= UInt32(f[i]) << UInt32(accBits)+ accBits += d+ while accBits >= 8 {+ out[pos] = UInt8(acc & 0xFF)+ pos += 1+ acc >>= 8+ accBits -= 8+ }+ }+ return out+ }++ /// FIPS 203 Algorithm 6. For d = 12 the values are reduced mod q.+ static func byteDecode(_ bytes: ArraySlice<UInt8>, _ d: Int) -> [Int32] {+ var f = [Int32](repeating: 0, count: n)+ let mask: UInt32 = (1 << UInt32(d)) - 1+ var acc: UInt32 = 0+ var accBits = 0+ var it = bytes.startIndex+ for i in 0..<n {+ while accBits < d {+ acc |= UInt32(bytes[it]) << UInt32(accBits)+ it += 1+ accBits += 8+ }+ var v = acc & mask+ acc >>= UInt32(d)+ accBits -= d+ if d == 12 { v %= UInt32(q) }+ f[i] = Int32(v)+ }+ return f+ }++ // MARK: - Sampling++ /// FIPS 203 Algorithm 7: rejection-sample a polynomial already in NTT form.+ static func sampleNTT(_ seed: [UInt8]) -> [Int32] {+ var xof = Keccak.shake128Reader(seed)+ var a = [Int32](repeating: 0, count: n)+ var j = 0+ while j < n {+ let c = xof.squeeze(3)+ let d1 = Int32(c[0]) | (Int32(c[1] & 0x0F) << 8)+ let d2 = Int32(c[1] >> 4) | (Int32(c[2]) << 4)+ if d1 < q {+ a[j] = d1+ j += 1+ }+ if d2 < q && j < n {+ a[j] = d2+ j += 1+ }+ }+ return a+ }++ /// FIPS 203 Algorithm 8: centered binomial distribution.+ static func samplePolyCBD(_ bytes: [UInt8], eta: Int) -> [Int32] {+ var f = [Int32](repeating: 0, count: n)+ @inline(__always) func bit(_ i: Int) -> Int32 {+ Int32((bytes[i >> 3] >> UInt8(i & 7)) & 1)+ }+ for i in 0..<n {+ var x: Int32 = 0+ var y: Int32 = 0+ for j in 0..<eta {+ x += bit(2 * i * eta + j)+ y += bit(2 * i * eta + eta + j)+ }+ f[i] = subMod(x, y)+ }+ return f+ }++ /// PRF_eta(s, b) = SHAKE256(s ‖ b, 64*eta).+ private static func prf(_ eta: Int, _ s: [UInt8], _ b: UInt8) -> [UInt8] {+ Keccak.shake256(s + [b], outputCount: 64 * eta)+ }++ /// Builds the matrix Â. FIPS 203 samples Â[i,j] from ρ‖j‖i (note the index order).+ private static func expandMatrix(_ rho: [UInt8]) -> [[[Int32]]] {+ var a = [[[Int32]]]()+ a.reserveCapacity(k)+ for i in 0..<k {+ var row = [[Int32]]()+ row.reserveCapacity(k)+ for j in 0..<k {+ row.append(sampleNTT(rho + [UInt8(j), UInt8(i)]))+ }+ a.append(row)+ }+ return a+ }++ // MARK: - K-PKE++ /// FIPS 203 Algorithm 13.+ static func kpkeKeyGen(d: [UInt8]) -> (ekPKE: [UInt8], dkPKE: [UInt8]) {+ let g = Keccak.sha3_512(d + [UInt8(k)])+ let rho = Array(g[0..<32])+ let sigma = Array(g[32..<64])++ let aHat = expandMatrix(rho)++ var counter: UInt8 = 0+ var s = [[Int32]]()+ for _ in 0..<k {+ s.append(samplePolyCBD(prf(eta1, sigma, counter), eta: eta1))+ counter += 1+ }+ var e = [[Int32]]()+ for _ in 0..<k {+ e.append(samplePolyCBD(prf(eta1, sigma, counter), eta: eta1))+ counter += 1+ }+ for i in 0..<k {+ ntt(&s[i])+ ntt(&e[i])+ }++ // t̂ = Â ∘ ŝ + ê+ var t = [[Int32]]()+ for i in 0..<k {+ var acc = [Int32](repeating: 0, count: n)+ for j in 0..<k {+ acc = polyAdd(acc, multiplyNTTs(aHat[i][j], s[j]))+ }+ t.append(polyAdd(acc, e[i]))+ }++ var ekPKE = [UInt8]()+ for i in 0..<k { ekPKE += byteEncode(t[i], 12) }+ ekPKE += rho++ var dkPKE = [UInt8]()+ for i in 0..<k { dkPKE += byteEncode(s[i], 12) }++ return (ekPKE, dkPKE)+ }++ /// FIPS 203 Algorithm 14.+ static func kpkeEncrypt(ekPKE: [UInt8], message: [UInt8], randomness r: [UInt8]) -> [UInt8] {+ var t = [[Int32]]()+ for i in 0..<k {+ t.append(byteDecode(ekPKE[(384 * i)..<(384 * (i + 1))], 12))+ }+ let rho = Array(ekPKE[(384 * k)..<(384 * k + 32)])+ let aHat = expandMatrix(rho)++ var counter: UInt8 = 0+ var y = [[Int32]]()+ for _ in 0..<k {+ y.append(samplePolyCBD(prf(eta1, r, counter), eta: eta1))+ counter += 1+ }+ var e1 = [[Int32]]()+ for _ in 0..<k {+ e1.append(samplePolyCBD(prf(eta2, r, counter), eta: eta2))+ counter += 1+ }+ let e2 = samplePolyCBD(prf(eta2, r, counter), eta: eta2)++ for i in 0..<k { ntt(&y[i]) }++ // u = NTT^-1(Â^T ∘ ŷ) + e1+ var u = [[Int32]]()+ for i in 0..<k {+ var acc = [Int32](repeating: 0, count: n)+ for j in 0..<k {+ acc = polyAdd(acc, multiplyNTTs(aHat[j][i], y[j]))+ }+ inverseNTT(&acc)+ u.append(polyAdd(acc, e1[i]))+ }++ // v = NTT^-1(t̂^T ∘ ŷ) + e2 + Decompress_1(m)+ var v = [Int32](repeating: 0, count: n)+ for i in 0..<k {+ v = polyAdd(v, multiplyNTTs(t[i], y[i]))+ }+ inverseNTT(&v)+ v = polyAdd(v, e2)+ let mu = byteDecode(message[message.startIndex...], 1).map { decompress($0, 1) }+ v = polyAdd(v, mu)++ var c = [UInt8]()+ for i in 0..<k {+ c += byteEncode(u[i].map { compress($0, du) }, du)+ }+ c += byteEncode(v.map { compress($0, dv) }, dv)+ return c+ }++ /// FIPS 203 Algorithm 15.+ static func kpkeDecrypt(dkPKE: [UInt8], ciphertext c: [UInt8]) -> [UInt8] {+ let c1Len = 32 * du * k+ var u = [[Int32]]()+ for i in 0..<k {+ let chunk = c[(32 * du * i)..<(32 * du * (i + 1))]+ u.append(byteDecode(chunk, du).map { decompress($0, du) })+ }+ let v = byteDecode(c[c1Len...], dv).map { decompress($0, dv) }++ var s = [[Int32]]()+ for i in 0..<k {+ s.append(byteDecode(dkPKE[(384 * i)..<(384 * (i + 1))], 12))+ }++ // w = v - NTT^-1(ŝ^T ∘ NTT(u))+ var acc = [Int32](repeating: 0, count: n)+ for i in 0..<k {+ var ui = u[i]+ ntt(&ui)+ acc = polyAdd(acc, multiplyNTTs(s[i], ui))+ }+ inverseNTT(&acc)+ let w = polySub(v, acc)++ return byteEncode(w.map { compress($0, 1) }, 1)+ }++ // MARK: - ML-KEM++ /// FIPS 203 Algorithm 16 (KeyGen_internal). `seed` is d‖z (64 bytes).+ static func keyGen(seed: [UInt8]) throws -> (ek: [UInt8], dk: [UInt8]) {+ guard seed.count == seedLength else {+ throw MLKEMError.badLength("ML-KEM seed must be \(seedLength) bytes, got \(seed.count)")+ }+ let d = Array(seed[0..<32])+ let z = Array(seed[32..<64])+ let (ekPKE, dkPKE) = kpkeKeyGen(d: d)+ // dk = dk_PKE ‖ ek ‖ H(ek) ‖ z+ let dk = dkPKE + ekPKE + Keccak.sha3_256(ekPKE) + z+ return (ekPKE, dk)+ }++ /// Generates a fresh random seed d‖z.+ static func randomSeed() throws -> [UInt8] {+ var seed = [UInt8](repeating: 0, count: seedLength)+ let status = SecRandomCopyBytes(kSecRandomDefault, seedLength, &seed)+ guard status == errSecSuccess else {+ throw MLKEMError.badLength("SecRandomCopyBytes failed (\(status))")+ }+ return seed+ }++ /// FIPS 203 Algorithm 17 (Encaps_internal) with caller-supplied message — deterministic, for tests.+ static func encapsulate(ek: [UInt8], message m: [UInt8]) throws -> (ciphertext: [UInt8], sharedSecret: [UInt8]) {+ guard ek.count == ekLength else {+ throw MLKEMError.badLength("ML-KEM public key must be \(ekLength) bytes, got \(ek.count)")+ }+ let g = Keccak.sha3_512(m + Keccak.sha3_256(ek))+ let sharedSecret = Array(g[0..<32])+ let r = Array(g[32..<64])+ let c = kpkeEncrypt(ekPKE: ek, message: m, randomness: r)+ return (c, sharedSecret)+ }++ /// FIPS 203 Algorithm 20 (Encaps): random message.+ static func encapsulate(ek: [UInt8]) throws -> (ciphertext: [UInt8], sharedSecret: [UInt8]) {+ var m = [UInt8](repeating: 0, count: 32)+ let status = SecRandomCopyBytes(kSecRandomDefault, 32, &m)+ guard status == errSecSuccess else {+ throw MLKEMError.badLength("SecRandomCopyBytes failed (\(status))")+ }+ return try encapsulate(ek: ek, message: m)+ }++ /// FIPS 203 Algorithm 18 / 21 (Decaps), including implicit rejection.+ static func decapsulate(dk: [UInt8], ciphertext c: [UInt8]) throws -> [UInt8] {+ guard dk.count == dkLength else {+ throw MLKEMError.badLength("ML-KEM private key must be \(dkLength) bytes, got \(dk.count)")+ }+ guard c.count == ctLength else {+ throw MLKEMError.badLength("ML-KEM ciphertext must be \(ctLength) bytes, got \(c.count)")+ }+ let dkPKE = Array(dk[0..<(384 * k)])+ let ekPKE = Array(dk[(384 * k)..<(768 * k + 32)])+ let h = Array(dk[(768 * k + 32)..<(768 * k + 64)])+ let z = Array(dk[(768 * k + 64)..<(768 * k + 96)])++ let mPrime = kpkeDecrypt(dkPKE: dkPKE, ciphertext: c)+ let g = Keccak.sha3_512(mPrime + h)+ var kPrime = Array(g[0..<32])+ let rPrime = Array(g[32..<64])+ let kBar = Keccak.shake256(z + c, outputCount: 32)++ let cPrime = kpkeEncrypt(ekPKE: ekPKE, message: mPrime, randomness: rPrime)+ // Implicit rejection on re-encryption mismatch, in constant time.+ var diff: UInt8 = 0+ for i in 0..<ctLength { diff |= c[i] ^ cPrime[i] }+ let mismatch = Int32(bitPattern: (UInt32(diff) &+ 0xFF) >> 8) // 0 if equal, 1 if not+ let maskByte = UInt8(truncatingIfNeeded: 0 &- mismatch)+ for i in 0..<32 {+ kPrime[i] = (kPrime[i] & ~maskByte) | (kBar[i] & maskByte)+ }+ return kPrime+ }+}
FindFamilyiOS/Crypto/PQCCrypto.swift
diff --git a/FindFamilyiOS/Crypto/PQCCrypto.swift b/FindFamilyiOS/Crypto/PQCCrypto.swiftindex dc8712094e..c04398b853 100644--- a/FindFamilyiOS/Crypto/PQCCrypto.swift+++ b/FindFamilyiOS/Crypto/PQCCrypto.swift@@ -1,5 +1,6 @@ import Foundation import CryptoKit+import Security // MARK: - PQC Bundle framing (identical to Kotlin Pqc.kt) //@@ -21,41 +22,23 @@ enum PQCBundle { return out } - static func lenPrefixSingle(_ a: Data) -> Data {- // Same as above but second piece empty — not used but kept for symmetry.- var out = Data()- out.reserveCapacity(4 + a.count)- let alen = UInt32(a.count).bigEndian- withUnsafeBytes(of: alen) { out.append(contentsOf: $0) }- out.append(a)- return out- }- static func unLenPrefix(_ x: Data) -> (Data, Data)? { guard x.count >= 4 else { return nil }- let len = x.withUnsafeBytes { ptr -> UInt32 in- var v: UInt32 = 0- withUnsafeMutableBytes(of: &v) { dest in- dest.copyMemory(from: UnsafeRawBufferPointer(start: ptr.baseAddress, count: 4))- }- return UInt32(bigEndian: v)- }- let lenI = Int(len)- guard 4 + lenI <= x.count else { return nil }- let first = x.subdata(in: 4..<(4 + lenI))- let second = x.subdata(in: (4 + lenI)..<x.count)+ let base = x.startIndex+ let len = (Int(x[base]) << 24) | (Int(x[base + 1]) << 16) | (Int(x[base + 2]) << 8) | Int(x[base + 3])+ guard len >= 0, 4 + len <= x.count else { return nil }+ let first = x.subdata(in: (base + 4)..<(base + 4 + len))+ let second = x.subdata(in: (base + 4 + len)..<x.endIndex) return (first, second) } // MARK: - Public/Private bundle builders static func buildPublic(kemPub: Data, dsaPub: Data) -> Data {- // Same layout Office uses for directory: [4B kemLen][kem][dsa] lenPrefix(kemPub, dsaPub) } static func buildPrivate(kemPriv: Data, dsaPriv: Data) -> Data {- // Ephemeral links store private as same framing: [4B kemPrivLen][kemPriv][dsaPriv] lenPrefix(kemPriv, dsaPriv) } @@ -91,12 +74,10 @@ enum PQCAES { /// Encrypts with `key` (32 bytes), returns `iv(12) + ciphertext||tag`. static func seal(key: Data, plaintext: Data) throws -> Data {- // CryptoKit expects 32-byte key for AES256. guard key.count == 32 else { throw NSError(domain: "pqc_aes", code: -1, userInfo: [NSLocalizedDescriptionKey: "key must be 32 bytes"]) } let symKey = SymmetricKey(data: key) let nonce = AES.GCM.Nonce() // random 12 bytes let sealed = try AES.GCM.seal(plaintext, using: symKey, nonce: nonce)- // sealed.ciphertext + sealed.tag (16). We manually prepend iv (nonce) to mimic Kotlin's E2ee.aesEncrypt. var out = Data() out.reserveCapacity(12 + sealed.ciphertext.count + sealed.tag.count) out.append(Data(nonce))@@ -109,17 +90,15 @@ enum PQCAES { static func open(key: Data, sealed: Data) throws -> Data { guard key.count == 32 else { throw NSError(domain: "pqc_aes", code: -1, userInfo: [NSLocalizedDescriptionKey: "key must be 32 bytes"]) } guard sealed.count >= ivLen + 16 else { throw NSError(domain: "pqc_aes", code: -2, userInfo: [NSLocalizedDescriptionKey: "sealed too short"]) }- let iv = sealed.subdata(in: 0..<ivLen)- let ctAndTag = sealed.subdata(in: ivLen..<sealed.count)- // AES.GCM last 16 bytes = tag+ let iv = sealed.subdata(in: sealed.startIndex..<(sealed.startIndex + ivLen))+ let ctAndTag = sealed.subdata(in: (sealed.startIndex + ivLen)..<sealed.endIndex) guard ctAndTag.count >= 16 else { throw NSError(domain: "pqc_aes", code: -3) }- let tag = ctAndTag.subdata(in: (ctAndTag.count - 16)..<ctAndTag.count)- let ct = ctAndTag.subdata(in: 0..<(ctAndTag.count - 16))+ let tag = ctAndTag.subdata(in: (ctAndTag.endIndex - 16)..<ctAndTag.endIndex)+ let ct = ctAndTag.subdata(in: ctAndTag.startIndex..<(ctAndTag.endIndex - 16)) let symKey = SymmetricKey(data: key) let nonce = try AES.GCM.Nonce(data: iv) let sealedBox = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ct, tag: tag)- let plain = try AES.GCM.open(sealedBox, using: symKey)- return plain+ return try AES.GCM.open(sealedBox, using: symKey) } } @@ -132,235 +111,173 @@ enum PQCSecurityCode { } } -// MARK: - PQC Rust bridge (C exports)+// MARK: - DER encoding (Bouncy Castle 1.85 layouts, mirrored from the Kotlin/Rust side) //-// If the Rust lib `libe2ee_pqc.a` is linked as an XCFramework, these symbols exist.-// If not linked (simulator without framework), calls return 0 and the Swift layer-// treats PQC as unavailable (graceful fallback to RSA).--// C functions exported from e2ee_pqc/src/c_bridge.rs-@_silgen_name("pqc_free")-func pqc_free(_ ptr: UnsafeMutablePointer<UInt8>?, _ len: Int)--@_silgen_name("pqc_secure_zero")-func pqc_secure_zero(_ ptr: UnsafeMutablePointer<UInt8>?, _ len: Int)--@_silgen_name("pqc_kem_keygen")-func pqc_kem_keygen(- _ pub_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ pub_len_out: UnsafeMutablePointer<Int>,- _ priv_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ priv_len_out: UnsafeMutablePointer<Int>-) -> Int32--@_silgen_name("pqc_dsa_keygen")-func pqc_dsa_keygen(- _ pub_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ pub_len_out: UnsafeMutablePointer<Int>,- _ priv_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ priv_len_out: UnsafeMutablePointer<Int>-) -> Int32--@_silgen_name("pqc_identity_keygen")-func pqc_identity_keygen(- _ pub_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ pub_bundle_len_out: UnsafeMutablePointer<Int>,- _ priv_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ priv_bundle_len_out: UnsafeMutablePointer<Int>-) -> Int32--@_silgen_name("pqc_link_keygen")-func pqc_link_keygen(- _ seed_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ seed_len_out: UnsafeMutablePointer<Int>,- _ pub_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ pub_bundle_len_out: UnsafeMutablePointer<Int>-) -> Int32--@_silgen_name("pqc_link_pub_from_seed")-func pqc_link_pub_from_seed(- _ seed: UnsafePointer<UInt8>?, _ seed_len: Int,- _ pub_bundle_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ pub_bundle_len_out: UnsafeMutablePointer<Int>-) -> Int32--@_silgen_name("pqc_kem_encaps")-func pqc_kem_encaps(- _ kem_pub: UnsafePointer<UInt8>?, _ kem_pub_len: Int,- _ ct_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ ct_len_out: UnsafeMutablePointer<Int>,- _ ss_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ ss_len_out: UnsafeMutablePointer<Int>-) -> Int32--@_silgen_name("pqc_kem_decaps")-func pqc_kem_decaps(- _ kem_priv: UnsafePointer<UInt8>?, _ kem_priv_len: Int,- _ ct: UnsafePointer<UInt8>?, _ ct_len: Int,- _ ss_out: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>,- _ ss_len_out: UnsafeMutablePointer<Int>-) -> Int32--@_silgen_name("pqc_security_code")-func pqc_security_code_c(- _ my_bundle: UnsafePointer<UInt8>?, _ my_bundle_len: Int,- _ their_bundle: UnsafePointer<UInt8>?, _ their_bundle_len: Int,- _ out: UnsafeMutablePointer<UInt8>?, _ out_len: Int-) -> Int32+// The prefixes are fixed because ML-KEM/ML-DSA keys are fixed-size, so the whole+// DER is prefix ‖ raw. These byte arrays are copied verbatim from+// `library/e2ee-p2p/src/main/rust/src/lib.rs` so the two sides agree exactly.++enum PQCDer {+ /// SPKI prefix = SEQUENCE, AlgorithmIdentifier(OID), BIT STRING header (+ unused = 00).+ static let kemPubPrefix: [UInt8] = [+ 0x30, 0x82, 0x04, 0xb2, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04,+ 0x02, 0x03, 0x82, 0x04, 0xa1, 0x00,+ ]+ static let dsaPubPrefix: [UInt8] = [+ 0x30, 0x82, 0x07, 0xb2, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03,+ 0x12, 0x03, 0x82, 0x07, 0xa1, 0x00,+ ]+ /// PKCS#8 prefix up to and including the seed OCTET STRING header.+ static let kemPrivPrefix: [UInt8] = [+ 0x30, 0x82, 0x09, 0xbe, 0x02, 0x01, 0x00, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,+ 0x03, 0x04, 0x04, 0x02, 0x04, 0x82, 0x09, 0xaa, 0x30, 0x82, 0x09, 0xa6, 0x04, 0x40,+ ]+ /// expandedKey OCTET STRING header.+ static let kemPrivMid: [UInt8] = [0x04, 0x82, 0x09, 0x60]+ static let dsaPrivPrefix: [UInt8] = [+ 0x30, 0x82, 0x0f, 0xfe, 0x02, 0x01, 0x00, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,+ 0x03, 0x04, 0x03, 0x12, 0x04, 0x82, 0x0f, 0xea, 0x30, 0x82, 0x0f, 0xe6, 0x04, 0x20,+ ]+ static let dsaPrivMid: [UInt8] = [0x04, 0x82, 0x0f, 0xc0]++ static func wrapKemPublic(_ ek: [UInt8]) -> Data { Data(kemPubPrefix + ek) }+ static func wrapDsaPublic(_ pk: [UInt8]) -> Data { Data(dsaPubPrefix + pk) }++ /// BC's seed+expanded "both" form: prefix ‖ seed ‖ mid ‖ expandedKey.+ static func wrapKemPrivate(seed: [UInt8], expanded: [UInt8]) -> Data {+ Data(kemPrivPrefix + seed + kemPrivMid + expanded)+ }++ static func wrapDsaPrivate(seed: [UInt8], expanded: [UInt8]) -> Data {+ Data(dsaPrivPrefix + seed + dsaPrivMid + expanded)+ }++ /// A raw public key is the trailing `rawLength` bytes of the SPKI DER.+ static func rawPublic(_ der: Data, rawLength: Int) -> [UInt8]? {+ guard der.count >= rawLength else { return nil }+ return Array(der.suffix(rawLength))+ }++ /// The expanded private key is the trailing `expandedLength` bytes of the PKCS#8 DER.+ static func expandedPrivate(_ der: Data, expandedLength: Int) -> [UInt8]? {+ guard der.count >= expandedLength else { return nil }+ return Array(der.suffix(expandedLength))+ }+} // MARK: - High-level PQC ops that mirror Kotlin Pqc.encryptTo / decrypt enum PQCCrypto {+ /// SP 800-56A single-step KDF with SHA-256 and empty OtherInfo — what Bouncy Castle's+ /// `KEMGenerateSpec(pub, "AES")` applies by default, so derived AES keys match the+ /// already-deployed Android ciphertexts. key = SHA-256(BE32(1) ‖ Z).+ static func concatKDF(_ z: [UInt8]) -> Data {+ var hasher = SHA256()+ withUnsafeBytes(of: UInt32(1).bigEndian) { hasher.update(bufferPointer: $0) }+ hasher.update(data: Data(z))+ return Data(hasher.finalize())+ }+ /// Encrypts `plaintext` to a recipient's public PQC bundle (from PQCBundle.buildPublic). /// Layout sealed = [4B encapLen BE][encap(1088)][aes] where aes = [12B iv][ct||tag], /// identical to Kotlin's Pqc.encryptTo (which does encaps + E2ee.aesEncrypt). static func encryptTo(bundle: Data, plaintext: Data) throws -> Data {- guard let (kemPub, _) = PQCBundle.splitPublic(bundle) else {+ guard let (kemPubDer, _) = PQCBundle.splitPublic(bundle),+ let ek = PQCDer.rawPublic(kemPubDer, rawLength: MLKEM768.ekLength) else { throw NSError(domain: "pqc", code: -1, userInfo: [NSLocalizedDescriptionKey: "invalid PQC bundle"]) }- // Use C bridge if available, otherwise throw to signal PQC unavailable.- // The Rust lib may not be linked on simulator — try and fall back.- if let sealed = try? encryptToViaNative(kemPub: kemPub, plaintext: plaintext) {- return sealed- }- // If native not linked, throw — caller treats as PQC unavailable.- throw NSError(domain: "pqc", code: -10, userInfo: [NSLocalizedDescriptionKey: "PQC native not available"])+ let result = try MLKEM768.encapsulate(ek: ek)+ let aes = try PQCAES.seal(key: concatKDF(result.sharedSecret), plaintext: plaintext)+ return PQCBundle.buildSealed(encap: Data(result.ciphertext), aes: aes) } - /// Decrypts sealed blob produced by `encryptTo` using our KEM private DER.+ /// Decrypts a sealed blob produced by `encryptTo` using our KEM private DER. static func decrypt(kemPrivateDer: Data, sealed: Data) throws -> Data { guard let (encap, aes) = PQCBundle.splitSealed(sealed) else { throw NSError(domain: "pqc", code: -2, userInfo: [NSLocalizedDescriptionKey: "invalid sealed blob"]) }- // Native decaps- let ss: Data- if let s = try? decapsViaNative(kemPrivateDer: kemPrivateDer, encap: encap) {- ss = s- } else {- throw NSError(domain: "pqc", code: -11, userInfo: [NSLocalizedDescriptionKey: "PQC native decaps not available"])+ guard let dk = PQCDer.expandedPrivate(kemPrivateDer, expandedLength: MLKEM768.dkLength) else {+ throw NSError(domain: "pqc", code: -3, userInfo: [NSLocalizedDescriptionKey: "invalid ML-KEM private key"]) }- return try PQCAES.open(key: ss, sealed: aes)+ let sharedSecret = try MLKEM768.decapsulate(dk: dk, ciphertext: Array(encap))+ return try PQCAES.open(key: concatKDF(sharedSecret), sealed: aes) } - // Convenience: decrypt using private bundle [4B kemPrivLen][kemPriv][dsaPriv]- // (mirrors how ephemeral links store private bundle).+ /// Decrypt using a private bundle [4B kemPrivLen][kemPriv][dsaPriv]+ /// (how ephemeral share links store their private half). static func decryptWithPrivateBundle(privateBundle: Data, sealed: Data) throws -> Data { guard let (kemPriv, _) = PQCBundle.splitPrivate(privateBundle) else {- throw NSError(domain: "pqc", code: -3, userInfo: [NSLocalizedDescriptionKey: "invalid private bundle"])+ throw NSError(domain: "pqc", code: -4, userInfo: [NSLocalizedDescriptionKey: "invalid private bundle"]) } return try decrypt(kemPrivateDer: kemPriv, sealed: sealed) } - // MARK: - Native wrappers-- private static func encryptToViaNative(kemPub: Data, plaintext: Data) throws -> Data {- var ctPtr: UnsafeMutablePointer<UInt8>? = nil- var ctLen: Int = 0- var ssPtr: UnsafeMutablePointer<UInt8>? = nil- var ssLen: Int = 0+ /// Generates a full identity: ML-KEM-768 + ML-DSA-65, DER-wrapped and bundled.+ ///+ /// The private DER carries BC's seed+expanded form, so the 2400-byte decapsulation+ /// key sits at the tail exactly where Android and the web share page look for it.+ static func generateIdentity() throws -> (publicBundle: Data, privateBundle: Data) {+ let kemSeed = try MLKEM768.randomSeed()+ let kem = try MLKEM768.keyGen(seed: kemSeed) - let ok: Int32 = kemPub.withUnsafeBytes { pubBuf in- pqc_kem_encaps(- pubBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), pubBuf.count,- &ctPtr, &ctLen,- &ssPtr, &ssLen- )- }- guard ok == 1, let cPtr = ctPtr, let sPtr = ssPtr else {- throw NSError(domain: "pqc", code: -4, userInfo: [NSLocalizedDescriptionKey: "encaps failed (native not linked?)"])+ var dsaSeed = [UInt8](repeating: 0, count: MLDSA65.seedLength)+ let status = SecRandomCopyBytes(kSecRandomDefault, MLDSA65.seedLength, &dsaSeed)+ guard status == errSecSuccess else {+ throw NSError(domain: "pqc", code: -5, userInfo: [NSLocalizedDescriptionKey: "SecRandomCopyBytes failed (\(status))"]) }- // Ensure free even on throw- defer {- pqc_free(cPtr, ctLen)- pqc_secure_zero(sPtr, ssLen)- pqc_free(sPtr, ssLen)- }- let encap = Data(bytes: cPtr, count: ctLen)- let ss = Data(bytes: sPtr, count: ssLen)- let aes = try PQCAES.seal(key: ss, plaintext: plaintext)- return PQCBundle.buildSealed(encap: encap, aes: aes)+ let dsa = try MLDSA65.keyGen(seed: dsaSeed)++ let publicBundle = PQCBundle.buildPublic(+ kemPub: PQCDer.wrapKemPublic(kem.ek),+ dsaPub: PQCDer.wrapDsaPublic(dsa.publicKey)+ )+ let privateBundle = PQCBundle.buildPrivate(+ kemPriv: PQCDer.wrapKemPrivate(seed: kemSeed, expanded: kem.dk),+ dsaPriv: PQCDer.wrapDsaPrivate(seed: dsaSeed, expanded: dsa.privateKey)+ )+ return (publicBundle, privateBundle) } - private static func decapsViaNative(kemPrivateDer: Data, encap: Data) throws -> Data {- var ssPtr: UnsafeMutablePointer<UInt8>? = nil- var ssLen: Int = 0- let ok: Int32 = kemPrivateDer.withUnsafeBytes { privBuf in- encap.withUnsafeBytes { ctBuf in- pqc_kem_decaps(- privBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), privBuf.count,- ctBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), ctBuf.count,- &ssPtr, &ssLen- )- }- }- guard ok == 1, let sPtr = ssPtr else {- throw NSError(domain: "pqc", code: -5, userInfo: [NSLocalizedDescriptionKey: "decaps failed"])- }- defer {- pqc_secure_zero(sPtr, ssLen)- pqc_free(sPtr, ssLen)- }- return Data(bytes: sPtr, count: ssLen)- }-- /// Generates a full identity (public bundle + private bundle) via Rust. Falls back to error if native not linked.- static func generateIdentity() throws -> (publicBundle: Data, privateBundle: Data) {- var pubPtr: UnsafeMutablePointer<UInt8>? = nil- var pubLen: Int = 0- var privPtr: UnsafeMutablePointer<UInt8>? = nil- var privLen: Int = 0- let ok = pqc_identity_keygen(&pubPtr, &pubLen, &privPtr, &privLen)- guard ok == 1, let pb = pubPtr, let pr = privPtr else {- throw NSError(domain: "pqc", code: -6, userInfo: [NSLocalizedDescriptionKey: "identity keygen failed (native not linked?)"])- }- defer {- // Don't free bundle here — copy first, free after.- // Private bundle contains secrets: zero then free.- // Public bundle freed after copy.- // Caller's Data owns copy.- }- let pubData = Data(bytes: pb, count: pubLen)- let privData = Data(bytes: pr, count: privLen)- pqc_free(pb, pubLen)- pqc_secure_zero(pr, privLen)- pqc_free(pr, privLen)- return (pubData, privData)- }+ /// Length of a share-link seed. A link carries only this in its URL fragment (`#s=`),+ /// so it is the link's whole secret and both platforms must expand it identically.+ static let linkSeedLength = 32 /// Generates a share-link key: a 32-byte ML-KEM seed plus the ML-KEM-only public bundle /// it derives. The seed is the link's whole secret — it is what goes in the URL fragment, /// and the recipient's browser expands it back into the keypair. static func generateLinkKey() throws -> (seed: Data, publicBundle: Data) {- var seedPtr: UnsafeMutablePointer<UInt8>? = nil- var seedLen: Int = 0- var pubPtr: UnsafeMutablePointer<UInt8>? = nil- var pubLen: Int = 0- let ok = pqc_link_keygen(&seedPtr, &seedLen, &pubPtr, &pubLen)- guard ok == 1, let sp = seedPtr, let pb = pubPtr else {- throw NSError(domain: "pqc", code: -7, userInfo: [NSLocalizedDescriptionKey: "link keygen failed (native not linked?)"])+ var seed = [UInt8](repeating: 0, count: linkSeedLength)+ let status = SecRandomCopyBytes(kSecRandomDefault, linkSeedLength, &seed)+ guard status == errSecSuccess else {+ throw NSError(domain: "pqc", code: -7, userInfo: [NSLocalizedDescriptionKey: "SecRandomCopyBytes failed (\(status))"]) }- defer {- pqc_secure_zero(sp, seedLen)- pqc_free(sp, seedLen)- pqc_free(pb, pubLen)- }- return (Data(bytes: sp, count: seedLen), Data(bytes: pb, count: pubLen))+ return (Data(seed), try linkPublicBundle(fromSeed: seed)) } /// Re-derives a share-link public bundle from a stored 32-byte seed. static func linkPublicFromSeed(_ seed: Data) throws -> Data {- var pubPtr: UnsafeMutablePointer<UInt8>? = nil- var pubLen: Int = 0- let ok: Int32 = seed.withUnsafeBytes { seedBuf in- pqc_link_pub_from_seed(- seedBuf.baseAddress?.assumingMemoryBound(to: UInt8.self), seedBuf.count,- &pubPtr, &pubLen- )- }- guard ok == 1, let pb = pubPtr else {- throw NSError(domain: "pqc", code: -8, userInfo: [NSLocalizedDescriptionKey: "link key derivation failed"])+ try linkPublicBundle(fromSeed: Array(seed))+ }++ /// A link bundle keeps the [4B kemLen][kemPub][dsaPub] framing with an empty ML-DSA half,+ /// matching `pqc_link_keygen`'s `len_prefix(&kem_pub, &[])`, so `splitPublic` and+ /// `encryptTo` need no special casing for links.+ private static func linkPublicBundle(fromSeed seed: [UInt8]) throws -> Data {+ guard seed.count == linkSeedLength else {+ throw NSError(domain: "pqc", code: -8, userInfo: [NSLocalizedDescriptionKey: "link seed must be \(linkSeedLength) bytes, got \(seed.count)"]) }- defer { pqc_free(pb, pubLen) }- return Data(bytes: pb, count: pubLen)+ let kem = try MLKEM768.keyGen(seed: try expandLinkSeed(seed))+ return PQCBundle.buildPublic(kemPub: PQCDer.wrapKemPublic(kem.ek), dsaPub: Data())+ }++ /// Expands a 32-byte link seed into the 64-byte `d‖z` that FIPS 203 KeyGen_internal takes.+ ///+ /// FIPS 203 defines no 32-byte seed form, so this must reproduce whatever+ /// `mlkem_link_keygen_from_seed` in the Rust crate does, byte for byte — the web share+ /// page expands the same seed and must land on the same public key.+ private static func expandLinkSeed(_ seed: [UInt8]) throws -> [UInt8] {+ throw NSError(domain: "pqc", code: -9, userInfo: [+ NSLocalizedDescriptionKey: "link seed expansion not ported from mlkem_link_keygen_from_seed",+ ]) } }
FindFamilyiOS/Networking/Networking.swift
diff --git a/FindFamilyiOS/Networking/Networking.swift b/FindFamilyiOS/Networking/Networking.swiftindex 63351b37a4..be2ee2832b 100644--- a/FindFamilyiOS/Networking/Networking.swift+++ b/FindFamilyiOS/Networking/Networking.swift@@ -39,9 +39,12 @@ final class NetworkClient { /// - Device PQC identity uses `PQCKeyManager` which stores `ff_pqcKemPub/Priv`, `ff_pqcDsaPub/Priv` /// (same as Android's `ff_pqc` prefix) in Keychain, with bundle format [4B kemLen][kemPub][dsaPub] /// and sealed layout [4B encapLen][encap][aes] (aes = [12B iv][ct||tag]), KDF SHA256(BE32(1)||Z).-/// - Server parallel endpoints `/api/pqc/*` store PQC bundles separately from RSA; publish/receive-/// have `_pqc` variants. If peer has PQC key, publish ONLY to PQC endpoint (higher tier).-/// - Receive drains both classic and PQC queues for backward compat during rollout.+/// - Server parallel endpoints `/api/pqc/*` store PQC bundles separately from RSA.+///+/// This app is **post-quantum only**: it publishes to and receives from the `_pqc` endpoints+/// exclusively and never touches the classic RSA location/UWB queues, and it registers only a+/// PQC bundle. Android keeps its classic fallback for other peers, but it always prefers PQC+/// when the peer has a bundle registered — which this app does on every launch. @MainActor final class Networking: ObservableObject { static let shared = Networking()@@ -300,6 +303,9 @@ final class Networking: ObservableObject { // MARK: - Receive (post-quantum only) + /// Drains the post-quantum queue. The classic RSA queue is deliberately not read:+ /// this app publishes and receives post-quantum only, so anything sitting in the+ /// classic queue was sent by a peer that hasn't picked up our PQC key yet. func receiveLocations() async -> [LocationValue]? { return await receiveLocationsPqc() }
FindFamilyiOS/UI/BottomPanels.swift
diff --git a/FindFamilyiOS/UI/BottomPanels.swift b/FindFamilyiOS/UI/BottomPanels.swiftindex 537c9636a0..deb157a0c1 100644--- a/FindFamilyiOS/UI/BottomPanels.swift+++ b/FindFamilyiOS/UI/BottomPanels.swift@@ -61,24 +61,9 @@ struct UserDetailPanel: View { let onToggleSending: (Bool) -> Void let onSetAutoToggle: (TimeInterval?) -> Void - @State private var showPqcInfo = false- var body: some View { VStack(spacing: 12) { UserCard(user: user, latest: latest, showSupporting: true) {}- // PQC status banner for unprotected connections (also tappable via lock in card)- if user.id != Networking.shared.userid && user.pqcEncryptionKey == nil {- Button { showPqcInfo = true } label: {- Label(Strings.pqcUnprotectedMessage, systemImage: "lock.open.trianglebadge.exclamationmark")- .font(.caption)- .foregroundStyle(.red)- .frame(maxWidth: .infinity, alignment: .leading)- .padding(8)- .background(Color.red.opacity(0.12))- .clipShape(RoundedRectangle(cornerRadius: 8))- }- .buttonStyle(.plain)- } VStack(spacing: 8) { HStack { Text(Strings.shareYourLocation)@@ -106,11 +91,6 @@ struct UserDetailPanel: View { .buttonStyle(.bordered) } .padding(.horizontal)- .alert(Strings.pqcUnprotectedTitle, isPresented: $showPqcInfo) {- Button(Strings.okButton, role: .cancel) {}- } message: {- Text(Strings.pqcUnprotectedMessage)- } } } @@ -166,7 +146,7 @@ struct AutoToggleRow: View { Text(currentLabel).font(.subheadline.monospacedDigit()) Image(systemName: "chevron.up.chevron.down").font(.caption2) }- .foregroundStyle(.accent)+ .foregroundStyle(Color.accentColor) } } .onReceive(ticker) { t in
FindFamilyiOS/UI/Cards.swift
diff --git a/FindFamilyiOS/UI/Cards.swift b/FindFamilyiOS/UI/Cards.swiftindex 2cc9661261..f03b9a8f2d 100644--- a/FindFamilyiOS/UI/Cards.swift+++ b/FindFamilyiOS/UI/Cards.swift@@ -72,16 +72,6 @@ struct UserCard: View { let showSupporting: Bool let onTap: () -> Void - @State private var showPqcInfo = false-- /// True iff this connection is PQC-protected (quantum safe). Self never shows badge.- var isPqcProtected: Bool {- if user.id == Networking.shared.userid { return true }- if user.id == 0 { return true } // empty/new waypoint placeholder- // A user with a cached PQC bundle is protected; otherwise show broken lock.- return user.pqcEncryptionKey != nil- }- var lastUpdatedString: String { if let ts = latest?.timestamp { return TimeFormatting.timestring(ts, future: false) } return Strings.lastUpdatedNever@@ -105,7 +95,6 @@ struct UserCard: View { } var body: some View {- // Wrap outer so .alert modifier is not inside the Card's Button gesture. Button(action: showSupporting ? onTap : {}) { HStack(alignment: .top, spacing: 12) { VStack(spacing: 4) {@@ -115,32 +104,7 @@ struct UserCard: View { } } VStack(alignment: .leading, spacing: 4) {- HStack(spacing: 4) {- Text(user.name).font(.headline).lineLimit(1)- // Broken-lock icon: only in list/detail and for non-self connections.- // If protected -> green closed lock (static). If unprotected -> red broken lock tappable.- if showSupporting && user.id != Networking.shared.userid {- if isPqcProtected {- Image(systemName: "lock.fill")- .font(.caption)- .foregroundStyle(Color.green)- .accessibilityLabel("Quantum protected")- } else {- // Button wrapper prevents parent Button from also receiving tap.- Button {- showPqcInfo = true- } label: {- Image(systemName: "lock.open.trianglebadge.exclamationmark")- .font(.system(size: 13, weight: .semibold))- .foregroundStyle(Color.red)- .padding(6)- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .accessibilityLabel("Not quantum protected")- }- }- }+ Text(user.name).font(.headline).lineLimit(1) if showSupporting { Text(Strings.userCardStatus(lastUpdatedString, user.locationName, sinceString)) .font(.caption)@@ -157,11 +121,6 @@ struct UserCard: View { } .buttonStyle(.plain) .disabled(!showSupporting)- .alert(Strings.pqcUnprotectedTitle, isPresented: $showPqcInfo) {- Button(Strings.okButton, role: .cancel) {}- } message: {- Text(Strings.pqcUnprotectedMessage)- } } } @@ -192,9 +151,6 @@ struct TemporaryLinkCard: View { Text(Strings.expires(TimeFormatting.timestring(link.deleteAt, future: true))) .font(.caption2) .foregroundStyle(.secondary)- if link.pqcPublicKey != nil {- Text("PQC enabled").font(.caption2).foregroundStyle(.green)- } } Spacer() Button {
FindFamilyiOS/Util/Util.swift
diff --git a/FindFamilyiOS/Util/Util.swift b/FindFamilyiOS/Util/Util.swiftindex 3f41afdd03..10f0a335db 100644--- a/FindFamilyiOS/Util/Util.swift+++ b/FindFamilyiOS/Util/Util.swift@@ -127,10 +127,6 @@ enum Strings { "Couldn't compute the code yet — \(name)'s key isn't available. Try again once they've shared their location." } - // PQC broken-lock info box (shown when tapping red lock for non-PQC peers)- static let pqcUnprotectedTitle = "Quantum protection"- static let pqcUnprotectedMessage = "Unprotected against quantum computers: this person needs to update their app."- // Shown when connecting to a peer whose app is too old for post-quantum encryption. static let outdatedPeerTitle = "Update needed" static let outdatedPeerMessage = "This person is using an older version of FindFamily that doesn't support quantum-safe encryption. Ask them to update their app, then try connecting again."