SPB Git

Repository Public

ACVPTests.swift 11.8 KB 248 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraSLHDSATests/ACVPTests.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 Foundation42import QyvoraMath43import Testing4445@testable import QyvoraSLHDSA4647/// Replays the NIST ACVP known-answer files for SLH-DSA (FIPS 205).48///49/// By default the committed files are used (`Vectors/`: keyGen in full, sigGen and sigVer reduced by50/// `Vectors/reduce_vectors.py`). When the environment variable `QYVORA_SLHDSA_FULL_KAT` names a directory51/// holding the complete NIST files, everything is replayed instead. Both layouts are accepted there:52/// `<dir>/SLH-DSA-sigGen-FIPS205/internalProjection.json.gz` and `<dir>/sigGen.json.gz`.53enum ACVP {54    struct LoadError: Error, CustomStringConvertible {55        let description: String56    }5758    static var fullDirectory: String? {59        guard let dir = ProcessInfo.processInfo.environment["QYVORA_SLHDSA_FULL_KAT"], !dir.isEmpty else { return nil }60        return dir61    }6263    /// Removes the gzip framing (RFC 1952) and inflates the raw DEFLATE stream.64    static func gunzip(_ data: Data) throws -> Data {65        let b = [UInt8](data)66        guard b.count > 18, b[0] == 0x1f, b[1] == 0x8b, b[2] == 8 else { throw LoadError(description: "not a gzip file") }67        let flags = b[3]68        var i = 1069        if flags & 0x04 != 0 {70            guard i + 2 <= b.count else { throw LoadError(description: "truncated gzip header") }71            i += 2 + Int(b[i]) + Int(b[i + 1]) << 872        }73        for bit: UInt8 in [0x08, 0x10] where flags & bit != 0 {74            while i < b.count, b[i] != 0 { i += 1 }75            i += 176        }77        if flags & 0x02 != 0 { i += 2 }78        guard i < b.count - 8 else { throw LoadError(description: "truncated gzip file") }79        let deflate = NSData(data: data.subdata(in: i..<(b.count - 8)))80        return try deflate.decompressed(using: .zlib) as Data81    }8283    /// Loads the test groups of one mode (`keyGen`, `sigGen`, `sigVer`).84    static func groups(_ mode: String) throws -> [[String: Any]] {85        let url: URL86        if let dir = fullDirectory {87            let base = URL(fileURLWithPath: dir, isDirectory: true)88            let nist = base.appendingPathComponent("SLH-DSA-\(mode)-FIPS205/internalProjection.json.gz")89            let flat = base.appendingPathComponent("\(mode).json.gz")90            if FileManager.default.fileExists(atPath: nist.path) {91                url = nist92            } else if FileManager.default.fileExists(atPath: flat.path) {93                url = flat94            } else {95                throw LoadError(description: "QYVORA_SLHDSA_FULL_KAT: no \(mode) file under \(dir)")96            }97        } else {98            guard let vectors = Bundle.module.url(forResource: "Vectors", withExtension: nil) else {99                throw LoadError(description: "Vectors resource directory missing")100            }101            url = vectors.appendingPathComponent("\(mode).json.gz")102        }103        let json = try JSONSerialization.jsonObject(with: gunzip(Data(contentsOf: url)))104        guard let root = json as? [String: Any], root["algorithm"] as? String == "SLH-DSA", root["mode"] as? String == mode,105            let groups = root["testGroups"] as? [[String: Any]], !groups.isEmpty106        else { throw LoadError(description: "unexpected ACVP structure in \(url.path)") }107        return groups108    }109110    static func hex(_ test: [String: Any], _ key: String) throws -> Bytes {111        guard let s = test[key] as? String, let b = Bytes(hex: s) else { throw LoadError(description: "bad hex field \(key)") }112        return b113    }114115    static func optionalHex(_ test: [String: Any], _ key: String) throws -> Bytes? {116        test[key] == nil ? nil : try hex(test, key)117    }118119    /// Pass/total counters keyed by a printable label, reported at the end of each test.120    struct Tally {121        var rows: [String: (passed: Int, total: Int)] = [:]122        mutating func record(_ label: String, _ ok: Bool) {123            var r = rows[label] ?? (0, 0)124            r.total += 1125            if ok { r.passed += 1 }126            rows[label] = r127        }128        var passed: Int { rows.values.reduce(0) { $0 + $1.passed } }129        var total: Int { rows.values.reduce(0) { $0 + $1.total } }130        func report(_ title: String) {131            var lines = ["ACVP \(title) [\(ACVP.fullDirectory == nil ? "committed set" : "FULL files")]: \(passed)/\(total)"]132            for key in rows.keys.sorted() { lines.append("  \(key): \(rows[key]!.passed)/\(rows[key]!.total)") }133            print(lines.joined(separator: "\n"))134        }135    }136137    static func variant(_ group: [String: Any]) -> String {138        let interface = group["signatureInterface"] as? String ?? "?"139        let preHash = group["preHash"] as? String ?? "?"140        var label = interface == "internal" ? "internal" : "external/\(preHash)"141        if let det = group["deterministic"] as? Bool { label += det ? "/deterministic" : "/hedged" }142        return label143    }144}145146@Suite struct SLHDSAACVPTests {147    @Test func keyGen() throws {148        var tally = ACVP.Tally()149        for group in try ACVP.groups("keyGen") {150            let name = try #require(group["parameterSet"] as? String)151            let set = try #require(SLHDSA.ParameterSet(name: name))152            for test in try #require(group["tests"] as? [[String: Any]]) {153                let pair = try SLHDSA.keyGenInternal(154                    set, skSeed: ACVP.hex(test, "skSeed"), skPrf: ACVP.hex(test, "skPrf"), pkSeed: ACVP.hex(test, "pkSeed"))155                let ok = try pair.secretKey == ACVP.hex(test, "sk") && pair.publicKey == ACVP.hex(test, "pk")156                tally.record(name, ok)157                #expect(ok, "keyGen \(name) tcId \(test["tcId"] ?? "?")")158            }159        }160        tally.report("keyGen")161        #expect(tally.total >= 120 && tally.rows.count == 12)162    }163164    @Test func sigGen() throws {165        var tally = ACVP.Tally()166        var sets = Set<String>()167        for group in try ACVP.groups("sigGen") {168            let name = try #require(group["parameterSet"] as? String)169            let set = try #require(SLHDSA.ParameterSet(name: name))170            let interface = try #require(group["signatureInterface"] as? String)171            let preHash = try #require(group["preHash"] as? String)172            let deterministic = try #require(group["deterministic"] as? Bool)173            sets.insert(name)174            for test in try #require(group["tests"] as? [[String: Any]]) {175                let sk = try ACVP.hex(test, "sk")176                let message = try ACVP.hex(test, "message")177                let expected = try ACVP.hex(test, "signature")178                let addrnd = try ACVP.optionalHex(test, "additionalRandomness")179                #expect((addrnd == nil) == deterministic)180                let signature: Bytes181                if interface == "internal" {182                    signature = try SLHDSA.signInternal(set, message: message, secretKey: sk, addrnd: addrnd)183                } else {184                    let context = try ACVP.optionalHex(test, "context") ?? []185                    let randomization: SLHDSA.Randomization = addrnd.map { .explicit($0) } ?? .deterministic186                    if preHash == "pure" {187                        signature = try SLHDSA.sign(set, message: message, context: context, secretKey: sk, randomization: randomization)188                    } else {189                        let algName = try #require(test["hashAlg"] as? String)190                        let alg = try #require(SLHDSA.PreHash(rawValue: algName))191                        signature = try SLHDSA.signPreHash(192                            set, message: message, context: context, preHash: alg, secretKey: sk, randomization: randomization)193                    }194                }195                let ok = signature == expected196                tally.record("\(name) \(ACVP.variant(group))", ok)197                #expect(ok, "sigGen \(name) tcId \(test["tcId"] ?? "?")")198            }199        }200        tally.report("sigGen")201        #expect(sets.count == 12 && tally.rows.count == 72)202    }203204    @Test func sigVer() throws {205        var tally = ACVP.Tally()206        var reasons: [String: (passed: Int, total: Int)] = [:]207        var sets = Set<String>()208        for group in try ACVP.groups("sigVer") {209            let name = try #require(group["parameterSet"] as? String)210            let set = try #require(SLHDSA.ParameterSet(name: name))211            let interface = try #require(group["signatureInterface"] as? String)212            let preHash = try #require(group["preHash"] as? String)213            sets.insert(name)214            for test in try #require(group["tests"] as? [[String: Any]]) {215                let pk = try ACVP.hex(test, "pk")216                let message = try ACVP.hex(test, "message")217                let signature = try ACVP.hex(test, "signature")218                let expected = try #require(test["testPassed"] as? Bool)219                let verified: Bool220                if interface == "internal" {221                    verified = SLHDSA.verifyInternal(set, message: message, signature: signature, publicKey: pk)222                } else {223                    let context = try ACVP.optionalHex(test, "context") ?? []224                    if preHash == "pure" {225                        verified = SLHDSA.verify(set, message: message, signature: signature, context: context, publicKey: pk)226                    } else {227                        let algName = try #require(test["hashAlg"] as? String)228                        let alg = try #require(SLHDSA.PreHash(rawValue: algName))229                        verified = SLHDSA.verifyPreHash(230                            set, message: message, signature: signature, context: context, preHash: alg, publicKey: pk)231                    }232                }233                let ok = verified == expected234                tally.record("\(name) \(ACVP.variant(group))", ok)235                let reason = test["reason"] as? String ?? "?"236                var r = reasons[reason] ?? (0, 0)237                r.total += 1238                if ok { r.passed += 1 }239                reasons[reason] = r240                #expect(ok, "sigVer \(name) tcId \(test["tcId"] ?? "?") (\(reason))")241            }242        }243        tally.report("sigVer")244        print(reasons.keys.sorted().map { "  reason \"\($0)\": \(reasons[$0]!.passed)/\(reasons[$0]!.total)" }.joined(separator: "\n"))245        #expect(sets.count == 12 && tally.rows.count == 36 && reasons.count == 7)246    }247}248
Files main
Menu

Theme