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

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / Crypto / PQCKeyManager.swift

PQCKeyManager.swift189 lines · 9.1 KiBRaw
1import Foundation
2
3// MARK: - PQC Key Manager (iOS mirror of Android PqcIdentity.loadOrCreate)
4//
5// Reuses the *exact same* cryptographic core as Office's Android e2ee-p2p module:
6// - ML-KEM-768 for encryption (key encapsulation + AES-256-GCM)
7// - ML-DSA-65 for signatures (reserved for future roster changes, but part of bundle)
8// - Keys as DER, byte-compatible with Bouncy Castle encoding (fixed SPKI/PKCS#8 prefixes)
9// - Bundle format [4B kemLen BE][kemPubDer][dsaPubDer] as in `Pqc.kt:bundle`
10// - KDF SHA256(BE32(1) || rawSS) as in lib.rs `concat_kdf_sha256`
11//
12// Storage: 4 separate Keychain entries (to stay under 4KB generic-password limit per item):
13// ff_pqcKemPub, ff_pqcKemPriv, ff_pqcDsaPub, ff_pqcDsaPriv
14// This mirrors `PqcIdentity.kt` which stores `${prefix}KemPub/Priv`, `DsaPub/Priv` via E2eeKeyStore.
15//
16// This class is deliberately independent of Office — prefix `ff_pqc` ensures FindFamily PQC keys
17// don't collide with any future Office iOS implementation that might use `office` prefix.
18
19final class PQCKeyManager {
20 static let shared = PQCKeyManager()
21
22 // Keychain account names — use ff_pqc prefix matching Android's "ff_pqc" prefix.
23 private enum KC {
24 static let kemPub = "ff_pqcKemPub"
25 static let kemPriv = "ff_pqcKemPriv"
26 static let dsaPub = "ff_pqcDsaPub"
27 static let dsaPriv = "ff_pqcDsaPriv"
28 static let publicBundle = "ff_pqcPublicBundle" // cached bundle for fast register
29 }
30
31 private var _kemPub: Data?
32 private var _kemPriv: Data?
33 private var _dsaPub: Data?
34 private var _dsaPriv: Data?
35 private var _publicBundle: Data?
36 private var _privateBundle: Data?
37
38 private var isLoaded = false
39 private let loadQueue = DispatchQueue(label: "cc.findfamily.pqc.keymanager")
40
41 private init() {}
42
43 // MARK: - Load / Create (mirrors PqcIdentity.loadOrCreate)
44
45 /// Returns the device PQC identity, generating + persisting on first use.
46 /// Throws if Rust native lib is not linked (native not available on this build) or generation fails.
47 func identity() throws -> PQCIdentity {
48 // Fast path in-memory.
49 if isLoaded, let pubB = _publicBundle, let privB = _privateBundle,
50 let kemPriv = _kemPriv, let kemPub = _kemPub {
51 return PQCIdentity(publicBundle: pubB, privateBundle: privB,
52 kemPublic: kemPub, kemPrivate: kemPriv,
53 dsaPublic: _dsaPub, dsaPrivate: _dsaPriv)
54 }
55 return try loadQueue.sync {
56 if isLoaded, let pubB = _publicBundle, let privB = _privateBundle,
57 let kemPriv = _kemPriv, let kemPub = _kemPub {
58 return PQCIdentity(publicBundle: pubB, privateBundle: privB,
59 kemPublic: kemPub, kemPrivate: kemPriv,
60 dsaPublic: _dsaPub, dsaPrivate: _dsaPriv)
61 }
62
63 // Try restore from Keychain.
64 if let kemPub = Keychain.getData(key: KC.kemPub),
65 let kemPriv = Keychain.getData(key: KC.kemPriv),
66 let dsaPub = Keychain.getData(key: KC.dsaPub),
67 let dsaPriv = Keychain.getData(key: KC.dsaPriv) {
68 // Validate DER sizes roughly (to avoid corrupt entries).
69 if kemPub.count > 1000 && kemPriv.count > 1000 {
70 let pubBundle = PQCBundle.buildPublic(kemPub: kemPub, dsaPub: dsaPub)
71 let privBundle = PQCBundle.buildPrivate(kemPriv: kemPriv, dsaPriv: dsaPriv)
72 _kemPub = kemPub
73 _kemPriv = kemPriv
74 _dsaPub = dsaPub
75 _dsaPriv = dsaPriv
76 _publicBundle = pubBundle
77 _privateBundle = privBundle
78 isLoaded = true
79 Keychain.setData(pubBundle, key: KC.publicBundle) // cache
80 print("PQCKeyManager: restored identity from Keychain pubBundle=\(pubBundle.count) privBundle=\(privBundle.count)")
81 return PQCIdentity(publicBundle: pubBundle, privateBundle: privBundle,
82 kemPublic: kemPub, kemPrivate: kemPriv,
83 dsaPublic: dsaPub, dsaPrivate: dsaPriv)
84 }
85 }
86
87 // Generate fresh via Rust bridge. This requires libe2ee_pqc.a linked.
88 // If not linked, PQCCrypto.generateIdentity throws "native not linked" → PQC unavailable.
89 let (pubBundle, privBundle) = try PQCCrypto.generateIdentity()
90 guard let (kemPriv, dsaPriv) = PQCBundle.splitPrivate(privBundle),
91 let (kemPub, dsaPub) = PQCBundle.splitPublic(pubBundle) else {
92 throw NSError(domain: "pqc_keymanager", code: -1, userInfo: [NSLocalizedDescriptionKey: "generated bundles invalid"])
93 }
94
95 // Persist each DER separately (mirrors Android onlyIfAbsent race-safe, but iOS single process simpler).
96 // Use onlyIfAbsent semantics: only write if not already present (best-effort race guard if two
97 // processes — main app + background location — both start simultaneously on first launch).
98 // We implement by checking again before write.
99 if Keychain.getData(key: KC.kemPub) == nil { Keychain.setData(kemPub, key: KC.kemPub) }
100 if Keychain.getData(key: KC.kemPriv) == nil { Keychain.setData(kemPriv, key: KC.kemPriv) }
101 if Keychain.getData(key: KC.dsaPub) == nil { Keychain.setData(dsaPub, key: KC.dsaPub) }
102 if Keychain.getData(key: KC.dsaPriv) == nil { Keychain.setData(dsaPriv, key: KC.dsaPriv) }
103
104 // Re-read final persisted (winner of race) to avoid returning ephemeral identity that can't decrypt.
105 let finalKemPub = Keychain.getData(key: KC.kemPub) ?? kemPub
106 let finalKemPriv = Keychain.getData(key: KC.kemPriv) ?? kemPriv
107 let finalDsaPub = Keychain.getData(key: KC.dsaPub) ?? dsaPub
108 let finalDsaPriv = Keychain.getData(key: KC.dsaPriv) ?? dsaPriv
109
110 let finalPubBundle = PQCBundle.buildPublic(kemPub: finalKemPub, dsaPub: finalDsaPub)
111 let finalPrivBundle = PQCBundle.buildPrivate(kemPriv: finalKemPriv, dsaPriv: finalDsaPriv)
112
113 _kemPub = finalKemPub
114 _kemPriv = finalKemPriv
115 _dsaPub = finalDsaPub
116 _dsaPriv = finalDsaPriv
117 _publicBundle = finalPubBundle
118 _privateBundle = finalPrivBundle
119 isLoaded = true
120 Keychain.setData(finalPubBundle, key: KC.publicBundle)
121
122 print("PQCKeyManager: generated fresh identity pubBundle=\(finalPubBundle.count) privBundle=\(finalPrivBundle.count) (final persisted)")
123
124 return PQCIdentity(publicBundle: finalPubBundle, privateBundle: finalPrivBundle,
125 kemPublic: finalKemPub, kemPrivate: finalKemPriv,
126 dsaPublic: finalDsaPub, dsaPrivate: finalDsaPriv)
127 }
128 }
129
130 /// Attempts to load identity without generating. Returns nil if not present or native unavailable.
131 func existingIdentity() -> PQCIdentity? {
132 try? identity()
133 }
134
135 /// Indicates whether PQC is available on this build (native lib linked and identity loadable).
136 var isAvailable: Bool {
137 (try? identity()) != nil
138 }
139
140 /// Returns the public bundle base64 for registration (like Android `Base64.encode(publicBundle)`).
141 func publicBundleB64() throws -> String {
142 try identity().publicBundle.base64EncodedString()
143 }
144
145 // MARK: - Share links (TemporaryLink)
146
147 /// Generate a fresh share-link key. The link is ML-KEM only and derived from a 32-byte
148 /// seed; the seed (base64url, unpadded) is what goes in the URL fragment, and the public
149 /// bundle is what locations get encrypted to.
150 func generateLinkKey() throws -> (seedB64Url: String, publicB64: String) {
151 let (seed, pubBundle) = try PQCCrypto.generateLinkKey()
152 let seedB64Url = seed.base64EncodedString()
153 .replacingOccurrences(of: "+", with: "-")
154 .replacingOccurrences(of: "/", with: "_")
155 .replacingOccurrences(of: "=", with: "")
156 return (seedB64Url, pubBundle.base64EncodedString())
157 }
158
159 // MARK: - Encrypt / Decrypt helpers (mirror Pqc.encryptTo / decrypt)
160
161 func encryptTo(bundle: Data, plaintext: Data) throws -> Data {
162 try PQCCrypto.encryptTo(bundle: bundle, plaintext: plaintext)
163 }
164
165 func decrypt(sealed: Data) throws -> Data {
166 // Decrypt using our KEM private DER (from identity).
167 let id = try identity()
168 return try PQCCrypto.decrypt(kemPrivateDer: id.kemPrivate, sealed: sealed)
169 }
170
171 func decryptWithPrivateBundle(privateBundle: Data, sealed: Data) throws -> Data {
172 try PQCCrypto.decryptWithPrivateBundle(privateBundle: privateBundle, sealed: sealed)
173 }
174}
175
176// MARK: - In-memory identity value type
177
178struct PQCIdentity {
179 let publicBundle: Data
180 let privateBundle: Data
181 let kemPublic: Data
182 let kemPrivate: Data
183 let dsaPublic: Data?
184 let dsaPrivate: Data?
185
186 func securityCode(with peerBundle: Data) -> String {
187 PQCSecurityCode.compute(myBundle: publicBundle, theirBundle: peerBundle)
188 }
189}