Repository Public
1import CryptoKit2import Foundation34/// All the cryptography of SP Sync. The account key never leaves the user's devices in the clear:5/// records are sealed with keys derived from it, and it travels between devices only inside HPKE envelopes6/// or sealed under the user's recovery key.7enum SyncCrypto {8 enum Failure: Error, Equatable { case malformed, wrongKey, unsupported }910 static let keyVersion = 11112 // MARK: Account key and derived keys1314 static func newAccountKey() -> SymmetricKey { SymmetricKey(size: .bits256) }1516 static func derive(_ key: SymmetricKey, _ info: String) -> SymmetricKey {17 HKDF<SHA256>.deriveKey(inputKeyMaterial: key, info: Data(info.utf8), outputByteCount: 32)18 }1920 static func data(_ key: SymmetricKey) -> Data { key.withUnsafeBytes { Data($0) } }2122 /// What a device presents to prove it holds the account key. The server stores only its SHA-256.23 static func keyProof(_ accountKey: SymmetricKey) -> String { data(derive(accountKey, "sp-sync/v1/proof")).base64EncodedString() }2425 /// The public verifier the server returns (`keyCheck`): lets a device detect that it holds the wrong key.26 static func keyCheck(_ accountKey: SymmetricKey) -> String {27 SHA256.hash(data: Data(keyProof(accountKey).utf8)).map { String(format: "%02x", $0) }.joined()28 }2930 // MARK: Records3132 /// Opaque, stable identifier for a record keyed by a URL or a query: the server cannot invert it,33 /// and two devices derive the same one, so the same page never becomes two records.34 static func recordID(for value: String, collection: String, accountKey: SymmetricKey) -> String {35 let mac = HMAC<SHA256>.authenticationCode(for: Data((collection + "\u{0}" + value).utf8), using: derive(accountKey, "sp-sync/v1/id"))36 return base64URL(Data(mac.prefix(18)))37 }3839 private static func aad(_ collection: String, _ id: String, _ version: Int) -> Data { Data("\(collection)|\(id)|\(version)".utf8) }4041 static func seal(_ plaintext: Data, collection: String, id: String, accountKey: SymmetricKey, version: Int = keyVersion) throws -> String {42 let key = derive(accountKey, "sp-sync/v1/enc/" + collection)43 return try ChaChaPoly.seal(plaintext, using: key, authenticating: aad(collection, id, version)).combined.base64EncodedString()44 }4546 /// Fails when the ciphertext was produced for another record, collection or key (the identifier is authenticated).47 static func open(_ payload: String, collection: String, id: String, accountKey: SymmetricKey, version: Int = keyVersion) throws -> Data {48 guard let combined = Data(base64Encoded: payload), let box = try? ChaChaPoly.SealedBox(combined: combined) else { throw Failure.malformed }49 let key = derive(accountKey, "sp-sync/v1/enc/" + collection)50 guard let plaintext = try? ChaChaPoly.open(box, using: key, authenticating: aad(collection, id, version)) else { throw Failure.wrongKey }51 return plaintext52 }5354 // MARK: Device enrollment (HPKE envelopes)5556 static let suite = HPKE.Ciphersuite.Curve25519_SHA256_ChachaPoly5758 static func newDeviceKey() -> Curve25519.KeyAgreement.PrivateKey { Curve25519.KeyAgreement.PrivateKey() }59 static func publicKeyString(_ key: Curve25519.KeyAgreement.PrivateKey) -> String { key.publicKey.rawRepresentation.base64EncodedString() }6061 private static func envelopeInfo(userID: String, deviceID: String) -> Data { Data("sp-sync/v1/envelope|\(userID)|\(deviceID)".utf8) }6263 /// Seals the account key for `devicePublicKey`. Only the holder of the matching private key can open it.64 static func sealEnvelope(accountKey: SymmetricKey, to devicePublicKey: String, userID: String, deviceID: String) throws -> String {65 guard let raw = Data(base64Encoded: devicePublicKey), let recipient = try? Curve25519.KeyAgreement.PublicKey(rawRepresentation: raw) else { throw Failure.malformed }66 var sender = try HPKE.Sender(recipientKey: recipient, ciphersuite: suite, info: envelopeInfo(userID: userID, deviceID: deviceID))67 let ciphertext = try sender.seal(data(accountKey))68 return (sender.encapsulatedKey + ciphertext).base64EncodedString()69 }7071 static func openEnvelope(_ envelope: String, with privateKey: Curve25519.KeyAgreement.PrivateKey, userID: String, deviceID: String) throws -> SymmetricKey {72 guard let raw = Data(base64Encoded: envelope), raw.count > 32 else { throw Failure.malformed }73 do {74 var recipient = try HPKE.Recipient(privateKey: privateKey, ciphersuite: suite, info: envelopeInfo(userID: userID, deviceID: deviceID),75 encapsulatedKey: raw.prefix(32))76 let key = try recipient.open(raw.dropFirst(32))77 guard key.count == 32 else { throw Failure.malformed }78 return SymmetricKey(data: key)79 } catch let failure as Failure { throw failure } catch { throw Failure.wrongKey }80 }8182 /// Six digits both devices show while one approves the other. They derive from the waiting device's public key,83 /// so a server that swapped the key would make the two codes differ.84 static func verificationCode(forPublicKey publicKey: String) -> String {85 let digest = SHA256.hash(data: Data(("sp-sync/v1/sas|" + publicKey).utf8))86 let number = digest.prefix(4).reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } % 1_000_00087 let text = String(format: "%06d", number)88 return text.prefix(3) + " " + text.suffix(3)89 }9091 // MARK: Recovery key9293 /// The recovery kit shown once to the user: the account identifier and 32 random bytes, as grouped base32.94 struct RecoveryKit: Equatable {95 var userID: String96 var secret: Data9798 init(userID: String) {99 self.userID = userID100 secret = Data((0..<32).map { _ in UInt8.random(in: 0...255) })101 }102103 init?(text: String) {104 let cleaned = text.uppercased().filter { $0.isLetter || $0.isNumber }105 guard cleaned.hasPrefix("SPB1"), let bytes = Base32.decode(String(cleaned.dropFirst(4))), bytes.count > 33,106 Int(bytes[0]) == bytes.count - 33, let id = String(data: bytes.dropFirst().dropLast(32), encoding: .utf8), !id.isEmpty else { return nil }107 userID = id108 secret = Data(bytes.suffix(32))109 }110111 /// `SPB1-XXXX-XXXX-…` — typed back in, or kept as a file, to recover the account and its data.112 var text: String {113 let id = Data(userID.utf8)114 let encoded = Base32.encode(Data([UInt8(id.count)]) + id + secret)115 var groups: [String] = ["SPB1"]116 var rest = Substring(encoded)117 while !rest.isEmpty { groups.append(String(rest.prefix(4))); rest = rest.dropFirst(4) }118 return groups.joined(separator: "-")119 }120121 private var key: SymmetricKey { SymmetricKey(data: secret) }122 /// Sent to the server (which stores a slow hash of it) to prove possession of the kit when every passkey is lost.123 var authenticator: String { SyncCrypto.data(SyncCrypto.derive(key, "sp-identity/v1/recovery-auth")).base64EncodedString() }124125 func seal(_ accountKey: SymmetricKey) throws -> String {126 try ChaChaPoly.seal(SyncCrypto.data(accountKey), using: SyncCrypto.derive(key, "sp-sync/v1/recovery-kek"),127 authenticating: Data(userID.utf8)).combined.base64EncodedString()128 }129130 func open(_ blob: String) throws -> SymmetricKey {131 guard let combined = Data(base64Encoded: blob), let box = try? ChaChaPoly.SealedBox(combined: combined) else { throw Failure.malformed }132 guard let raw = try? ChaChaPoly.open(box, using: SyncCrypto.derive(key, "sp-sync/v1/recovery-kek"), authenticating: Data(userID.utf8)),133 raw.count == 32 else { throw Failure.wrongKey }134 return SymmetricKey(data: raw)135 }136 }137138 static func base64URL(_ data: Data) -> String {139 data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")140 }141142 static func data(base64URL text: String) -> Data? {143 var s = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")144 while s.count % 4 != 0 { s += "=" }145 return Data(base64Encoded: s)146 }147}148149/// RFC 4648 base32 without padding (letters that are easy to read aloud and type).150enum Base32 {151 private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")152153 static func encode(_ data: Data) -> String {154 var out = "", buffer = 0, bits = 0155 for byte in data {156 buffer = (buffer << 8) | Int(byte); bits += 8157 while bits >= 5 { out.append(alphabet[(buffer >> (bits - 5)) & 31]); bits -= 5 }158 }159 if bits > 0 { out.append(alphabet[(buffer << (5 - bits)) & 31]) }160 return out161 }162163 static func decode(_ text: String) -> Data? {164 var out = Data(), buffer = 0, bits = 0165 for character in text {166 guard let value = alphabet.firstIndex(of: character) else { return nil }167 buffer = (buffer << 5) | value; bits += 5168 if bits >= 8 { out.append(UInt8((buffer >> (bits - 8)) & 0xff)); bits -= 8 }169 buffer &= 0xffff170 }171 return out172 }173}174