SPB Git

Repository Public

SystemCrypto.swift 5.4 KB 117 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraVault/SystemCrypto.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 CommonCrypto42import CryptoKit43import Foundation44import QyvoraMath4546/// The operating-system primitives used next to the from-scratch engine (CryptoKit and CommonCrypto).47///48/// The QYVORA engine is unaudited. Wherever a real secret is protected, the vault therefore uses these49/// audited implementations by default and cross-checks them against the engine (`VaultSelfTest`).50/// This file imports no engine module on purpose, so the two families cannot be confused.51public enum SystemCrypto {52    public enum Failure: Error, Equatable, Sendable {53        case invalidKey54        case invalidNonce55        case truncated56        case authenticationFailed57        case invalidParameters58    }5960    public static func sha256(_ data: Bytes) -> Bytes {61        Bytes(CryptoKit.SHA256.hash(data: data))62    }6364    public static func hmacSHA256(key: Bytes, message: Bytes) -> Bytes {65        Bytes(CryptoKit.HMAC<CryptoKit.SHA256>.authenticationCode(for: message, using: SymmetricKey(data: key)))66    }6768    /// HKDF-SHA256 (RFC 5869), extract then expand. `length` must be at most 8160 bytes.69    public static func hkdfSHA256(inputKeyMaterial: Bytes, salt: Bytes, info: Bytes, length: Int) -> Bytes {70        let key = CryptoKit.HKDF<CryptoKit.SHA256>.deriveKey(71            inputKeyMaterial: SymmetricKey(data: inputKeyMaterial), salt: salt, info: info, outputByteCount: length)72        return key.withUnsafeBytes { Bytes($0) }73    }7475    /// PBKDF2-HMAC-SHA512 from CommonCrypto.76    public static func pbkdf2SHA512(password: Bytes, salt: Bytes, iterations: UInt32, length: Int) throws(Failure) -> Bytes {77        guard iterations >= 1, length >= 1 else { throw .invalidParameters }78        var out = Bytes(repeating: 0, count: length)79        let status = password.withUnsafeBytes { pw -> Int32 in80            // CommonCrypto rejects a null password pointer; an empty password still needs a valid address81            var placeholder: Int8 = 082            return withUnsafePointer(to: &placeholder) { empty in83                let pwPointer = pw.baseAddress?.assumingMemoryBound(to: Int8.self) ?? empty84                return salt.withUnsafeBufferPointer { s in85                    CCKeyDerivationPBKDF(86                        CCPBKDFAlgorithm(kCCPBKDF2), pwPointer, pw.count, s.baseAddress, s.count,87                        CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512), iterations, &out, length)88                }89            }90        }91        guard status == Int32(kCCSuccess) else { throw .invalidParameters }92        return out93    }9495    /// AES-256-GCM seal; returns ciphertext ‖ tag (16 bytes).96    public static func aes256GCMSeal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes) throws(Failure) -> Bytes {97        guard key.count == 32 else { throw .invalidKey }98        guard nonce.count == 12, let n = try? AES.GCM.Nonce(data: nonce) else { throw .invalidNonce }99        guard let box = try? AES.GCM.seal(plaintext, using: SymmetricKey(data: key), nonce: n, authenticating: associatedData) else {100            throw .invalidParameters101        }102        return Bytes(box.ciphertext) + Bytes(box.tag)103    }104105    /// AES-256-GCM open of ciphertext ‖ tag.106    public static func aes256GCMOpen(key: Bytes, nonce: Bytes, sealed: Bytes, associatedData: Bytes) throws(Failure) -> Bytes {107        guard key.count == 32 else { throw .invalidKey }108        guard nonce.count == 12, let n = try? AES.GCM.Nonce(data: nonce) else { throw .invalidNonce }109        guard sealed.count >= 16 else { throw .truncated }110        let split = sealed.count - 16111        guard let box = try? AES.GCM.SealedBox(nonce: n, ciphertext: sealed[0..<split], tag: sealed[split...]),112              let plain = try? AES.GCM.open(box, using: SymmetricKey(data: key), authenticating: associatedData)113        else { throw .authenticationFailed }114        return Bytes(plain)115    }116}117
Files main
Menu

Theme