SPB Git

Repository Public

SecureBundle.swift 9.0 KB 148 lines swift

1// SP Lecture Studio — LectureSync2// File: Packages/LectureSync/Sources/SecureBundle.swift3// Description: Passphrase-encrypted project bundles (AES-256-GCM, chunked, authenticated against truncation and reordering) and Keychain storage.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import CryptoKit9import CommonCrypto10import Security11import LocalAuthentication1213public enum SecureBundleError: Error, Equatable { case badFormat, wrongPassphraseOrCorrupt, truncated, io(String), cancelled }1415/// File format `SLSB1`:16/// magic(5) | salt(16) | iterations(u32 BE) | noncePrefix(8) | chunkSize(u32 BE) | then for each chunk: length(u32 BE) | ciphertext | tag(16).17/// The key is PBKDF2-HMAC-SHA256(passphrase, salt). Each chunk uses nonce = prefix ‖ counter(u32 BE) and authenticates18/// `counter ‖ isLast` as additional data, so chunks cannot be dropped, reordered or the file truncated without detection.19public enum SecureBundle {20    static let magic = Data("SLSB1".utf8)21    public static let defaultIterations: UInt32 = 310_00022    static let chunkSize = 1 << 202324    public static func deriveKey(passphrase: String, salt: Data, iterations: UInt32) -> SymmetricKey {25        var out = [UInt8](repeating: 0, count: 32)26        let pw = Array(passphrase.precomposedStringWithCanonicalMapping.utf8)27        salt.withUnsafeBytes { s in28            _ = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), pw.map { Int8(bitPattern: $0) }, pw.count, s.bindMemory(to: UInt8.self).baseAddress, salt.count,29                                     CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), iterations, &out, 32)30        }31        return SymmetricKey(data: out)32    }3334    static func random(_ count: Int) -> Data {35        var d = Data(count: count)36        _ = d.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, count, $0.baseAddress!) }37        return d38    }3940    public static func encrypt(_ source: URL, to destination: URL, passphrase: String, iterations: UInt32 = defaultIterations, progress: ((Double) -> Bool)? = nil) throws {41        let fm = FileManager.default42        let total = max(1, (try? fm.attributesOfItem(atPath: source.path)[.size] as? NSNumber)?.int64Value ?? 1)43        let input: FileHandle44        do { input = try FileHandle(forReadingFrom: source) } catch { throw SecureBundleError.io(error.localizedDescription) }45        defer { try? input.close() }46        fm.createFile(atPath: destination.path, contents: nil)47        guard let out = try? FileHandle(forWritingTo: destination) else { throw SecureBundleError.io("cannot create \(destination.lastPathComponent)") }48        defer { try? out.close() }49        let salt = random(16), prefix = random(8)50        let key = deriveKey(passphrase: passphrase, salt: salt, iterations: iterations)51        var header = magic; header.append(salt); header.append(be(iterations)); header.append(prefix); header.append(be(UInt32(chunkSize)))52        try out.write(contentsOf: header)53        var counter: UInt32 = 054        var done: Int64 = 055        var current = try input.read(upToCount: chunkSize) ?? Data()56        while true {57            let next = try input.read(upToCount: chunkSize) ?? Data()58            let isLast = next.isEmpty59            let nonce = try AES.GCM.Nonce(data: prefix + be(counter))60            let sealed = try AES.GCM.seal(current, using: key, nonce: nonce, authenticating: be(counter) + Data([isLast ? 1 : 0]))61            try out.write(contentsOf: be(UInt32(sealed.ciphertext.count))); try out.write(contentsOf: sealed.ciphertext); try out.write(contentsOf: sealed.tag)62            done += Int64(current.count); counter += 163            if let progress, !progress(Double(done) / Double(total)) { try? out.close(); try? fm.removeItem(at: destination); throw SecureBundleError.cancelled }64            if isLast { break }65            current = next66        }67        try out.synchronize()68    }6970    public static func decrypt(_ source: URL, to destination: URL, passphrase: String, progress: ((Double) -> Bool)? = nil) throws {71        let fm = FileManager.default72        let total = max(1, (try? fm.attributesOfItem(atPath: source.path)[.size] as? NSNumber)?.int64Value ?? 1)73        guard let input = try? FileHandle(forReadingFrom: source) else { throw SecureBundleError.io("cannot open") }74        defer { try? input.close() }75        guard let header = try input.read(upToCount: 37), header.count == 37, header.prefix(5) == magic else { throw SecureBundleError.badFormat }76        let salt = header.subdata(in: 5..<21), iterations = u32(header, 21), prefix = header.subdata(in: 25..<33), declaredChunk = Int(u32(header, 33))77        guard iterations >= 10_000, iterations <= 10_000_000, declaredChunk > 0, declaredChunk <= 16 << 20 else { throw SecureBundleError.badFormat }78        let key = deriveKey(passphrase: passphrase, salt: salt, iterations: iterations)79        fm.createFile(atPath: destination.path, contents: nil)80        guard let out = try? FileHandle(forWritingTo: destination) else { throw SecureBundleError.io("cannot create") }81        var ok = false82        defer { try? out.close(); if !ok { try? fm.removeItem(at: destination) } }83        var counter: UInt32 = 0, sawLast = false, read: Int64 = 3784        while let lenData = try input.read(upToCount: 4), !lenData.isEmpty {85            guard lenData.count == 4, !sawLast else { throw SecureBundleError.truncated }86            let len = Int(u32(lenData, 0))87            guard len <= declaredChunk, let body = try input.read(upToCount: len + 16), body.count == len + 16 else { throw SecureBundleError.truncated }88            read += Int64(4 + body.count)89            let nonce = try AES.GCM.Nonce(data: prefix + be(counter))90            let box = try AES.GCM.SealedBox(nonce: nonce, ciphertext: body.prefix(len), tag: body.suffix(16))91            // The "is last" flag is authenticated: try as a middle chunk, then as the final one.92            if let plain = try? AES.GCM.open(box, using: key, authenticating: be(counter) + Data([0])) { try out.write(contentsOf: plain) }93            else if let plain = try? AES.GCM.open(box, using: key, authenticating: be(counter) + Data([1])) { try out.write(contentsOf: plain); sawLast = true }94            else { throw SecureBundleError.wrongPassphraseOrCorrupt }95            counter += 196            if let progress, !progress(Double(read) / Double(total)) { throw SecureBundleError.cancelled }97        }98        guard sawLast else { throw SecureBundleError.truncated }99        try out.synchronize(); ok = true100    }101102    static func be(_ v: UInt32) -> Data { withUnsafeBytes(of: v.bigEndian) { Data($0) } }103    static func u32(_ d: Data, _ o: Int) -> UInt32 { d.subdata(in: (d.startIndex + o)..<(d.startIndex + o + 4)).reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } }104105    /// A random passphrase for pairing two devices (the user copies it once; 125 bits of entropy).106    public static func generatePairingCode() -> String {107        let alphabet = Array("ABCDEFGHJKLMNPQRSTUVWXYZ23456789")108        let bytes = [UInt8](random(25))109        let chars = bytes.map { alphabet[Int($0) % 32] }110        return stride(from: 0, to: 25, by: 5).map { String(chars[$0..<($0 + 5)]) }.joined(separator: "-")111    }112}113114/// Secrets (upload token, transcription token, pairing code) live in the Keychain, never in the project or in preferences.115public enum KeychainStore {116    public static let service = "ai.spboucher.splecturestudio"117118    @discardableResult119    public static func set(_ value: String?, account: String) -> Bool {120        let base: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]121        SecItemDelete(base as CFDictionary)122        guard let value, !value.isEmpty else { return true }123        var add = base124        add[kSecValueData as String] = Data(value.utf8)125        add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly126        return SecItemAdd(add as CFDictionary, nil) == errSecSuccess127    }128129    public static func get(account: String) -> String? {130        let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account,131                                kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]132        var out: CFTypeRef?133        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }134        return String(data: d, encoding: .utf8)135    }136}137138/// Optional Face ID / Touch ID gate in front of the stored credentials. The biometric check happens on the device only;139/// it unlocks the local Keychain item and nothing biometric is ever transmitted.140public enum BiometricGate {141    public static var isAvailable: Bool { LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) }142    public static func unlock(reason: String) async -> Bool {143        let ctx = LAContext()144        guard ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) else { return false }145        return (try? await ctx.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) ?? false146    }147}148
Files main
Menu

Theme