SPB Git

Repository Public

WycheproofTests.swift 20.2 KB 439 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/WycheproofAuditTests/WycheproofTests.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 QyvoraIdentity44import QyvoraMath45import Testing4647@testable import QyvoraMLDSA48@testable import QyvoraMLKEM49@testable import QyvoraSecp256k150@testable import QyvoraSymmetric5152// Replay of the Wycheproof vectors stored in security/vectors/wycheproof (pinned revision, see53// MANIFEST.json). Rule for every case: a "valid" vector must be accepted with the expected output,54// an "invalid" one must be rejected (error or false, never a trap), an "acceptable" one may go55// either way and is only tallied. Cases outside the engine's interface (for example AES-GCM with a56// nonce that is not 96 bits, which the public API refuses) are replayed through the internal entry57// point when one exists and are otherwise counted as skipped, never as passed.5859struct Tally {60    var cases = 0, failed = 0, skipped = 0, acceptableAccepted = 0, acceptableRejected = 061    var failures: [String] = []62    var extraNote = ""6364    mutating func check(_ tc: [String: Any], accepted: Bool) {65        cases += 166        switch tc.str("result") {67        case "valid": if !accepted { fail(tc, "valid vector rejected") }68        case "invalid": if accepted { fail(tc, "invalid vector accepted") }69        default: if accepted { acceptableAccepted += 1 } else { acceptableRejected += 1 }70        }71    }7273    mutating func fail(_ tc: [String: Any], _ why: String) {74        failed += 175        if failures.count < 20 { failures.append("tcId \(tc["tcId"] ?? "?") (\(tc.str("comment"))): \(why)") }76    }7778    mutating func skip() { skipped += 1 }7980    func finish(_ algorithm: String, _ file: String, parameterSet: String = "") {81        var note = file82        if acceptableAccepted + acceptableRejected > 0 {83            note += "; acceptable: \(acceptableAccepted) accepted, \(acceptableRejected) rejected"84        }85        if skipped > 0 { note += "; \(skipped) outside the engine interface (skipped)" }86        if !extraNote.isEmpty { note += "; " + extraNote }87        AuditRecorder.record(88            area: "wycheproof", name: file, algorithm: algorithm, parameterSet: parameterSet, oracle: "Wycheproof",89            cases: cases, failed: failed, skipped: skipped, note: note)90        #expect(failed == 0, "\(file): \(failures.joined(separator: " | "))")91        #expect(cases > 0, "\(file): no case replayed")92    }93}9495func wycheproofGroups(_ file: String) throws -> [[String: Any]] {96    try AuditVectors.acvpGroups(AuditPaths.vectors.appendingPathComponent("wycheproof/\(file).json.gz"))97}9899@Suite struct WycheproofECDSA {100    static func publicKey(_ group: [String: Any]) -> Bytes? {101        (group["publicKey"] as? [String: Any])?.hex("uncompressed")102    }103104    /// DER files. `lowS`: Bitcoin rules (BIP-62/146: high-s refused); otherwise plain ECDSA where both s and n−s verify.105    @Test(arguments: [("ecdsa_secp256k1_sha256_test", false), ("ecdsa_secp256k1_sha256_bitcoin_test", true)])106    func der(_ file: String, _ lowS: Bool) throws {107        var tally = Tally()108        for g in try wycheproofGroups(file) {109            let pk = try #require(Self.publicKey(g))110            for t in g.acvpTests {111                let digest = SHA256.hash(t.hex("msg") ?? [])112                var ok = false113                if let sig = t.hex("sig"), let compact = try? Secp256k1.parseDER(sig) {114                    ok = Secp256k1.verify(compactSignature: compact, digest: digest, publicKey: pk, requireLowS: lowS)115                }116                tally.check(t, accepted: ok)117            }118        }119        tally.finish("ECDSA secp256k1 (DER, SHA-256\(lowS ? ", Bitcoin low-s" : ""))", file)120    }121122    @Test func p1363() throws {123        var tally = Tally()124        for g in try wycheproofGroups("ecdsa_secp256k1_sha256_p1363_test") {125            let pk = try #require(Self.publicKey(g))126            for t in g.acvpTests {127                let digest = SHA256.hash(t.hex("msg") ?? [])128                let ok = Secp256k1.verify(compactSignature: t.hex("sig") ?? [], digest: digest, publicKey: pk, requireLowS: false)129                tally.check(t, accepted: ok)130            }131        }132        tally.finish("ECDSA secp256k1 (r‖s, SHA-256)", "ecdsa_secp256k1_sha256_p1363_test")133    }134}135136@Suite struct WycheproofAEAD {137    @Test func aesGCM() throws {138        var tally = Tally()139        var internalNonce = 0140        for g in try wycheproofGroups("aes_gcm_test") {141            let ivBits = g.integer("ivSize") ?? 0, tagBits = g.integer("tagSize") ?? 0142            for t in g.acvpTests {143                guard let key = t.hex("key"), let iv = t.hex("iv"), let aad = t.hex("aad"), let msg = t.hex("msg"),144                    let ct = t.hex("ct"), let tag = t.hex("tag"), tagBits == 128145                else {146                    tally.skip()147                    continue148                }149                guard let gcm = try? AESGCM(key: key) else {150                    tally.check(t, accepted: false)151                    continue152                }153                var accepted = false154                if ivBits == 96 {155                    if let opened = try? gcm.open(nonce: iv, ciphertext: ct, tag: tag, associatedData: aad) {156                        accepted = opened == msg157                        // encryption direction on valid vectors158                        if t.str("result") == "valid", let sealed = try? gcm.seal(nonce: iv, plaintext: msg, associatedData: aad) {159                            accepted = accepted && sealed.ciphertext == ct && sealed.tag == tag160                        }161                    }162                } else {163                    // The public interface refuses nonces that are not 96 bits…164                    let refused = (try? gcm.open(nonce: iv, ciphertext: ct, tag: tag, associatedData: aad)) == nil165                    if !refused { tally.fail(t, "non-96-bit nonce accepted by the public interface") }166                    // …and the internal GHASH-derived pre-counter path is checked against the vector (empty IV is invalid).167                    internalNonce += 1168                    if !iv.isEmpty, let opened = try? gcm.openAnyNonce(nonce: iv, ciphertext: ct, tag: tag, associatedData: aad) {169                        accepted = opened == msg170                    }171                }172                tally.check(t, accepted: accepted)173            }174        }175        tally.extraNote = "\(internalNonce) cases with a nonce that is not 96 bits: refused by the public interface, replayed through the internal entry point"176        tally.finish("AES-GCM (128/192/256-bit keys)", "aes_gcm_test")177    }178179    @Test func chaCha20Poly1305() throws {180        var tally = Tally()181        for g in try wycheproofGroups("chacha20_poly1305_test") {182            for t in g.acvpTests {183                guard let key = t.hex("key"), let iv = t.hex("iv"), let aad = t.hex("aad"), let msg = t.hex("msg"),184                    let ct = t.hex("ct"), let tag = t.hex("tag")185                else {186                    tally.skip()187                    continue188                }189                var accepted = false190                if let opened = try? ChaCha20Poly1305.open(key: key, nonce: iv, ciphertext: ct, tag: tag, associatedData: aad) {191                    accepted = opened == msg192                    if t.str("result") == "valid",193                        let sealed = try? ChaCha20Poly1305.seal(key: key, nonce: iv, plaintext: msg, associatedData: aad)194                    {195                        accepted = accepted && sealed.ciphertext == ct && sealed.tag == tag196                    }197                }198                tally.check(t, accepted: accepted)199            }200        }201        tally.finish("ChaCha20-Poly1305", "chacha20_poly1305_test")202    }203}204205@Suite struct WycheproofMACAndKDF {206    static func hmac(_ sha512: Bool, key: Bytes, message: Bytes) -> Bytes {207        sha512 ? HMAC<SHA512>.authenticate(key: key, message: message) : HMAC<SHA256>.authenticate(key: key, message: message)208    }209210    @Test(arguments: [("hmac_sha256_test", false), ("hmac_sha512_test", true)])211    func hmac(_ file: String, _ sha512: Bool) throws {212        var tally = Tally()213        for g in try wycheproofGroups(file) {214            let tagBytes = (g.integer("tagSize") ?? 0) / 8215            for t in g.acvpTests {216                guard let key = t.hex("key"), let msg = t.hex("msg"), let tag = t.hex("tag") else {217                    tally.skip()218                    continue219                }220                // Truncated tags of the vectors: compare the leading bytes, in constant time.221                let full = Self.hmac(sha512, key: key, message: msg)222                tally.check(t, accepted: tag.count == tagBytes && ConstantTime.equal(Bytes(full.prefix(tagBytes)), tag))223            }224        }225        tally.finish(sha512 ? "HMAC-SHA-512" : "HMAC-SHA-256", file)226    }227228    @Test(arguments: [("hkdf_sha256_test", false), ("hkdf_sha512_test", true)])229    func hkdf(_ file: String, _ sha512: Bool) throws {230        var tally = Tally()231        for g in try wycheproofGroups(file) {232            for t in g.acvpTests {233                guard let ikm = t.hex("ikm"), let salt = t.hex("salt"), let info = t.hex("info"), let okm = t.hex("okm"),234                    let size = t.integer("size")235                else {236                    tally.skip()237                    continue238                }239                let out =240                    sha512241                    ? HKDF<SHA512>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: size)242                    : HKDF<SHA256>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: size)243                // "invalid" = requested size above 255·HashLen: must be refused (nil)244                tally.check(t, accepted: out != nil && out == okm)245            }246        }247        tally.finish(sha512 ? "HKDF-SHA-512" : "HKDF-SHA-256", file)248    }249250    @Test(arguments: [("pbkdf2_hmacsha256_test", false), ("pbkdf2_hmacsha512_test", true)])251    func pbkdf2(_ file: String, _ sha512: Bool) throws {252        var tally = Tally()253        for g in try wycheproofGroups(file) {254            for t in g.acvpTests {255                guard let password = t.hex("password"), let salt = t.hex("salt"), let dk = t.hex("dk"),256                    let iterations = t.integer("iterationCount"), let length = t.integer("dkLen")257                else {258                    tally.skip()259                    continue260                }261                let out =262                    sha512263                    ? PBKDF2<SHA512>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)264                    : PBKDF2<SHA256>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)265                tally.check(t, accepted: out == dk)266            }267        }268        tally.finish(sha512 ? "PBKDF2-HMAC-SHA-512" : "PBKDF2-HMAC-SHA-256", file)269    }270271    /// X25519 is CryptoKit's in QYVORA (classical half of the hybrid exchange): this checks the wrapper's272    /// policy — correct shared secrets, all-zero shared secret refused.273    @Test func x25519() throws {274        var tally = Tally()275        var zeroRefused = 0, zeroTotal = 0276        for g in try wycheproofGroups("x25519_test") {277            for t in g.acvpTests {278                guard let pub = t.hex("public"), let priv = t.hex("private"), let shared = t.hex("shared") else {279                    tally.skip()280                    continue281                }282                let out = try? X25519.sharedSecret(privateKey: priv, publicKey: pub)283                let flags = t["flags"] as? [String] ?? []284                if flags.contains("ZeroSharedSecret") {285                    zeroTotal += 1286                    if out == nil { zeroRefused += 1 } else { tally.fail(t, "all-zero shared secret returned") }287                }288                tally.check(t, accepted: out == shared)289            }290        }291        #expect(zeroTotal > 0 && zeroRefused == zeroTotal)292        tally.finish("X25519 (CryptoKit, QYVORA wrapper policy)", "x25519_test")293    }294}295296@Suite struct WycheproofMLKEM {297    static let sets: [(Int, MLKEM.ParameterSet)] = [(512, .mlkem512), (768, .mlkem768), (1024, .mlkem1024)]298299    @Test(arguments: [512, 768, 1024]) func keygenSeed(_ bits: Int) throws {300        let ps = try #require(Self.sets.first { $0.0 == bits }?.1)301        var tally = Tally()302        for g in try wycheproofGroups("mlkem_\(bits)_keygen_seed_test") {303            for t in g.acvpTests {304                guard let seed = t.hex("seed"), let ek = t.hex("ek"), let dk = t.hex("dk") else {305                    tally.skip()306                    continue307                }308                let pair = try? MLKEM.keyPair(ps, seed: seed)309                tally.check(t, accepted: pair?.encapsulationKey == ek && pair?.decapsulationKey == dk)310            }311        }312        tally.finish("ML-KEM keygen from seed", "mlkem_\(bits)_keygen_seed_test", parameterSet: ps.name)313    }314315    /// Seed → key pair, then decapsulation of `c` (including malformed and malleable ciphertexts: implicit rejection).316    @Test(arguments: [512, 768, 1024]) func decapsFromSeed(_ bits: Int) throws {317        let ps = try #require(Self.sets.first { $0.0 == bits }?.1)318        var tally = Tally()319        for g in try wycheproofGroups("mlkem_\(bits)_test") {320            for t in g.acvpTests {321                guard let seed = t.hex("seed"), let c = t.hex("c"), let k = t.hex("K") else {322                    tally.skip()323                    continue324                }325                var accepted = false326                if let pair = try? MLKEM.keyPair(ps, seed: seed) {327                    let ekMatches = t.hex("ek").map { $0.isEmpty || $0 == pair.encapsulationKey } ?? true328                    if let out = try? MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: c) {329                        accepted = ekMatches && out == k330                    }331                }332                tally.check(t, accepted: accepted)333            }334        }335        tally.finish("ML-KEM decapsulation (seed keys)", "mlkem_\(bits)_test", parameterSet: ps.name)336    }337338    @Test(arguments: [512, 768, 1024]) func encaps(_ bits: Int) throws {339        let ps = try #require(Self.sets.first { $0.0 == bits }?.1)340        var tally = Tally()341        for g in try wycheproofGroups("mlkem_\(bits)_encaps_test") {342            for t in g.acvpTests {343                guard let m = t.hex("m"), let ek = t.hex("ek"), let c = t.hex("c"), let k = t.hex("K") else {344                    tally.skip()345                    continue346                }347                let out = try? MLKEM.encapsInternal(ps, encapsulationKey: ek, m: m)348                tally.check(t, accepted: out != nil && out?.ciphertext == c && out?.sharedSecret == k)349            }350        }351        tally.finish("ML-KEM encapsulation (key validation)", "mlkem_\(bits)_encaps_test", parameterSet: ps.name)352    }353354    @Test(arguments: [512, 768, 1024]) func decapsExpandedKey(_ bits: Int) throws {355        let ps = try #require(Self.sets.first { $0.0 == bits }?.1)356        var tally = Tally()357        for g in try wycheproofGroups("mlkem_\(bits)_semi_expanded_decaps_test") {358            for t in g.acvpTests {359                guard let dk = t.hex("dk"), let c = t.hex("c") else {360                    tally.skip()361                    continue362                }363                // Invalid cases (wrong lengths, key failing the FIPS 203 §7.3 hash check) carry no expected K.364                let out = try? MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: c)365                tally.check(t, accepted: out != nil && (t.hex("K").map { $0 == out } ?? (t.str("result") != "valid")))366            }367        }368        tally.finish("ML-KEM decapsulation (expanded key validation)", "mlkem_\(bits)_semi_expanded_decaps_test", parameterSet: ps.name)369    }370}371372@Suite struct WycheproofMLDSA {373    static let sets: [(Int, MLDSA.ParameterSet)] = [(44, .mldsa44), (65, .mldsa65), (87, .mldsa87)]374375    static func sign(_ ps: MLDSA.ParameterSet, sk: Bytes, pk: Bytes?, _ t: [String: Any]) -> Bytes? {376        let rnd = t.hex("rnd")377        let randomness: MLDSA.Randomness = rnd.map { .explicit($0) } ?? .deterministic378        if let msg = t.hex("msg"), t["msg"] != nil {379            return try? MLDSA.sign(ps, privateKey: sk, message: msg, context: t.hex("ctx") ?? [], randomness: randomness)380        }381        if let mu = t.hex("mu") {382            return try? MLDSA.signInternal(ps, privateKey: sk, mu: mu, rnd: rnd ?? Bytes(repeating: 0, count: 32))383        }384        return nil385    }386387    @Test(arguments: [44, 65, 87]) func signFromSeed(_ level: Int) throws {388        let ps = try #require(Self.sets.first { $0.0 == level }?.1)389        var tally = Tally()390        for g in try wycheproofGroups("mldsa_\(level)_sign_seed_test") {391            let pair = g.hex("privateSeed").flatMap { try? MLDSA.keyGenInternal(ps, seed: $0) }392            if let pk = g.hex("publicKey"), let pair, !pk.isEmpty { #expect(pair.publicKey == pk) }393            for t in g.acvpTests {394                guard let expected = t.hex("sig") else {395                    tally.skip()396                    continue397                }398                let sig = pair.flatMap { Self.sign(ps, sk: $0.privateKey, pk: $0.publicKey, t) }399                tally.check(t, accepted: sig != nil && sig == expected)400            }401        }402        tally.finish("ML-DSA signing (seed keys)", "mldsa_\(level)_sign_seed_test", parameterSet: ps.name)403    }404405    @Test(arguments: [44, 65, 87]) func signExpandedKey(_ level: Int) throws {406        let ps = try #require(Self.sets.first { $0.0 == level }?.1)407        var tally = Tally()408        for g in try wycheproofGroups("mldsa_\(level)_sign_noseed_test") {409            let sk = g.hex("privateKey") ?? []410            for t in g.acvpTests {411                guard let expected = t.hex("sig") else {412                    tally.skip()413                    continue414                }415                let sig = Self.sign(ps, sk: sk, pk: g.hex("publicKey"), t)416                tally.check(t, accepted: sig != nil && sig == expected)417            }418        }419        tally.finish("ML-DSA signing (expanded keys, key validation)", "mldsa_\(level)_sign_noseed_test", parameterSet: ps.name)420    }421422    @Test(arguments: [44, 65, 87]) func verify(_ level: Int) throws {423        let ps = try #require(Self.sets.first { $0.0 == level }?.1)424        var tally = Tally()425        for g in try wycheproofGroups("mldsa_\(level)_verify_test") {426            let pk = g.hex("publicKey") ?? []427            for t in g.acvpTests {428                guard let msg = t.hex("msg"), let sig = t.hex("sig") else {429                    tally.skip()430                    continue431                }432                let ok = MLDSA.verify(ps, publicKey: pk, message: msg, signature: sig, context: t.hex("ctx") ?? [])433                tally.check(t, accepted: ok)434            }435        }436        tally.finish("ML-DSA verification", "mldsa_\(level)_verify_test", parameterSet: ps.name)437    }438}439
Files main
Menu

Theme