import Foundation import CryptoKit import CommonCrypto /// Decrypts the init config file (format: XUQM-CONFIG-V1...). /// Algorithm: AES-256-GCM with PBKDF2-HMAC-SHA256 key derivation (120,000 iterations). enum ConfigFileCrypto { private static let magic = "XUQM-CONFIG-V1" private static let passphrase = "xuqm-config-file-v1.2026.internal" private static let keyByteCount = 32 private static let pbkdf2Iterations: UInt32 = 120_000 static func decrypt(_ content: String) throws -> String { let parts = content.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: ".") guard parts.count == 4, parts[0] == magic else { throw ConfigFileError.invalidFormat } guard let salt = base64UrlDecode(parts[1]), let iv = base64UrlDecode(parts[2]), let ciphertext = base64UrlDecode(parts[3]) else { throw ConfigFileError.invalidFormat } let key = try deriveKey(salt: salt) let combined = iv + ciphertext let sealedBox = try AES.GCM.SealedBox(combined: combined) let decrypted = try AES.GCM.open(sealedBox, using: key) guard let plaintext = String(data: decrypted, encoding: .utf8) else { throw ConfigFileError.decryptionFailed } return plaintext } private static func deriveKey(salt: Data) throws -> SymmetricKey { let passphraseBytes = Array(passphrase.utf8) let saltBytes = Array(salt) var derivedKey = [UInt8](repeating: 0, count: keyByteCount) let status = CCKeyDerivationPBKDF( CCPBKDFAlgorithm(kCCPBKDF2), passphrase, passphraseBytes.count, saltBytes, saltBytes.count, CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), pbkdf2Iterations, &derivedKey, keyByteCount ) guard status == kCCSuccess else { throw ConfigFileError.keyDerivationFailed } return SymmetricKey(data: Data(derivedKey)) } private static func base64UrlDecode(_ value: String) -> Data? { var s = value.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") let rem = s.count % 4 if rem > 0 { s += String(repeating: "=", count: 4 - rem) } return Data(base64Encoded: s) } } enum ConfigFileError: Error { case invalidFormat case keyDerivationFailed case decryptionFailed }