Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / apple / FindFamily / FindFamilyiOS / Crypto / Crypto.swift
Crypto.swift198 lines · 7.4 KiBRaw
| 1 | import Foundation |
| 2 | import Security |
| 3 | import CryptoKit |
| 4 | |
| 5 | // MARK: - Keychain wrapper |
| 6 | |
| 7 | enum Keychain { |
| 8 | private static let service = "cc.findfamily.ios.swift" |
| 9 | |
| 10 | static func setData(_ data: Data, key: String) { |
| 11 | delete(key: key) |
| 12 | let query: [String: Any] = [ |
| 13 | kSecClass as String: kSecClassGenericPassword, |
| 14 | kSecAttrService as String: service, |
| 15 | kSecAttrAccount as String: key, |
| 16 | kSecValueData as String: data, |
| 17 | kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock, |
| 18 | ] |
| 19 | SecItemAdd(query as CFDictionary, nil) |
| 20 | } |
| 21 | |
| 22 | static func getData(key: String) -> Data? { |
| 23 | let query: [String: Any] = [ |
| 24 | kSecClass as String: kSecClassGenericPassword, |
| 25 | kSecAttrService as String: service, |
| 26 | kSecAttrAccount as String: key, |
| 27 | kSecReturnData as String: true, |
| 28 | kSecMatchLimit as String: kSecMatchLimitOne, |
| 29 | ] |
| 30 | var result: AnyObject? |
| 31 | let status = SecItemCopyMatching(query as CFDictionary, &result) |
| 32 | guard status == errSecSuccess, let data = result as? Data else { return nil } |
| 33 | return data |
| 34 | } |
| 35 | |
| 36 | static func delete(key: String) { |
| 37 | let query: [String: Any] = [ |
| 38 | kSecClass as String: kSecClassGenericPassword, |
| 39 | kSecAttrService as String: service, |
| 40 | kSecAttrAccount as String: key, |
| 41 | ] |
| 42 | SecItemDelete(query as CFDictionary) |
| 43 | } |
| 44 | |
| 45 | static func setString(_ s: String, key: String) { |
| 46 | setData(Data(s.utf8), key: key) |
| 47 | } |
| 48 | |
| 49 | static func getString(key: String) -> String? { |
| 50 | getData(key: key).flatMap { String(data: $0, encoding: .utf8) } |
| 51 | } |
| 52 | |
| 53 | static func setInt64(_ v: Int64, key: String) { |
| 54 | var x = v |
| 55 | setData(Data(bytes: &x, count: 8), key: key) |
| 56 | } |
| 57 | |
| 58 | static func getInt64(key: String) -> Int64? { |
| 59 | guard let data = getData(key: key), data.count == 8 else { return nil } |
| 60 | return data.withUnsafeBytes { $0.load(as: Int64.self) } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | // MARK: - Security code formatting (safety numbers) |
| 65 | |
| 66 | /// Formats an iterated hash into a 6-group, 5-digit safety number, and runs the shared |
| 67 | /// canonical-order iterated-SHA256 computation. Identical to Kotlin `SecurityCode`. |
| 68 | /// Used by the post-quantum safety number (`PQCSecurityCode`). |
| 69 | enum SecurityCodeFormat { |
| 70 | static let iterations = 4000 |
| 71 | |
| 72 | /// SHA-256(a) and SHA-256(b) are combined in canonical (sorted) order, then hashed |
| 73 | /// `iterations` times, then formatted. Both peers compute the same code regardless of role. |
| 74 | static func compute(_ aDigestInput: Data, _ bDigestInput: Data) -> String { |
| 75 | let a = sha256(aDigestInput) |
| 76 | let b = sha256(bDigestInput) |
| 77 | var h = a.lexicographicallyPrecedes(b) ? a + b : b + a |
| 78 | for _ in 0..<iterations { h = sha256(h) } |
| 79 | return format(h) |
| 80 | } |
| 81 | |
| 82 | static func sha256(_ d: Data) -> Data { Data(SHA256.hash(data: d)) } |
| 83 | |
| 84 | /// 6 groups of 5 bytes → big-endian UInt64 → `% 100000`, zero-padded, space-separated. |
| 85 | static func format(_ h: Data) -> String { |
| 86 | var sb = "" |
| 87 | var idx = 0 |
| 88 | for group in 0..<6 { |
| 89 | guard idx + 5 <= h.count else { break } |
| 90 | var v: UInt64 = 0 |
| 91 | for j in 0..<5 { v = (v << 8) | UInt64(h[h.startIndex + idx + j]) } |
| 92 | if group > 0 { sb.append(" ") } |
| 93 | sb.append(String(format: "%05d", v % 100000)) |
| 94 | idx += 5 |
| 95 | } |
| 96 | return sb |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | // MARK: - Base26 |
| 101 | |
| 102 | /// Encodes a Long id using uppercase A..Z digits. Mirrors `encodeBase26` in the Modern-Apps library. |
| 103 | enum Base26 { |
| 104 | private static let digits = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ") |
| 105 | |
| 106 | static func encode(_ value: Int64) -> String { |
| 107 | if value == 0 { return "A" } |
| 108 | let n = UInt64(bitPattern: value) |
| 109 | var result = "" |
| 110 | var v = n |
| 111 | repeat { |
| 112 | result.append(digits[Int(v % 26)]) |
| 113 | v /= 26 |
| 114 | } while v > 0 |
| 115 | return String(result.reversed()) |
| 116 | } |
| 117 | |
| 118 | static func decode(_ s: String) -> Int64? { |
| 119 | var v: UInt64 = 0 |
| 120 | for ch in s.uppercased() { |
| 121 | guard let idx = digits.firstIndex(of: ch) else { return nil } |
| 122 | v = v &* 26 &+ UInt64(idx) |
| 123 | } |
| 124 | return Int64(bitPattern: v) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | extension Int64 { |
| 129 | /// Convenience: `myId.base26`. |
| 130 | var base26: String { Base26.encode(self) } |
| 131 | } |
| 132 | |
| 133 | // MARK: - Invite fingerprint |
| 134 | |
| 135 | /// Short fingerprint of a public bundle, small enough to ride in an invite link. |
| 136 | /// Byte-identical to Kotlin `InviteFingerprint`. |
| 137 | /// |
| 138 | /// A PQC bundle is ~3.1 kB, so the key itself cannot travel in a URL. An invite carries |
| 139 | /// this truncated digest instead; the recipient still fetches the full bundle from the |
| 140 | /// relay and checks that it hashes to what the link said, which removes the relay's |
| 141 | /// ability to substitute a key of its own. The user id is hashed in so a fingerprint |
| 142 | /// lifted from one invite cannot be presented as another user's. |
| 143 | /// |
| 144 | /// Cross-platform test vectors, asserted on the Android side in `InviteFingerprintTest` |
| 145 | /// (`matches_the_cross_platform_test_vector`). With `publicBundle` = 3184 bytes where |
| 146 | /// byte *i* is `i % 256`: |
| 147 | /// |
| 148 | /// userId 12345 -> "iXVzYL2J4imtjXPgh-dmtw" |
| 149 | /// userId -2 -> "rjnCvl7blekCiZv2q9QJOA" |
| 150 | /// |
| 151 | /// A link minted on one platform has to verify on the other, so changing the domain |
| 152 | /// string, the id width, or `length` here breaks live invites in both directions. |
| 153 | enum InviteFingerprint { |
| 154 | /// Truncated digest length. 16 bytes encodes to 22 unpadded base64url characters. |
| 155 | static let length = 16 |
| 156 | |
| 157 | private static let domain = "ff-invite-v1" |
| 158 | |
| 159 | /// `SHA-256(domain || u64be(userId) || publicBundle)`, truncated to `length`. |
| 160 | static func compute(userId: Int64, publicBundle: Data) -> Data { |
| 161 | var input = Data(domain.utf8) |
| 162 | // Big-endian over the *bit pattern*, so a negative id hashes to the same bytes |
| 163 | // the Kotlin side produces for the matching ULong. |
| 164 | withUnsafeBytes(of: UInt64(bitPattern: userId).bigEndian) { input.append(contentsOf: $0) } |
| 165 | input.append(publicBundle) |
| 166 | return Data(SecurityCodeFormat.sha256(input).prefix(length)) |
| 167 | } |
| 168 | |
| 169 | /// The `k=` value of a share link: unpadded base64url. |
| 170 | static func encode(userId: Int64, publicBundle: Data) -> String { |
| 171 | base64urlEncode(compute(userId: userId, publicBundle: publicBundle)) |
| 172 | } |
| 173 | |
| 174 | /// Whether `publicBundle` is the one `expected` (unpadded base64url) names. A |
| 175 | /// malformed or truncated value fails rather than being skipped, so a mangled link |
| 176 | /// counts as unverified instead of silently trusting whatever the relay returned. |
| 177 | static func matches(userId: Int64, publicBundle: Data, expected: String) -> Bool { |
| 178 | guard let want = base64urlDecode(expected), want.count == length else { return false } |
| 179 | return want == compute(userId: userId, publicBundle: publicBundle) |
| 180 | } |
| 181 | |
| 182 | static func base64urlEncode(_ data: Data) -> String { |
| 183 | data.base64EncodedString() |
| 184 | .replacingOccurrences(of: "+", with: "-") |
| 185 | .replacingOccurrences(of: "/", with: "_") |
| 186 | .replacingOccurrences(of: "=", with: "") |
| 187 | } |
| 188 | |
| 189 | static func base64urlDecode(_ s: String) -> Data? { |
| 190 | var b64 = s |
| 191 | .replacingOccurrences(of: "-", with: "+") |
| 192 | .replacingOccurrences(of: "_", with: "/") |
| 193 | // Data(base64Encoded:) rejects unpadded input, and links carry it unpadded. |
| 194 | let remainder = b64.count % 4 |
| 195 | if remainder != 0 { b64 += String(repeating: "=", count: 4 - remainder) } |
| 196 | return Data(base64Encoded: b64) |
| 197 | } |
| 198 | } |