SPB Git

Repository Public

SecureEnclaveKey.swift 8.2 KB 185 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraStorage/SecureEnclaveKey.swift8// Module           : Qyvora Storage9// 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 CryptoKit42import Foundation43import QyvoraMath44import Security4546/// A device-bound P-256 key-agreement key used to wrap a short secret (ECIES-like construction, system primitives only).47///48/// Wrapped blob layout:49///50///     version (1 byte, 0x01) ‖ ephemeral public key (65 bytes, X9.63 uncompressed) ‖ nonce (12) ‖ ciphertext ‖ tag (16)51///52/// - shared secret = ECDH(ephemeral private key, device public key)53/// - key = HKDF-SHA256(shared secret, salt = ephemeral public ‖ device public (X9.63), info = "qyvora/v1/se-wrap", 32 bytes)54/// - AES-256-GCM, associated data = version ‖ ephemeral public key55///56/// Wrapping needs only the public key; unwrapping needs the Secure Enclave (the private key never leaves it).57public protocol SecureEnclaveKeyProvider: Sendable {58    /// False on hardware without a Secure Enclave (simulator, some Macs): callers must then skip this layer.59    var isAvailable: Bool { get }60    func wrap(_ secret: Bytes) throws(StorageError) -> Bytes61    func unwrap(_ blob: Bytes) throws(StorageError) -> Bytes62    /// Forgets the key: every blob wrapped under it becomes permanently unreadable.63    func destroy() throws(StorageError)64}6566enum EnclaveECIES {67    static let version: UInt8 = 0x0168    static let info = Data("qyvora/v1/se-wrap".utf8)69    static let publicKeySize = 657071    static func key(_ shared: SharedSecret, ephemeral: P256.KeyAgreement.PublicKey, device: P256.KeyAgreement.PublicKey) -> SymmetricKey {72        shared.hkdfDerivedSymmetricKey(73            using: SHA256.self, salt: ephemeral.x963Representation + device.x963Representation, sharedInfo: info, outputByteCount: 32)74    }7576    static func seal(_ secret: Bytes, device: P256.KeyAgreement.PublicKey) throws(StorageError) -> Bytes {77        let ephemeral = P256.KeyAgreement.PrivateKey()78        do {79            let shared = try ephemeral.sharedSecretFromKeyAgreement(with: device)80            let header = Data([version]) + ephemeral.publicKey.x963Representation81            let box = try AES.GCM.seal(Data(secret), using: key(shared, ephemeral: ephemeral.publicKey, device: device), authenticating: header)82            return Bytes(header) + Bytes(box.nonce) + Bytes(box.ciphertext) + Bytes(box.tag)83        } catch {84            throw .invalidData85        }86    }8788    static func open(89        _ blob: Bytes, device: P256.KeyAgreement.PublicKey, agree: (P256.KeyAgreement.PublicKey) throws -> SharedSecret90    ) throws(StorageError) -> Bytes {91        let headerSize = 1 + publicKeySize92        guard blob.count >= headerSize + 12 + 16, blob[0] == version else { throw .invalidData }93        do {94            let ephemeral = try P256.KeyAgreement.PublicKey(x963Representation: Data(blob[1..<headerSize]))95            let shared = try agree(ephemeral)96            let box = try AES.GCM.SealedBox(97                nonce: AES.GCM.Nonce(data: Data(blob[headerSize..<headerSize + 12])),98                ciphertext: Data(blob[(headerSize + 12)..<(blob.count - 16)]),99                tag: Data(blob[(blob.count - 16)...]))100            let plain = try AES.GCM.open(box, using: key(shared, ephemeral: ephemeral, device: device), authenticating: Data(blob[0..<headerSize]))101            return Bytes(plain)102        } catch {103            throw .invalidData104        }105    }106}107108/// The real Secure Enclave key (`SecureEnclave.P256.KeyAgreement`). Its opaque handle — an encrypted blob only this109/// device's Secure Enclave can use — is kept in the Keychain under `account`; the key is created on first use.110public struct SystemSecureEnclaveKey: SecureEnclaveKeyProvider {111    private let keychain: any KeychainStore112    private let account: String113114    public init(keychain: any KeychainStore, account: String = "secure-enclave-wrap-key") {115        self.keychain = keychain116        self.account = account117    }118119    public var isAvailable: Bool { SecureEnclave.isAvailable }120121    private func key(create: Bool) throws(StorageError) -> SecureEnclave.P256.KeyAgreement.PrivateKey {122        guard isAvailable else { throw .secureEnclaveUnavailable }123        if keychain.contains(account: account) {124            let handle = try keychain.get(account: account, prompt: nil)125            guard let key = try? SecureEnclave.P256.KeyAgreement.PrivateKey(dataRepresentation: Data(handle)) else { throw .invalidData }126            return key127        }128        guard create else { throw .notFound }129        var error: Unmanaged<CFError>?130        guard let control = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .privateKeyUsage, &error) else {131            error?.release()132            throw .secureEnclaveUnavailable133        }134        guard let key = try? SecureEnclave.P256.KeyAgreement.PrivateKey(accessControl: control) else { throw .secureEnclaveUnavailable }135        try keychain.set(Bytes(key.dataRepresentation), account: account, access: .passcodeSetThisDeviceOnly)136        return key137    }138139    public func wrap(_ secret: Bytes) throws(StorageError) -> Bytes {140        try EnclaveECIES.seal(secret, device: try key(create: true).publicKey)141    }142143    public func unwrap(_ blob: Bytes) throws(StorageError) -> Bytes {144        let k = try key(create: false)145        return try EnclaveECIES.open(blob, device: k.publicKey) { try k.sharedSecretFromKeyAgreement(with: $0) }146    }147148    public func destroy() throws(StorageError) {149        try keychain.delete(account: account)150    }151}152153/// Test double: the same construction with a software P-256 key held in memory.154public final class SoftwareEnclaveKey: SecureEnclaveKeyProvider, @unchecked Sendable {155    private let lock = NSLock()156    private var key: P256.KeyAgreement.PrivateKey?157    public let isAvailable: Bool158159    public init(available: Bool = true) {160        isAvailable = available161        key = available ? P256.KeyAgreement.PrivateKey() : nil162    }163164    public func wrap(_ secret: Bytes) throws(StorageError) -> Bytes {165        guard isAvailable else { throw .secureEnclaveUnavailable }166        let k = lock.withLock { () -> P256.KeyAgreement.PrivateKey in167            if let key { return key }168            let fresh = P256.KeyAgreement.PrivateKey()169            key = fresh170            return fresh171        }172        return try EnclaveECIES.seal(secret, device: k.publicKey)173    }174175    public func unwrap(_ blob: Bytes) throws(StorageError) -> Bytes {176        guard isAvailable else { throw .secureEnclaveUnavailable }177        guard let k = lock.withLock({ key }) else { throw .notFound }178        return try EnclaveECIES.open(blob, device: k.publicKey) { try k.sharedSecretFromKeyAgreement(with: $0) }179    }180181    public func destroy() throws(StorageError) {182        lock.withLock { key = nil }183    }184}185
Files main
Menu

Theme