SPB Git

Repository Public

PostQuantumACVP.swift 17.9 KB 362 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/ConformanceAuditTests/PostQuantumACVP.swift8// Module           : Tests9// 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 AuditSupport42import Foundation43import QyvoraMath44import Testing4546@testable import QyvoraMLDSA47@testable import QyvoraMLKEM48@testable import QyvoraSLHDSA4950// Independent replay of the NIST ACVP files (ML-KEM FIPS 203, ML-DSA FIPS 204, SLH-DSA FIPS 205) with51// exact counts per parameter set and per function. The vector files are those committed with the engine52// tests (Tests/<Module>Tests/Vectors); for SLH-DSA the complete NIST files are replayed instead when they53// are present on the machine and the run is a full one.5455@Suite struct ACVPMLKEM {56    static let source = "NIST ACVP (FIPS 203)"5758    @Test func keyGen() throws {59        var board = Board(source: Self.source)60        let url = AuditPaths.engineVectors("QyvoraMLKEM").appendingPathComponent("acvp-ML-KEM-keyGen-FIPS203.json.gz")61        for g in try AuditVectors.acvpGroups(url) {62            let ps = try #require(MLKEM.ParameterSet.allCases.first { $0.name == g.str("parameterSet") })63            for t in g.acvpTests {64                let pair = try? MLKEM.keyGenInternal(ps, d: t.hex("d") ?? [], z: t.hex("z") ?? [])65                let ok = pair != nil && pair?.encapsulationKey == t.hex("ek") && pair?.decapsulationKey == t.hex("dk")66                board.add("ML-KEM", ps.name, "keyGen", ok: ok, id: t["tcId"])67            }68        }69        board.finish(minimum: 75)70    }7172    @Test func encapDecap() throws {73        var board = Board(source: Self.source)74        let url = AuditPaths.engineVectors("QyvoraMLKEM").appendingPathComponent("acvp-ML-KEM-encapDecap-FIPS203.json.gz")75        for g in try AuditVectors.acvpGroups(url) {76            let ps = try #require(MLKEM.ParameterSet.allCases.first { $0.name == g.str("parameterSet") })77            let function = g.str("function")78            for t in g.acvpTests {79                var ok = false80                switch function {81                case "encapsulation":82                    if let ek = t.hex("ek"), let m = t.hex("m"), let r = try? MLKEM.encapsInternal(ps, encapsulationKey: ek, m: m) {83                        ok = r.ciphertext == t.hex("c") && r.sharedSecret == t.hex("k")84                        if let dk = t.hex("dk") {85                            ok = ok && (try? MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: r.ciphertext)) == r.sharedSecret86                        }87                    }88                case "decapsulation":89                    if let dk = t.hex("dk"), let c = t.hex("c") {90                        ok = (try? MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: c)) == t.hex("k")91                    }92                case "decapsulationKeyCheck":93                    ok = MLKEM.isValidDecapsulationKey(ps, t.hex("dk") ?? []) == t.flag("testPassed")94                case "encapsulationKeyCheck":95                    ok = MLKEM.isValidEncapsulationKey(ps, t.hex("ek") ?? []) == t.flag("testPassed")96                default:97                    ok = false98                }99                board.add("ML-KEM", ps.name, function, ok: ok, id: t["tcId"])100            }101        }102        board.finish(minimum: 165)103    }104}105106@Suite struct ACVPMLDSA {107    static let source = "NIST ACVP (FIPS 204)"108109    static func url(_ mode: String) -> URL {110        AuditPaths.engineVectors("QyvoraMLDSA").appendingPathComponent("acvp-ML-DSA-\(mode)-FIPS204.json.gz")111    }112113    static func preHash(_ name: String) -> MLDSA.PreHash? {114        switch name {115        case "SHA2-224": return .sha2_224116        case "SHA2-256": return .sha2_256117        case "SHA2-384": return .sha2_384118        case "SHA2-512": return .sha2_512119        case "SHA2-512/224": return .sha2_512_224120        case "SHA2-512/256": return .sha2_512_256121        case "SHA3-224": return .sha3_224122        case "SHA3-256": return .sha3_256123        case "SHA3-384": return .sha3_384124        case "SHA3-512": return .sha3_512125        case "SHAKE-128": return .shake128126        case "SHAKE-256": return .shake256127        default: return nil128        }129    }130131    /// Digest of the message for a HashML-DSA case: Keccak family by the engine (verified separately against the132    /// SHA-3 ACVP files), SHA-2 by system libraries, SHA-512/t from the pre-computed hashlib table.133    static func digest(_ name: String, _ m: Bytes, truncated: [String: [Bytes: Bytes]]) -> Bytes? {134        guard let h = preHash(name) else { return nil }135        if let k = MLDSA.KeccakPreHash.allCases.first(where: { $0.preHash == h }) { return k.digest(m) }136        if let d = ReferenceDigest.sha2(name, m) { return d }137        return truncated[name]?[m]138    }139140    /// SHA-512/224 and SHA-512/256 digests of every message that needs one, computed in one hashlib call per function.141    static func truncatedDigests(_ groups: [[String: Any]]) -> [String: [Bytes: Bytes]] {142        var out: [String: [Bytes: Bytes]] = [:]143        for (name, lib) in [("SHA2-512/224", "sha512_224"), ("SHA2-512/256", "sha512_256")] {144            var messages: [Bytes] = []145            for g in groups where g.str("preHash") == "preHash" {146                for t in g.acvpTests where t.str("hashAlg") == name { messages.append(t.hex("message") ?? []) }147            }148            if let digests = ReferenceDigest.hashlib(lib, messages) {149                out[name] = Dictionary(zip(messages, digests), uniquingKeysWith: { a, _ in a })150            }151        }152        return out153    }154155    static func variant(_ g: [String: Any]) -> String {156        var s = "\(g.str("signatureInterface"))/\(g.str("preHash"))"157        if g.flag("externalMu") { s += "/externalMu" }158        if g["deterministic"] != nil { s += g.flag("deterministic") ? "/deterministic" : "/hedged" }159        return s160    }161162    @Test func keyGen() throws {163        var board = Board(source: Self.source)164        for g in try AuditVectors.acvpGroups(Self.url("keyGen")) {165            let ps = try #require(MLDSA.ParameterSet.allCases.first { $0.name == g.str("parameterSet") })166            for t in g.acvpTests {167                let pair = try? MLDSA.keyGenInternal(ps, seed: t.hex("seed") ?? [])168                board.add("ML-DSA", ps.name, "keyGen", ok: pair != nil && pair?.publicKey == t.hex("pk") && pair?.privateKey == t.hex("sk"), id: t["tcId"])169            }170        }171        board.finish(minimum: 75)172    }173174    @Test func sigGen() throws {175        var board = Board(source: Self.source)176        let groups = try AuditVectors.acvpGroups(Self.url("sigGen"))177        let truncated = Self.truncatedDigests(groups)178        for g in groups {179            let ps = try #require(MLDSA.ParameterSet.allCases.first { $0.name == g.str("parameterSet") })180            let deterministic = g.flag("deterministic")181            let name = "sigGen " + Self.variant(g)182            for t in g.acvpTests {183                guard let sk = t.hex("sk"), let expected = t.hex("signature") else {184                    board.add("ML-DSA", ps.name, name, ok: false, id: t["tcId"])185                    continue186                }187                let rnd = deterministic ? Bytes(repeating: 0, count: 32) : (t.hex("rnd") ?? [])188                let randomness: MLDSA.Randomness = deterministic ? .deterministic : .explicit(rnd)189                var sig: Bytes?190                switch (g.str("signatureInterface"), g.str("preHash"), g.flag("externalMu")) {191                case ("external", "pure", false):192                    sig = try? MLDSA.sign(ps, privateKey: sk, message: t.hex("message") ?? [], context: t.hex("context") ?? [], randomness: randomness)193                case ("external", "preHash", false):194                    guard let h = Self.preHash(t.str("hashAlg")), let d = Self.digest(t.str("hashAlg"), t.hex("message") ?? [], truncated: truncated)195                    else {196                        board.skip("ML-DSA", ps.name, name)197                        continue198                    }199                    sig = try? MLDSA.signPreHashed(ps, privateKey: sk, digest: d, hash: h, context: t.hex("context") ?? [], randomness: randomness)200                case ("internal", _, false):201                    sig = try? MLDSA.signInternal(ps, privateKey: sk, message: t.hex("message") ?? [], rnd: rnd)202                case ("internal", _, true):203                    sig = try? MLDSA.signInternal(ps, privateKey: sk, mu: t.hex("mu") ?? [], rnd: rnd)204                default:205                    sig = nil206                }207                board.add("ML-DSA", ps.name, name, ok: sig != nil && sig == expected, id: t["tcId"])208            }209        }210        board.finish(minimum: 300)211    }212213    @Test func sigVer() throws {214        var board = Board(source: Self.source)215        let groups = try AuditVectors.acvpGroups(Self.url("sigVer"))216        let truncated = Self.truncatedDigests(groups)217        for g in groups {218            let ps = try #require(MLDSA.ParameterSet.allCases.first { $0.name == g.str("parameterSet") })219            let name = "sigVer " + Self.variant(g)220            for t in g.acvpTests {221                let pk = t.hex("pk") ?? [], sig = t.hex("signature") ?? []222                var result: Bool?223                switch (g.str("signatureInterface"), g.str("preHash"), g.flag("externalMu")) {224                case ("external", "pure", false):225                    result = MLDSA.verify(ps, publicKey: pk, message: t.hex("message") ?? [], signature: sig, context: t.hex("context") ?? [])226                case ("external", "preHash", false):227                    guard let h = Self.preHash(t.str("hashAlg")), let d = Self.digest(t.str("hashAlg"), t.hex("message") ?? [], truncated: truncated)228                    else {229                        board.skip("ML-DSA", ps.name, name)230                        continue231                    }232                    result = MLDSA.verifyPreHashed(ps, publicKey: pk, digest: d, signature: sig, hash: h, context: t.hex("context") ?? [])233                case ("internal", _, false):234                    result = MLDSA.verifyInternal(ps, publicKey: pk, message: t.hex("message") ?? [], signature: sig)235                case ("internal", _, true):236                    result = MLDSA.verifyInternal(ps, publicKey: pk, mu: t.hex("mu") ?? [], signature: sig)237                default:238                    result = nil239                }240                board.add("ML-DSA", ps.name, name, ok: result == t.flag("testPassed"), id: t["tcId"])241            }242        }243        board.finish(minimum: 150)244    }245}246247@Suite struct ACVPSLHDSA {248    /// Directory of the complete NIST files: `QY_SLHDSA_FULL_KAT`, else the owner's Rust library checkout.249    /// Used in full mode only (the complete sigGen file alone is several hundred slow signatures).250    static let fullDirectory: URL? = {251        guard AuditMode.isFull || ProcessInfo.processInfo.environment["QY_SLHDSA_FULL_KAT"] != nil else { return nil }252        let candidates = [253            ProcessInfo.processInfo.environment["QY_SLHDSA_FULL_KAT"],254            NSHomeDirectory() + "/Desktop/Cluster/projets/SP/spb-quantum-crypto/tests/kat/acvp",255        ].compactMap { $0 }256        return candidates.map { URL(fileURLWithPath: $0) }.first {257            FileManager.default.fileExists(atPath: $0.appendingPathComponent("SLH-DSA-sigGen-FIPS205/internalProjection.json.gz").path)258        }259    }()260261    static var source: String { fullDirectory == nil ? "NIST ACVP (FIPS 205, reduced committed set)" : "NIST ACVP (FIPS 205, complete files)" }262263    static func groups(_ mode: String) throws -> [[String: Any]] {264        if let dir = fullDirectory {265            return try AuditVectors.acvpGroups(dir.appendingPathComponent("SLH-DSA-\(mode)-FIPS205/internalProjection.json.gz"))266        }267        return try AuditVectors.acvpGroups(AuditPaths.engineVectors("QyvoraSLHDSA").appendingPathComponent("\(mode).json.gz"))268    }269270    static func variant(_ g: [String: Any]) -> String {271        var label = g.str("signatureInterface") == "internal" ? "internal" : "external/\(g.str("preHash"))"272        if let det = g["deterministic"] as? Bool { label += det ? "/deterministic" : "/hedged" }273        return label274    }275276    @Test func keyGen() throws {277        var board = Board(source: Self.source)278        for g in try Self.groups("keyGen") {279            let set = try #require(SLHDSA.ParameterSet(name: g.str("parameterSet")))280            for t in g.acvpTests {281                let pair = try? SLHDSA.keyGenInternal(set, skSeed: t.hex("skSeed") ?? [], skPrf: t.hex("skPrf") ?? [], pkSeed: t.hex("pkSeed") ?? [])282                board.add("SLH-DSA", set.name, "keyGen", ok: pair != nil && pair?.secretKey == t.hex("sk") && pair?.publicKey == t.hex("pk"), id: t["tcId"])283            }284        }285        board.finish(minimum: 120)286    }287288    /// One group of work for the concurrent replay.289    struct SigGenCase: Sendable {290        let set: SLHDSA.ParameterSet, name: String, id: Int291        let interface: String, preHash: String, hashAlg: String292        let sk: Bytes, message: Bytes, context: Bytes, addrnd: Bytes?, expected: Bytes293    }294295    @Test func sigGen() async throws {296        var cases: [SigGenCase] = []297        for g in try Self.groups("sigGen") {298            let set = try #require(SLHDSA.ParameterSet(name: g.str("parameterSet")))299            for t in g.acvpTests {300                cases.append(301                    SigGenCase(302                        set: set, name: "sigGen " + Self.variant(g), id: t.integer("tcId") ?? -1,303                        interface: g.str("signatureInterface"), preHash: g.str("preHash"), hashAlg: t.str("hashAlg"),304                        sk: t.hex("sk") ?? [], message: t.hex("message") ?? [], context: t.hex("context") ?? [],305                        addrnd: t.hex("additionalRandomness"), expected: t.hex("signature") ?? []))306            }307        }308        // Signing with the "s" sets is slow: the cases are independent and replayed concurrently.309        let results = await withTaskGroup(of: (Int, Bool).self) { group in310            for (i, c) in cases.enumerated() {311                group.addTask {312                    let sig: Bytes?313                    if c.interface == "internal" {314                        sig = try? SLHDSA.signInternal(c.set, message: c.message, secretKey: c.sk, addrnd: c.addrnd)315                    } else {316                        let randomization: SLHDSA.Randomization = c.addrnd.map { .explicit($0) } ?? .deterministic317                        if c.preHash == "pure" {318                            sig = try? SLHDSA.sign(c.set, message: c.message, context: c.context, secretKey: c.sk, randomization: randomization)319                        } else if let alg = SLHDSA.PreHash(rawValue: c.hashAlg) {320                            sig = try? SLHDSA.signPreHash(321                                c.set, message: c.message, context: c.context, preHash: alg, secretKey: c.sk, randomization: randomization)322                        } else {323                            sig = nil324                        }325                    }326                    return (i, sig != nil && sig == c.expected)327                }328            }329            var out = [Bool](repeating: false, count: cases.count)330            for await (i, ok) in group { out[i] = ok }331            return out332        }333        var board = Board(source: Self.source)334        for (c, ok) in zip(cases, results) { board.add("SLH-DSA", c.set.name, c.name, ok: ok, id: c.id) }335        board.finish(minimum: 72)336    }337338    @Test func sigVer() throws {339        var board = Board(source: Self.source)340        for g in try Self.groups("sigVer") {341            let set = try #require(SLHDSA.ParameterSet(name: g.str("parameterSet")))342            let name = "sigVer " + Self.variant(g)343            for t in g.acvpTests {344                let pk = t.hex("pk") ?? [], message = t.hex("message") ?? [], sig = t.hex("signature") ?? []345                let verified: Bool346                if g.str("signatureInterface") == "internal" {347                    verified = SLHDSA.verifyInternal(set, message: message, signature: sig, publicKey: pk)348                } else if g.str("preHash") == "pure" {349                    verified = SLHDSA.verify(set, message: message, signature: sig, context: t.hex("context") ?? [], publicKey: pk)350                } else if let alg = SLHDSA.PreHash(rawValue: t.str("hashAlg")) {351                    verified = SLHDSA.verifyPreHash(set, message: message, signature: sig, context: t.hex("context") ?? [], preHash: alg, publicKey: pk)352                } else {353                    board.skip("SLH-DSA", set.name, name)354                    continue355                }356                board.add("SLH-DSA", set.name, name, ok: verified == t.flag("testPassed"), id: t["tcId"])357            }358        }359        board.finish(minimum: 72)360    }361}362
Files main
Menu

Theme