Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraVault/VaultCrypto.swift8// Module : Qyvora Vault9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import QyvoraStorage44import QyvoraSymmetric4546/// Errors of the Quantum Vault. No case carries secret data.47public enum VaultError: Error, Equatable, Sendable {48 public enum Corruption: Equatable, Sendable {49 /// The file is shorter than its declared structure.50 case truncated51 /// The file does not start with the vault magic.52 case badMagic53 /// The format version is not supported by this build.54 case unsupportedVersion(UInt16)55 /// The trailing SHA-256 checksum does not match: the file was damaged.56 case checksumMismatch57 /// The checksum matches but a field is out of range or inconsistent.58 case malformed59 }6061 /// No vault file exists yet.62 case notFound63 /// `create` was called while a vault file exists.64 case alreadyExists65 /// The operation needs an unlocked vault.66 case locked67 /// The password does not open the password slot.68 case wrongPassword69 /// The PIN does not open the PIN slot. `retryAllowedAt` is set when a delay now applies.70 case wrongPIN(retryAllowedAt: Date?)71 /// Too many wrong PINs: no attempt is accepted before `until`.72 case pinLocked(until: Date)73 /// The wipe-after-N policy fired: the vault was erased from this device.74 case wiped75 /// No PIN slot (or its device-bound Keychain material is gone, e.g. after a restore on another device).76 case pinNotEnabled77 /// No device slot.78 case deviceSlotNotEnabled79 /// The biometric check failed or was cancelled.80 case deviceAuthenticationFailed81 /// The device key is gone (biometrics re-enrolled, Keychain reset, other device): use the password.82 case deviceKeyUnavailable83 case secureEnclaveUnavailable84 /// The file (and its `.previous` copy, when one exists) is damaged.85 case corrupted(Corruption)86 /// The file is well formed but its HMAC or a record does not verify under the vault key: it was modified.87 case integrityFailure88 case recordNotFound89 /// Empty password, PIN shorter than six characters, KDF parameters out of range, oversized record.90 case invalidParameters91 /// The key-derivation function failed (memory allocation, parameters).92 case kdfFailure93 /// The system and engine implementations disagree: the vault refuses to work (fail closed).94 case selfTestFailed95 case storage(StorageError)96}9798/// One AES-256-GCM implementation. The vault has two of the same algorithm so each can check the other.99public protocol AEADBackend: Sendable {100 var name: String { get }101 /// Returns ciphertext ‖ tag (16 bytes). Key 32 bytes, nonce 12 bytes.102 func seal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes) throws(VaultError) -> Bytes103 /// Opens ciphertext ‖ tag. Any failure is `integrityFailure`; no plaintext is released.104 func open(key: Bytes, nonce: Bytes, sealed: Bytes, associatedData: Bytes) throws(VaultError) -> Bytes105}106107/// CryptoKit AES-GCM: the default for sealing real secrets, because the engine is unaudited.108public struct SystemAEAD: AEADBackend {109 public init() {}110 public var name: String { "AES-256-GCM (CryptoKit)" }111112 public func seal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes) throws(VaultError) -> Bytes {113 do {114 return try SystemCrypto.aes256GCMSeal(key: key, nonce: nonce, plaintext: plaintext, associatedData: associatedData)115 } catch {116 throw .invalidParameters117 }118 }119120 public func open(key: Bytes, nonce: Bytes, sealed: Bytes, associatedData: Bytes) throws(VaultError) -> Bytes {121 do {122 return try SystemCrypto.aes256GCMOpen(key: key, nonce: nonce, sealed: sealed, associatedData: associatedData)123 } catch {124 throw .integrityFailure125 }126 }127}128129/// The from-scratch engine (`QyvoraSymmetric.AES256GCM`).130public struct EngineAEAD: AEADBackend {131 public init() {}132 public var name: String { "AES-256-GCM (QYVORA engine)" }133134 public func seal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes) throws(VaultError) -> Bytes {135 guard let r = try? AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: associatedData) else {136 throw .invalidParameters137 }138 return r.ciphertext + r.tag139 }140141 public func open(key: Bytes, nonce: Bytes, sealed: Bytes, associatedData: Bytes) throws(VaultError) -> Bytes {142 guard sealed.count >= AES256GCM.tagSize else { throw .integrityFailure }143 let split = sealed.count - AES256GCM.tagSize144 guard let plain = try? AES256GCM.open(145 key: key, nonce: nonce, ciphertext: Bytes(sealed[0..<split]), tag: Bytes(sealed[split...]), associatedData: associatedData)146 else { throw .integrityFailure }147 return plain148 }149}150151/// Which implementation seals. Both open what the other sealed.152public enum AEADKind: String, Sendable, Codable, CaseIterable {153 case system154 case engine155156 public var backend: any AEADBackend {157 switch self {158 case .system: return SystemAEAD()159 case .engine: return EngineAEAD()160 }161 }162}163164/// Cross-check of the system primitives against the engine. The vault runs it before creating or unlocking165/// and refuses to continue if any comparison fails.166public enum VaultSelfTest {167 /// The result of one run, cached for the life of the process.168 public static let passed: Bool = (try? run()) != nil169170 /// Throws `selfTestFailed` on the first disagreement.171 public static func run() throws(VaultError) {172 let key = Bytes((0..<32).map { UInt8($0 &* 7 &+ 3) })173 let nonce = Bytes((0..<12).map { UInt8($0 &* 13 &+ 1) })174 let aad = Bytes("qyvora self-test".utf8)175 let system = SystemAEAD(), engine = EngineAEAD()176 for size in [0, 1, 15, 16, 17, 64, 257] {177 let plain = Bytes((0..<size).map { UInt8(truncatingIfNeeded: $0 &* 31 &+ 5) })178 let a = try system.seal(key: key, nonce: nonce, plaintext: plain, associatedData: aad)179 let b = try engine.seal(key: key, nonce: nonce, plaintext: plain, associatedData: aad)180 guard a == b, a.count == size + 16 else { throw .selfTestFailed }181 guard (try? engine.open(key: key, nonce: nonce, sealed: a, associatedData: aad)) == plain,182 (try? system.open(key: key, nonce: nonce, sealed: b, associatedData: aad)) == plain183 else { throw .selfTestFailed }184 var bad = a185 bad[bad.count - 1] ^= 0x80186 guard (try? engine.open(key: key, nonce: nonce, sealed: bad, associatedData: aad)) == nil,187 (try? system.open(key: key, nonce: nonce, sealed: bad, associatedData: aad)) == nil,188 (try? engine.open(key: key, nonce: nonce, sealed: a, associatedData: aad + [0])) == nil,189 (try? system.open(key: key, nonce: nonce, sealed: a, associatedData: aad + [0])) == nil190 else { throw .selfTestFailed }191 }192 let message = Bytes("QYVORA".utf8)193 guard SystemCrypto.sha256(message) == SHA256.hash(message),194 SystemCrypto.hmacSHA256(key: key, message: message) == HMAC<SHA256>.authenticate(key: key, message: message),195 SystemCrypto.hkdfSHA256(inputKeyMaterial: key, salt: nonce, info: aad, length: 80)196 == HKDF<SHA256>.deriveKey(inputKeyMaterial: key, salt: nonce, info: aad, length: 80),197 (try? SystemCrypto.pbkdf2SHA512(password: message, salt: nonce, iterations: 3, length: 70))198 == PBKDF2<SHA512>.deriveKey(password: message, salt: nonce, iterations: 3, length: 70)199 else { throw .selfTestFailed }200 }201}202203/// Cost parameters of the password-based key derivation. They are stored in every slot and backup header.204public struct KDFParameters: Codable, Sendable, Equatable {205 /// Argon2id memory in KiB.206 public var argon2MemoryKiB: UInt32207 /// Argon2id passes (t).208 public var argon2Iterations: UInt32209 /// Argon2id lanes (p).210 public var argon2Parallelism: UInt32211 /// PBKDF2-HMAC-SHA512 iterations.212 public var pbkdf2Iterations: UInt32213214 public init(argon2MemoryKiB: UInt32, argon2Iterations: UInt32, argon2Parallelism: UInt32, pbkdf2Iterations: UInt32) {215 self.argon2MemoryKiB = argon2MemoryKiB216 self.argon2Iterations = argon2Iterations217 self.argon2Parallelism = argon2Parallelism218 self.pbkdf2Iterations = pbkdf2Iterations219 }220221 /// Default: Argon2id 64 MiB, t = 3, p = 4 (RFC 9106 second recommendation) and PBKDF2 with 600 000 iterations.222 public static let standard = KDFParameters(argon2MemoryKiB: 65_536, argon2Iterations: 3, argon2Parallelism: 4, pbkdf2Iterations: 600_000)223224 /// Tiny parameters for unit tests only. They give no protection.225 public static let insecureForTesting = KDFParameters(argon2MemoryKiB: 32, argon2Iterations: 1, argon2Parallelism: 1, pbkdf2Iterations: 8)226227 /// Bounds accepted when reading a file: they stop a forged header from requesting gigabytes of memory228 /// or hours of computation. Memory 8 KiB per lane to 2 GiB, t 1...64, p 1...16, PBKDF2 1...10 000 000.229 public var isWithinLimits: Bool {230 (1...16).contains(argon2Parallelism) && (1...64).contains(argon2Iterations)231 && argon2MemoryKiB >= 8 * argon2Parallelism && argon2MemoryKiB <= 1 << 21232 && (1...10_000_000).contains(pbkdf2Iterations)233 }234235 /// The cost this device accepts to pay for a file it did not write itself (QYV-SVC-012): Argon2id up to 256 MiB,236 /// 16 passes and 16 lanes, PBKDF2 up to 2 400 000 iterations — four times the default of each. The format bound237 /// (`isWithinLimits`) is far higher: a forged header inside it could ask for 2 GiB, which iOS answers by ending the238 /// application, before the password can even be checked. A file above the ceiling is refused, not opened slowly.239 public static let deviceCeiling = KDFParameters(argon2MemoryKiB: 262_144, argon2Iterations: 16, argon2Parallelism: 16, pbkdf2Iterations: 2_400_000)240241 /// True when every cost is at or below the one of `ceiling`.242 public func isWithin(_ ceiling: KDFParameters) -> Bool {243 argon2MemoryKiB <= ceiling.argon2MemoryKiB && argon2Iterations <= ceiling.argon2Iterations244 && argon2Parallelism <= ceiling.argon2Parallelism && pbkdf2Iterations <= ceiling.pbkdf2Iterations245 }246247 public static let encodedSize = 16248249 public func encode(into w: inout ByteWriter) {250 w.u32(argon2MemoryKiB)251 w.u32(argon2Iterations)252 w.u32(argon2Parallelism)253 w.u32(pbkdf2Iterations)254 }255256 public init(from r: inout ByteReader) throws(ByteReaderError) {257 argon2MemoryKiB = try r.u32()258 argon2Iterations = try r.u32()259 argon2Parallelism = try r.u32()260 pbkdf2Iterations = try r.u32()261 }262}263264/// The password-stretching combiner shared by the vault slots and the backup format:265///266/// a = Argon2id(secret, argon2Salt, memory, t, p, 32 bytes) — QYVORA engine267/// b = PBKDF2-HMAC-SHA512(secret, pbkdf2Salt, iterations, 32 bytes) — CommonCrypto268/// key = HKDF-SHA256(ikm = a ‖ b, salt = argon2Salt ‖ pbkdf2Salt, info = UTF-8(info), 32 bytes) — CryptoKit269///270/// HKDF is a dual-PRF combiner here: the result is at least as hard to guess as the stronger of the two inputs.271/// A defect in the from-scratch Argon2id can therefore not bring the vault below system PBKDF2, and the memory272/// hardness of Argon2id is kept as long as the engine is correct.273public enum KeyStretching {274 public static let saltSize = 16275 public static let keySize = 32276277 public static func deriveKey(278 secret: Bytes, argon2Salt: Bytes, pbkdf2Salt: Bytes, parameters: KDFParameters, info: String279 ) throws(VaultError) -> Bytes {280 guard parameters.isWithinLimits, argon2Salt.count == saltSize, pbkdf2Salt.count == saltSize else { throw .invalidParameters }281 let argonParameters = Argon2.Parameters(282 memoryKiB: Int(parameters.argon2MemoryKiB), iterations: Int(parameters.argon2Iterations),283 parallelism: Int(parameters.argon2Parallelism), tagLength: 32)284 guard var a = try? Argon2.id(password: secret, salt: argon2Salt, parameters: argonParameters) else { throw .kdfFailure }285 defer { SecureMemory.zero(&a) }286 guard var b = try? SystemCrypto.pbkdf2SHA512(password: secret, salt: pbkdf2Salt, iterations: parameters.pbkdf2Iterations, length: 32)287 else { throw .kdfFailure }288 defer { SecureMemory.zero(&b) }289 var ikm = a + b290 defer { SecureMemory.zero(&ikm) }291 return SystemCrypto.hkdfSHA256(inputKeyMaterial: ikm, salt: argon2Salt + pbkdf2Salt, info: Bytes(info.utf8), length: keySize)292 }293294 /// The byte string derived from a password: UTF-8 of its NFKD form (the same text typed on another keyboard295 /// or platform gives the same bytes).296 public static func passwordBytes(_ password: String) -> Bytes {297 Bytes(password.decomposedStringWithCompatibilityMapping.utf8)298 }299}300301/// Usage-separated subkeys of the master key: HKDF-SHA256(master, salt = vault id ‖ key epoch (4 bytes), info = label).302public enum VaultLabels {303 public static let records = "qyvora/v1/records"304 public static let fileMAC = "qyvora/v1/file-mac"305 public static let backup = "qyvora/v1/backup"306 public static let passwordSlot = "qyvora/v1/slot/password"307 public static let pinSlot = "qyvora/v1/slot/pin"308 static let slotAAD = "qyvora/v1/slot"309 static let recordAAD = "qyvora/v1/record"310}311