Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / apple / FindFamily / FindFamilyiOS / Crypto / PQCCrypto.swift
PQCCrypto.swift283 lines · 13.4 KiBRaw
| 1 | import Foundation |
| 2 | import CryptoKit |
| 3 | import Security |
| 4 | |
| 5 | // MARK: - PQC Bundle framing (identical to Kotlin Pqc.kt) |
| 6 | // |
| 7 | // Public bundle: [4B kemPubLen BE][kemPub SPKI DER][dsaPub SPKI DER] |
| 8 | // Private bundle: [4B kemPrivLen BE][kemPriv PKCS#8 DER][dsaPriv PKCS#8 DER] |
| 9 | // Sealed blob: [4B encapLen BE][encap(1088)][aes] where aes = [12B iv][ciphertext||tag] |
| 10 | // Shared secret: SHA256(BE32(1) || rawSS) — same KDF as Office / Bouncy Castle's default. |
| 11 | |
| 12 | enum PQCBundle { |
| 13 | // MARK: - Length-prefix framing |
| 14 | |
| 15 | static func lenPrefix(_ a: Data, _ b: Data) -> Data { |
| 16 | var out = Data() |
| 17 | out.reserveCapacity(4 + a.count + b.count) |
| 18 | let alen = UInt32(a.count).bigEndian |
| 19 | withUnsafeBytes(of: alen) { out.append(contentsOf: $0) } |
| 20 | out.append(a) |
| 21 | out.append(b) |
| 22 | return out |
| 23 | } |
| 24 | |
| 25 | static func unLenPrefix(_ x: Data) -> (Data, Data)? { |
| 26 | guard x.count >= 4 else { return nil } |
| 27 | let base = x.startIndex |
| 28 | let len = (Int(x[base]) << 24) | (Int(x[base + 1]) << 16) | (Int(x[base + 2]) << 8) | Int(x[base + 3]) |
| 29 | guard len >= 0, 4 + len <= x.count else { return nil } |
| 30 | let first = x.subdata(in: (base + 4)..<(base + 4 + len)) |
| 31 | let second = x.subdata(in: (base + 4 + len)..<x.endIndex) |
| 32 | return (first, second) |
| 33 | } |
| 34 | |
| 35 | // MARK: - Public/Private bundle builders |
| 36 | |
| 37 | static func buildPublic(kemPub: Data, dsaPub: Data) -> Data { |
| 38 | lenPrefix(kemPub, dsaPub) |
| 39 | } |
| 40 | |
| 41 | static func buildPrivate(kemPriv: Data, dsaPriv: Data) -> Data { |
| 42 | lenPrefix(kemPriv, dsaPriv) |
| 43 | } |
| 44 | |
| 45 | static func splitPublic(_ bundle: Data) -> (kemPub: Data, dsaPub: Data)? { |
| 46 | guard let (k, d) = unLenPrefix(bundle) else { return nil } |
| 47 | return (k, d) |
| 48 | } |
| 49 | |
| 50 | static func splitPrivate(_ bundle: Data) -> (kemPriv: Data, dsaPriv: Data)? { |
| 51 | guard let (k, d) = unLenPrefix(bundle) else { return nil } |
| 52 | return (k, d) |
| 53 | } |
| 54 | |
| 55 | // MARK: - Sealed blob helpers [4B encapLen][encap][aes] where aes = [12B iv][ct||tag] |
| 56 | |
| 57 | static func buildSealed(encap: Data, aes: Data) -> Data { |
| 58 | lenPrefix(encap, aes) |
| 59 | } |
| 60 | |
| 61 | static func splitSealed(_ blob: Data) -> (encap: Data, aes: Data)? { |
| 62 | guard let (e, a) = unLenPrefix(blob) else { return nil } |
| 63 | return (e, a) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // MARK: - AES-256-GCM helpers (mirrors E2ee.aesEncrypt / aesDecrypt in Kotlin) |
| 68 | // |
| 69 | // Layout: E2ee.aesEncrypt produces iv(12) + ct||tag (16) with random IV prepended. |
| 70 | // We reproduce that via CryptoKit AES.GCM. |
| 71 | |
| 72 | enum PQCAES { |
| 73 | static let ivLen = 12 |
| 74 | |
| 75 | /// Encrypts with `key` (32 bytes), returns `iv(12) + ciphertext||tag`. |
| 76 | static func seal(key: Data, plaintext: Data) throws -> Data { |
| 77 | guard key.count == 32 else { throw NSError(domain: "pqc_aes", code: -1, userInfo: [NSLocalizedDescriptionKey: "key must be 32 bytes"]) } |
| 78 | let symKey = SymmetricKey(data: key) |
| 79 | let nonce = AES.GCM.Nonce() // random 12 bytes |
| 80 | let sealed = try AES.GCM.seal(plaintext, using: symKey, nonce: nonce) |
| 81 | var out = Data() |
| 82 | out.reserveCapacity(12 + sealed.ciphertext.count + sealed.tag.count) |
| 83 | out.append(Data(nonce)) |
| 84 | out.append(sealed.ciphertext) |
| 85 | out.append(sealed.tag) |
| 86 | return out |
| 87 | } |
| 88 | |
| 89 | /// Reverses `seal`: input `iv(12) + ct||tag`, key 32 bytes. |
| 90 | static func open(key: Data, sealed: Data) throws -> Data { |
| 91 | guard key.count == 32 else { throw NSError(domain: "pqc_aes", code: -1, userInfo: [NSLocalizedDescriptionKey: "key must be 32 bytes"]) } |
| 92 | guard sealed.count >= ivLen + 16 else { throw NSError(domain: "pqc_aes", code: -2, userInfo: [NSLocalizedDescriptionKey: "sealed too short"]) } |
| 93 | let iv = sealed.subdata(in: sealed.startIndex..<(sealed.startIndex + ivLen)) |
| 94 | let ctAndTag = sealed.subdata(in: (sealed.startIndex + ivLen)..<sealed.endIndex) |
| 95 | guard ctAndTag.count >= 16 else { throw NSError(domain: "pqc_aes", code: -3) } |
| 96 | let tag = ctAndTag.subdata(in: (ctAndTag.endIndex - 16)..<ctAndTag.endIndex) |
| 97 | let ct = ctAndTag.subdata(in: ctAndTag.startIndex..<(ctAndTag.endIndex - 16)) |
| 98 | let symKey = SymmetricKey(data: key) |
| 99 | let nonce = try AES.GCM.Nonce(data: iv) |
| 100 | let sealedBox = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ct, tag: tag) |
| 101 | return try AES.GCM.open(sealedBox, using: symKey) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | // MARK: - Security code (same as Kotlin SecurityCode.compute) |
| 106 | |
| 107 | enum PQCSecurityCode { |
| 108 | /// Computes a 6-group 5-digit safety number from two public bundles, identical both sides. |
| 109 | static func compute(myBundle: Data, theirBundle: Data) -> String { |
| 110 | SecurityCodeFormat.compute(myBundle, theirBundle) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // MARK: - DER encoding (Bouncy Castle 1.85 layouts, mirrored from the Kotlin/Rust side) |
| 115 | // |
| 116 | // The prefixes are fixed because ML-KEM/ML-DSA keys are fixed-size, so the whole |
| 117 | // DER is prefix ‖ raw. These byte arrays are copied verbatim from |
| 118 | // `library/e2ee-p2p/src/main/rust/src/lib.rs` so the two sides agree exactly. |
| 119 | |
| 120 | enum PQCDer { |
| 121 | /// SPKI prefix = SEQUENCE, AlgorithmIdentifier(OID), BIT STRING header (+ unused = 00). |
| 122 | static let kemPubPrefix: [UInt8] = [ |
| 123 | 0x30, 0x82, 0x04, 0xb2, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, |
| 124 | 0x02, 0x03, 0x82, 0x04, 0xa1, 0x00, |
| 125 | ] |
| 126 | static let dsaPubPrefix: [UInt8] = [ |
| 127 | 0x30, 0x82, 0x07, 0xb2, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, |
| 128 | 0x12, 0x03, 0x82, 0x07, 0xa1, 0x00, |
| 129 | ] |
| 130 | /// PKCS#8 prefix up to and including the seed OCTET STRING header. |
| 131 | static let kemPrivPrefix: [UInt8] = [ |
| 132 | 0x30, 0x82, 0x09, 0xbe, 0x02, 0x01, 0x00, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, |
| 133 | 0x03, 0x04, 0x04, 0x02, 0x04, 0x82, 0x09, 0xaa, 0x30, 0x82, 0x09, 0xa6, 0x04, 0x40, |
| 134 | ] |
| 135 | /// expandedKey OCTET STRING header. |
| 136 | static let kemPrivMid: [UInt8] = [0x04, 0x82, 0x09, 0x60] |
| 137 | static let dsaPrivPrefix: [UInt8] = [ |
| 138 | 0x30, 0x82, 0x0f, 0xfe, 0x02, 0x01, 0x00, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, |
| 139 | 0x03, 0x04, 0x03, 0x12, 0x04, 0x82, 0x0f, 0xea, 0x30, 0x82, 0x0f, 0xe6, 0x04, 0x20, |
| 140 | ] |
| 141 | static let dsaPrivMid: [UInt8] = [0x04, 0x82, 0x0f, 0xc0] |
| 142 | |
| 143 | static func wrapKemPublic(_ ek: [UInt8]) -> Data { Data(kemPubPrefix + ek) } |
| 144 | static func wrapDsaPublic(_ pk: [UInt8]) -> Data { Data(dsaPubPrefix + pk) } |
| 145 | |
| 146 | /// BC's seed+expanded "both" form: prefix ‖ seed ‖ mid ‖ expandedKey. |
| 147 | static func wrapKemPrivate(seed: [UInt8], expanded: [UInt8]) -> Data { |
| 148 | Data(kemPrivPrefix + seed + kemPrivMid + expanded) |
| 149 | } |
| 150 | |
| 151 | static func wrapDsaPrivate(seed: [UInt8], expanded: [UInt8]) -> Data { |
| 152 | Data(dsaPrivPrefix + seed + dsaPrivMid + expanded) |
| 153 | } |
| 154 | |
| 155 | /// A raw public key is the trailing `rawLength` bytes of the SPKI DER. |
| 156 | static func rawPublic(_ der: Data, rawLength: Int) -> [UInt8]? { |
| 157 | guard der.count >= rawLength else { return nil } |
| 158 | return Array(der.suffix(rawLength)) |
| 159 | } |
| 160 | |
| 161 | /// The expanded private key is the trailing `expandedLength` bytes of the PKCS#8 DER. |
| 162 | static func expandedPrivate(_ der: Data, expandedLength: Int) -> [UInt8]? { |
| 163 | guard der.count >= expandedLength else { return nil } |
| 164 | return Array(der.suffix(expandedLength)) |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // MARK: - High-level PQC ops that mirror Kotlin Pqc.encryptTo / decrypt |
| 169 | |
| 170 | enum PQCCrypto { |
| 171 | /// SP 800-56A single-step KDF with SHA-256 and empty OtherInfo — what Bouncy Castle's |
| 172 | /// `KEMGenerateSpec(pub, "AES")` applies by default, so derived AES keys match the |
| 173 | /// already-deployed Android ciphertexts. key = SHA-256(BE32(1) ‖ Z). |
| 174 | static func concatKDF(_ z: [UInt8]) -> Data { |
| 175 | var hasher = SHA256() |
| 176 | withUnsafeBytes(of: UInt32(1).bigEndian) { hasher.update(bufferPointer: $0) } |
| 177 | hasher.update(data: Data(z)) |
| 178 | return Data(hasher.finalize()) |
| 179 | } |
| 180 | |
| 181 | /// Encrypts `plaintext` to a recipient's public PQC bundle (from PQCBundle.buildPublic). |
| 182 | /// Layout sealed = [4B encapLen BE][encap(1088)][aes] where aes = [12B iv][ct||tag], |
| 183 | /// identical to Kotlin's Pqc.encryptTo (which does encaps + E2ee.aesEncrypt). |
| 184 | static func encryptTo(bundle: Data, plaintext: Data) throws -> Data { |
| 185 | guard let (kemPubDer, _) = PQCBundle.splitPublic(bundle), |
| 186 | let ek = PQCDer.rawPublic(kemPubDer, rawLength: MLKEM768.ekLength) else { |
| 187 | throw NSError(domain: "pqc", code: -1, userInfo: [NSLocalizedDescriptionKey: "invalid PQC bundle"]) |
| 188 | } |
| 189 | let result = try MLKEM768.encapsulate(ek: ek) |
| 190 | let aes = try PQCAES.seal(key: concatKDF(result.sharedSecret), plaintext: plaintext) |
| 191 | return PQCBundle.buildSealed(encap: Data(result.ciphertext), aes: aes) |
| 192 | } |
| 193 | |
| 194 | /// Decrypts a sealed blob produced by `encryptTo` using our KEM private DER. |
| 195 | static func decrypt(kemPrivateDer: Data, sealed: Data) throws -> Data { |
| 196 | guard let (encap, aes) = PQCBundle.splitSealed(sealed) else { |
| 197 | throw NSError(domain: "pqc", code: -2, userInfo: [NSLocalizedDescriptionKey: "invalid sealed blob"]) |
| 198 | } |
| 199 | guard let dk = PQCDer.expandedPrivate(kemPrivateDer, expandedLength: MLKEM768.dkLength) else { |
| 200 | throw NSError(domain: "pqc", code: -3, userInfo: [NSLocalizedDescriptionKey: "invalid ML-KEM private key"]) |
| 201 | } |
| 202 | let sharedSecret = try MLKEM768.decapsulate(dk: dk, ciphertext: Array(encap)) |
| 203 | return try PQCAES.open(key: concatKDF(sharedSecret), sealed: aes) |
| 204 | } |
| 205 | |
| 206 | /// Decrypt using a private bundle [4B kemPrivLen][kemPriv][dsaPriv] |
| 207 | /// (how ephemeral share links store their private half). |
| 208 | static func decryptWithPrivateBundle(privateBundle: Data, sealed: Data) throws -> Data { |
| 209 | guard let (kemPriv, _) = PQCBundle.splitPrivate(privateBundle) else { |
| 210 | throw NSError(domain: "pqc", code: -4, userInfo: [NSLocalizedDescriptionKey: "invalid private bundle"]) |
| 211 | } |
| 212 | return try decrypt(kemPrivateDer: kemPriv, sealed: sealed) |
| 213 | } |
| 214 | |
| 215 | /// Generates a full identity: ML-KEM-768 + ML-DSA-65, DER-wrapped and bundled. |
| 216 | /// |
| 217 | /// The private DER carries BC's seed+expanded form, so the 2400-byte decapsulation |
| 218 | /// key sits at the tail exactly where Android and the web share page look for it. |
| 219 | static func generateIdentity() throws -> (publicBundle: Data, privateBundle: Data) { |
| 220 | let kemSeed = try MLKEM768.randomSeed() |
| 221 | let kem = try MLKEM768.keyGen(seed: kemSeed) |
| 222 | |
| 223 | var dsaSeed = [UInt8](repeating: 0, count: MLDSA65.seedLength) |
| 224 | let status = SecRandomCopyBytes(kSecRandomDefault, MLDSA65.seedLength, &dsaSeed) |
| 225 | guard status == errSecSuccess else { |
| 226 | throw NSError(domain: "pqc", code: -5, userInfo: [NSLocalizedDescriptionKey: "SecRandomCopyBytes failed (\(status))"]) |
| 227 | } |
| 228 | let dsa = try MLDSA65.keyGen(seed: dsaSeed) |
| 229 | |
| 230 | let publicBundle = PQCBundle.buildPublic( |
| 231 | kemPub: PQCDer.wrapKemPublic(kem.ek), |
| 232 | dsaPub: PQCDer.wrapDsaPublic(dsa.publicKey) |
| 233 | ) |
| 234 | let privateBundle = PQCBundle.buildPrivate( |
| 235 | kemPriv: PQCDer.wrapKemPrivate(seed: kemSeed, expanded: kem.dk), |
| 236 | dsaPriv: PQCDer.wrapDsaPrivate(seed: dsaSeed, expanded: dsa.privateKey) |
| 237 | ) |
| 238 | return (publicBundle, privateBundle) |
| 239 | } |
| 240 | |
| 241 | /// Length of a share-link seed. A link carries only this in its URL fragment (`#s=`), |
| 242 | /// so it is the link's whole secret and both platforms must expand it identically. |
| 243 | static let linkSeedLength = 32 |
| 244 | |
| 245 | /// Generates a share-link key: a 32-byte ML-KEM seed plus the ML-KEM-only public bundle |
| 246 | /// it derives. The seed is the link's whole secret — it is what goes in the URL fragment, |
| 247 | /// and the recipient's browser expands it back into the keypair. |
| 248 | static func generateLinkKey() throws -> (seed: Data, publicBundle: Data) { |
| 249 | var seed = [UInt8](repeating: 0, count: linkSeedLength) |
| 250 | let status = SecRandomCopyBytes(kSecRandomDefault, linkSeedLength, &seed) |
| 251 | guard status == errSecSuccess else { |
| 252 | throw NSError(domain: "pqc", code: -7, userInfo: [NSLocalizedDescriptionKey: "SecRandomCopyBytes failed (\(status))"]) |
| 253 | } |
| 254 | return (Data(seed), try linkPublicBundle(fromSeed: seed)) |
| 255 | } |
| 256 | |
| 257 | /// Re-derives a share-link public bundle from a stored 32-byte seed. |
| 258 | static func linkPublicFromSeed(_ seed: Data) throws -> Data { |
| 259 | try linkPublicBundle(fromSeed: Array(seed)) |
| 260 | } |
| 261 | |
| 262 | /// A link bundle keeps the [4B kemLen][kemPub][dsaPub] framing with an empty ML-DSA half, |
| 263 | /// matching `pqc_link_keygen`'s `len_prefix(&kem_pub, &[])`, so `splitPublic` and |
| 264 | /// `encryptTo` need no special casing for links. |
| 265 | private static func linkPublicBundle(fromSeed seed: [UInt8]) throws -> Data { |
| 266 | guard seed.count == linkSeedLength else { |
| 267 | throw NSError(domain: "pqc", code: -8, userInfo: [NSLocalizedDescriptionKey: "link seed must be \(linkSeedLength) bytes, got \(seed.count)"]) |
| 268 | } |
| 269 | let kem = try MLKEM768.keyGen(seed: try expandLinkSeed(seed)) |
| 270 | return PQCBundle.buildPublic(kemPub: PQCDer.wrapKemPublic(kem.ek), dsaPub: Data()) |
| 271 | } |
| 272 | |
| 273 | /// Expands a 32-byte link seed into the 64-byte `d‖z` that FIPS 203 KeyGen_internal takes. |
| 274 | /// |
| 275 | /// FIPS 203 defines no 32-byte seed form, so this must reproduce whatever |
| 276 | /// `mlkem_link_keygen_from_seed` in the Rust crate does, byte for byte — the web share |
| 277 | /// page expands the same seed and must land on the same public key. |
| 278 | private static func expandLinkSeed(_ seed: [UInt8]) throws -> [UInt8] { |
| 279 | throw NSError(domain: "pqc", code: -9, userInfo: [ |
| 280 | NSLocalizedDescriptionKey: "link seed expansion not ported from mlkem_link_keygen_from_seed", |
| 281 | ]) |
| 282 | } |
| 283 | } |