SPB Git

Repository Public

QyvoraCrypto.swift 13.7 KB 186 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraCrypto/QyvoraCrypto.swift8// Module           : Qyvora Crypto9// 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// =============================================================================4041@_exported import QyvoraMath42@_exported import QyvoraKeccak43@_exported import QyvoraSymmetric44@_exported import QyvoraMLKEM45@_exported import QyvoraMLDSA46@_exported import QyvoraSLHDSA47@_exported import QyvoraSecp256k148@_exported import QyvoraEd255194950/// The QYVORA Cryptographic Engine: one import for every primitive, plus a catalogue that the51/// application shows on its "Cryptographic information" screen.52public enum QyvoraEngine {53    public static let version = "1.0.0"5455    /// Audit status of the from-scratch implementations. Passing test vectors is not a certification.56    public static let auditStatus = "Not audited. Validated against NIST ACVP vectors and independent implementations; not certified."5758    public enum Kind: String, Sendable, CaseIterable {59        case keyEncapsulation = "Key encapsulation"60        case signature = "Signature"61        case hash = "Hash / XOF"62        case mac = "MAC / KDF"63        case aead = "Authenticated encryption"64        case curve = "Elliptic curve"65    }6667    public struct Algorithm: Sendable, Identifiable, Equatable {68        public let name: String69        public let standard: String70        public let kind: Kind71        /// NIST security category (1–5) when the standard assigns one.72        public let category: Int?73        public let publicKeySize: Int?74        public let privateKeySize: Int?75        /// Signature or ciphertext size.76        public let outputSize: Int?77        /// What QYVORA uses it for; "available" when the engine provides it without a product use yet.78        public let use: String79        public var id: String { name }80        /// False for a primitive QYVORA uses from the operating system (CryptoKit) instead of implementing it: it is81        /// listed so that the catalogue names everything the product relies on, and is not part of the from-scratch82        /// engine, of its test vectors or of its self-test.83        public var isFromScratch: Bool { !systemPrimitives.contains(name) }84        private var systemPrimitives: Set<String> { QyvoraEngine.systemPrimitiveNames }85    }8687    /// Names of the catalogue entries that are system primitives (see `Algorithm.isFromScratch`).88    static let systemPrimitiveNames: Set<String> = ["X25519"]8990    /// The algorithms implemented from scratch in this engine: the catalogue without the system primitives.91    public static var engineAlgorithms: [Algorithm] { algorithms.filter(\.isFromScratch) }9293    public static let algorithms: [Algorithm] = {94        var list = [Algorithm]()95        let kemCategory: [Int] = [1, 3, 5]96        for (i, p) in MLKEM.ParameterSet.allCases.enumerated() {97            list.append(Algorithm(name: p.name, standard: "FIPS 203", kind: .keyEncapsulation, category: kemCategory[i],98                                  publicKeySize: p.encapsulationKeySize, privateKeySize: p.decapsulationKeySize, outputSize: p.ciphertextSize,99                                  use: p == .mlkem1024 ? "Device-to-device transfer and identity key exchange (hybrid with X25519)" : "Available"))100        }101        let dsaCategory: [Int] = [2, 3, 5]102        for (i, p) in MLDSA.ParameterSet.allCases.enumerated() {103            list.append(Algorithm(name: p.name, standard: "FIPS 204", kind: .signature, category: dsaCategory[i],104                                  publicKeySize: p.publicKeySize, privateKeySize: p.privateKeySize, outputSize: p.signatureSize,105                                  use: p == .mldsa87 ? "Quantum Identity signatures, backup and transfer authentication" : "Available"))106        }107        for p in SLHDSA.ParameterSet.allCases {108            list.append(Algorithm(name: p.name, standard: "FIPS 205", kind: .signature, category: p.securityCategory,109                                  publicKeySize: p.publicKeySize, privateKeySize: p.secretKeySize, outputSize: p.signatureSize,110                                  use: p == .shake_256f ? "Quantum Identity second signature (hash-based, conservative assumption)" : "Available"))111        }112        list += [113            Algorithm(name: "SHA3-224/256/384/512", standard: "FIPS 202", kind: .hash, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: nil, use: "Identity fingerprints, ML-KEM, ML-DSA"),114            Algorithm(name: "SHAKE128 / SHAKE256", standard: "FIPS 202", kind: .hash, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: nil, use: "ML-KEM, ML-DSA, SLH-DSA-SHAKE"),115            Algorithm(name: "Keccak-256", standard: "Ethereum Yellow Paper", kind: .hash, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: 32, use: "Ethereum addresses, transaction hashes, ABI selectors"),116            Algorithm(name: "cSHAKE / KMAC128 / KMAC256", standard: "SP 800-185", kind: .mac, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: nil, use: "Available"),117            Algorithm(name: "SHA-224/256/384/512", standard: "FIPS 180-4", kind: .hash, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: nil, use: "Bitcoin hashes, BIP-32/39, SLH-DSA-SHA2"),118            Algorithm(name: "RIPEMD-160", standard: "ISO/IEC 10118-3", kind: .hash, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: 20, use: "Bitcoin HASH160"),119            Algorithm(name: "BLAKE2b", standard: "RFC 7693", kind: .hash, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: nil, use: "Argon2id"),120            Algorithm(name: "HMAC / HKDF / PBKDF2", standard: "FIPS 198-1, RFC 5869, RFC 8018", kind: .mac, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: nil, use: "Key separation, BIP-32, BIP-39, RFC 6979"),121            Algorithm(name: "Argon2id", standard: "RFC 9106", kind: .mac, category: nil, publicKeySize: nil, privateKeySize: nil, outputSize: nil, use: "Vault and backup password hardening (combined with system PBKDF2)"),122            Algorithm(name: "AES-256-GCM", standard: "FIPS 197, SP 800-38D", kind: .aead, category: nil, publicKeySize: nil, privateKeySize: 32, outputSize: nil, use: "Cross-check of the system AES-256-GCM that seals the vault"),123            Algorithm(name: "ChaCha20-Poly1305", standard: "RFC 8439", kind: .aead, category: nil, publicKeySize: nil, privateKeySize: 32, outputSize: nil, use: "Available"),124            Algorithm(name: "secp256k1 ECDSA", standard: "SEC 2, RFC 6979", kind: .curve, category: nil, publicKeySize: 33, privateKeySize: 32, outputSize: 64, use: "Transaction signatures on Bitcoin, Litecoin, Dogecoin, Bitcoin Cash, the EVM networks and TRON (not quantum-resistant)"),125            Algorithm(name: "secp256k1 Schnorr", standard: "BIP-340", kind: .curve, category: nil, publicKeySize: 32, privateKeySize: 32, outputSize: 64, use: "Available. Implemented and tested, not used for spending: QYVORA signs Bitcoin transactions with ECDSA (Taproot preparation; not quantum-resistant)"),126            Algorithm(name: "Ed25519", standard: "RFC 8032", kind: .curve, category: nil, publicKeySize: 32, privateKeySize: 32, outputSize: 64, use: "Solana transaction signatures and SLIP-0010 key derivation (not quantum-resistant)"),127            // not an implementation of this engine: the operating system's, named here because the product relies on it128            Algorithm(name: "X25519", standard: "RFC 7748", kind: .curve, category: nil, publicKeySize: 32, privateKeySize: 32, outputSize: 32, use: "System implementation (CryptoKit), not part of this engine: the classical half of the hybrid envelope with ML-KEM-1024 (not quantum-resistant)"),129        ]130        return list131    }()132133    /// Known-answer self-test run at application start (hashes, secp256k1 key derivation and ECDSA signing, Ed25519, ML-KEM, ML-DSA, SLH-DSA, AES-256-GCM): a wrong result means the binary must not be trusted.134    public static func selfTest() -> Bool {135        guard SHA3.sha3_256([]).hex == "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a",136              SHA256.hash(Bytes("abc".utf8)).hex == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",137              (try? Secp256k1.publicKey(privateKey: Bytes(repeating: 0, count: 31) + [1]).hex) == "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"138        else { return false }139        // ECDSA signing, the operation that authorizes payments: the widely published RFC 6979 vector (key 1,140        // SHA-256("Satoshi Nakamoto")), then verification of the signature and refusal of a modified digest.141        let one = Bytes(repeating: 0, count: 31) + [1]142        let satoshi = SHA256.hash(Bytes("Satoshi Nakamoto".utf8))143        guard let ecdsa = try? Secp256k1.sign(digest: satoshi, privateKey: one),144              ecdsa.compact.hex == "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5",145              let onePublic = try? Secp256k1.publicKey(privateKey: one),146              Secp256k1.verify(compactSignature: ecdsa.compact, digest: satoshi, publicKey: onePublic),147              !Secp256k1.verify(compactSignature: ecdsa.compact, digest: SHA256.hash(satoshi), publicKey: onePublic),148              (try? Secp256k1.recoverPublicKey(compactSignature: ecdsa.compact, recoveryID: ecdsa.recoveryID, digest: satoshi)) == onePublic149        else { return false }150        // Ed25519, which signs Solana transactions: test vector 1 of RFC 8032 section 7.1 (empty message), then151        // verification of the signature and refusal of another message.152        let edSeed = Hex.decode("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60") ?? []153        guard let edPublic = try? Ed25519.publicKey(seed: edSeed),154              edPublic.hex == "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",155              let edSignature = try? Ed25519.sign(message: [], seed: edSeed),156              edSignature.hex == "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",157              Ed25519.verify(signature: edSignature, message: [], publicKey: edPublic),158              !Ed25519.verify(signature: edSignature, message: [0], publicKey: edPublic)159        else { return false }160        // Deterministic known answers. The post-quantum digests were produced by this engine at the revision161        // that passes the full NIST ACVP files; the AES-GCM value is test case 14 of the GCM specification.162        let z32 = Bytes(repeating: 0, count: 32), z16 = Bytes(repeating: 0, count: 16)163        let message = Bytes("QYVORA".utf8)164        guard let kem = try? MLKEM.keyGenInternal(.mlkem768, d: z32, z: z32),165              let enc = try? MLKEM.encapsInternal(.mlkem768, encapsulationKey: kem.encapsulationKey, m: z32),166              SHA3.sha3_256(kem.encapsulationKey + enc.ciphertext + enc.sharedSecret).hex == "0969fafc2a11f61ec22b1196979e28a3211f2852359bf684ba92cf0d9f54abc3",167              (try? MLKEM.decapsulate(.mlkem768, decapsulationKey: kem.decapsulationKey, ciphertext: enc.ciphertext)) == enc.sharedSecret168        else { return false }169        guard let dsa = try? MLDSA.keyGenInternal(.mldsa44, seed: z32),170              let sig = try? MLDSA.sign(.mldsa44, privateKey: dsa.privateKey, message: message, randomness: .deterministic),171              SHA3.sha3_256(dsa.publicKey + sig).hex == "9504a5b1d95e17f704386bb70167806a2f74f9e4b4089172984ad5bddeec5904",172              MLDSA.verify(.mldsa44, publicKey: dsa.publicKey, message: message, signature: sig),173              !MLDSA.verify(.mldsa44, publicKey: dsa.publicKey, message: message + [0], signature: sig)174        else { return false }175        guard let slh = try? SLHDSA.keyGenInternal(.shake_128f, skSeed: z16, skPrf: z16, pkSeed: z16),176              let hsig = try? SLHDSA.sign(.shake_128f, message: message, secretKey: slh.secretKey, randomization: .deterministic),177              SHA3.sha3_256(slh.publicKey + hsig).hex == "4cc3334357fa52f8e252c3f94d0a959117b3f5321c66348d19bf08695ead3c29",178              SLHDSA.verify(.shake_128f, message: message, signature: hsig, publicKey: slh.publicKey)179        else { return false }180        guard let gcm = try? AES256GCM.seal(key: z32, nonce: Bytes(repeating: 0, count: 12), plaintext: z16, associatedData: []),181              gcm.ciphertext.hex == "cea7403d4d606b6e074ec5d3baf39d18", gcm.tag.hex == "d0d1c8a799996bf0265b98b5d48ab919"182        else { return false }183        return true184    }185}186
Files main
Menu

Theme