SPB Git

Repository Public

Crypto.swift 7.0 KB 149 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatSecurity/Sources/Crypto.swift3// Description: ChaChaPoly authenticated encryption envelope, HKDF/PBKDF2 key derivation, pairing codes and API-key hashing.4import CommonCrypto5import CryptoKit6import Foundation78public enum CryptoError: LocalizedError, Sendable, Equatable {9    case malformedEnvelope, unsupportedVersion(UInt8), authenticationFailed, derivationFailed, invalidCode10    public var errorDescription: String? {11        switch self {12        case .malformedEnvelope: "The encrypted data is malformed."13        case .unsupportedVersion(let v): "Unsupported encryption version \(v)."14        case .authenticationFailed: "The data could not be decrypted: wrong key or modified data."15        case .derivationFailed: "The key could not be derived."16        case .invalidCode: "The code is not valid."17        }18    }19}2021/// AEAD envelope: [version 1 byte][nonce 12][ciphertext][tag 16].22public enum SecretBox {23    public static let version: UInt8 = 12425    public static func seal(_ plaintext: Data, key: SymmetricKey, associatedData: Data = Data()) throws -> Data {26        let box = try ChaChaPoly.seal(plaintext, using: key, nonce: ChaChaPoly.Nonce(), authenticating: associatedData)27        return Data([version]) + box.combined28    }2930    public static func open(_ envelope: Data, key: SymmetricKey, associatedData: Data = Data()) throws -> Data {31        guard envelope.count >= 1 + 12 + 16, let v = envelope.first else { throw CryptoError.malformedEnvelope }32        guard v == version else { throw CryptoError.unsupportedVersion(v) }33        guard let box = try? ChaChaPoly.SealedBox(combined: envelope.dropFirst()) else { throw CryptoError.malformedEnvelope }34        do { return try ChaChaPoly.open(box, using: key, authenticating: associatedData) }35        catch { throw CryptoError.authenticationFailed }36    }37}3839public enum KeyDerivation {40    public static let defaultIterations = 600_0004142    /// HKDF-SHA256 subkey for one purpose ("sync-records", "sync-auth", …).43    public static func subkey(from master: SymmetricKey, purpose: String, salt: Data = Data(), length: Int = 32) -> SymmetricKey {44        HKDF<SHA256>.deriveKey(inputKeyMaterial: master, salt: salt, info: Data(purpose.utf8), outputByteCount: length)45    }4647    public static func randomSalt(_ count: Int = 16) -> Data {48        var bytes = [UInt8](repeating: 0, count: count)49        _ = SecRandomCopyBytes(kSecRandomDefault, count, &bytes)50        return Data(bytes)51    }5253    /// PBKDF2-HMAC-SHA256. The salt is random and stored next to the ciphertext; it is not secret.54    public static func key(fromPassphrase passphrase: String, salt: Data, iterations: Int = defaultIterations, length: Int = 32) throws -> SymmetricKey {55        SymmetricKey(data: try pbkdf2(password: Data(normalize(passphrase).utf8), salt: salt, iterations: iterations, length: length))56    }5758    public static func pbkdf2(password: Data, salt: Data, iterations: Int, length: Int) throws -> Data {59        guard iterations > 0, length > 0 else { throw CryptoError.derivationFailed }60        var out = [UInt8](repeating: 0, count: length)61        let status = password.withUnsafeBytes { pw in62            salt.withUnsafeBytes { s in63                CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), pw.bindMemory(to: CChar.self).baseAddress, password.count,64                                     s.bindMemory(to: UInt8.self).baseAddress, salt.count,65                                     CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), UInt32(iterations), &out, length)66            }67        }68        guard status == kCCSuccess else { throw CryptoError.derivationFailed }69        return Data(out)70    }7172    /// Codes are compared without dashes, spaces or case.73    public static func normalize(_ passphrase: String) -> String {74        guard PairingCode.looksLikeCode(passphrase) else { return passphrase }75        return PairingCode.canonical(passphrase)76    }77}7879/// Human-friendly sync passphrase: 5 random groups of 4 + 1 checksum group, from an alphabet without 0/O/1/I/L.80public enum PairingCode {81    public static let alphabet = Array("ABCDEFGHJKMNPQRSTUVWXYZ23456789")   // 31 symbols82    static let groupCount = 6, groupSize = 48384    public static func generate() -> String {85        var rng = SystemRandomNumberGenerator()86        let body = (0..<(groupCount - 1) * groupSize).map { _ in alphabet[Int.random(in: 0..<alphabet.count, using: &rng)] }87        return format(body + checksum(body))88    }8990    public static func canonical(_ code: String) -> String {91        String(code.uppercased().filter { alphabet.contains($0) })92    }9394    static func looksLikeCode(_ text: String) -> Bool {95        let stripped = text.uppercased().filter { !$0.isWhitespace && $0 != "-" }96        return stripped.count == groupCount * groupSize && stripped.allSatisfy { alphabet.contains($0) }97    }9899    public static func isValid(_ code: String) -> Bool {100        guard looksLikeCode(code) else { return false }101        let chars = Array(canonical(code))102        return Array(chars.suffix(groupSize)) == checksum(Array(chars.prefix((groupCount - 1) * groupSize)))103    }104105    /// Returns the canonical dashed form or throws when the checksum does not match (typo detection).106    public static func validated(_ code: String) throws -> String {107        guard isValid(code) else { throw CryptoError.invalidCode }108        return format(Array(canonical(code)))109    }110111    static func checksum(_ body: [Character]) -> [Character] {112        let digest = Array(SHA256.hash(data: Data(String(body).utf8)))113        return (0..<groupSize).map { alphabet[Int(digest[$0]) % alphabet.count] }114    }115116    static func format(_ chars: [Character]) -> String {117        stride(from: 0, to: chars.count, by: groupSize).map { String(chars[$0..<min($0 + groupSize, chars.count)]) }.joined(separator: "-")118    }119}120121public enum APIKeyHasher {122    static let base62 = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")123    public static let prefix = "lc-"124125    public static func generate() -> String {126        var rng = SystemRandomNumberGenerator()127        return prefix + String((0..<32).map { _ in base62[Int.random(in: 0..<62, using: &rng)] })128    }129130    /// Lowercase hex SHA-256; only the hash is stored.131    public static func hash(_ key: String) -> String {132        SHA256.hash(data: Data(key.utf8)).map { String(format: "%02x", $0) }.joined()133    }134135    public static func constantTimeEquals(_ a: String, _ b: String) -> Bool {136        let x = Array(a.utf8), y = Array(b.utf8)137        var diff = UInt8(x.count == y.count ? 0 : 1)138        for i in 0..<max(x.count, y.count) { diff |= (i < x.count ? x[i] : 0) ^ (i < y.count ? y[i] : 0) }139        return diff == 0140    }141142    public static func verify(_ key: String, againstHash stored: String) -> Bool { constantTimeEquals(hash(key), stored) }143144    /// "lc-ab…yz" for display.145    public static func masked(_ key: String) -> String {146        key.count > 9 ? key.prefix(5) + "…" + key.suffix(4) : String(repeating: "•", count: key.count)147    }148}149
Files main
Menu

Theme