Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Tests/ConformanceAuditTests/ClassicalVectors.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 QyvoraCore44import QyvoraMath45import Testing4647@testable import QyvoraKeccak48@testable import QyvoraSecp256k149@testable import QyvoraSymmetric5051// NIST ACVP hash vectors (SHA-2, SHA-3, SHAKE), NIST CAVP AES-256-GCM vectors, the GCM specification52// vectors, and the official BIP vectors stored in security/vectors/bip (BIP-32, BIP-39, BIP-173/350, BIP-340).53// RFC 8439, BIP-84, BIP-143, BIP-174 and BIP-380 vectors are embedded in the engine test targets and are54// counted by the engine test run (see the report, "engine test suites").5556/// Sponge over a message given as a bit string (ACVP SHA-3 files are bit oriented).57private func spongeBits(rate: Int, suffix: UInt8, message: Bytes, bitLength: Int, output: Int) -> Bytes {58 let q = bitLength / 8, r = bitLength % 859 if r == 0 {60 var s = KeccakSponge(rate: rate, suffix: suffix)61 s.absorb(Bytes(message.prefix(q)))62 return s.squeeze(output)63 }64 let tail = UInt16(message[q] >> UInt8(8 - r))65 let merged = tail | UInt16(suffix) << UInt16(r)66 if merged < 0x80 {67 var s = KeccakSponge(rate: rate, suffix: UInt8(merged))68 s.absorb(Bytes(message.prefix(q)))69 return s.squeeze(output)70 }71 var s = KeccakSponge(rate: rate, suffix: UInt8(merged >> 8))72 s.absorb(Bytes(message.prefix(q)) + [UInt8(merged & 0xff)])73 return s.squeeze(output)74}7576@Suite struct ACVPHashes {77 static let largeData = AuditMode.isFull7879 /// Expands the "largeMsg" description of an LDT case and feeds it to `update` in 1 MiB pieces.80 static func feedLarge(_ t: [String: Any], _ update: (Bytes) -> Void) -> Bool {81 guard let large = t["largeMsg"] as? [String: Any], let content = large.hex("content"), let bits = large.integer("fullLength"),82 large.str("expansionTechnique") == "repeating", bits % 8 == 0, !content.isEmpty, (bits / 8) % content.count == 083 else { return false }84 let total = bits / 885 var chunk = Bytes()86 while chunk.count < 1 << 20 { chunk += content }87 var done = 088 while total - done >= chunk.count {89 update(chunk)90 done += chunk.count91 }92 if done < total { update(Bytes(chunk.prefix(total - done))) }93 return true94 }9596 @Test(arguments: [("acvp-sha2-256.json.gz", 32), ("acvp-sha2-512.json.gz", 64)])97 func sha2(_ file: String, _ digest: Int) throws {98 let algorithm = digest == 32 ? "SHA-256" : "SHA-512"99 func hash(_ m: Bytes) -> Bytes { digest == 32 ? SHA256.hash(m) : SHA512.hash(m) }100 var board = Board(source: "NIST ACVP (FIPS 180-4)")101 for g in try AuditVectors.acvpGroups(AuditPaths.engineVectors("QyvoraSymmetric").appendingPathComponent(file)) {102 for t in g.acvpTests {103 switch g.str("testType") {104 case "AFT":105 let len = t.integer("len") ?? 0106 let msg = Bytes((t.hex("msg") ?? []).prefix(len / 8))107 board.add(algorithm, "", "AFT", ok: len % 8 == 0 && hash(msg) == t.hex("md"), id: t["tcId"])108 case "MCT":109 var seed = t.hex("msg") ?? []110 let length = seed.count111 for r in t["resultsArray"] as? [[String: Any]] ?? [] {112 var a = seed, b = seed, c = seed113 for _ in 0..<1000 {114 var m = a + b + c115 if m.count >= length { m.removeLast(m.count - length) } else { m += Bytes(repeating: 0, count: length - m.count) }116 a = b117 b = c118 c = hash(m)119 }120 seed = c121 board.add(algorithm, "", "MCT checkpoint (1000 iterations)", ok: c == r.hex("md"), id: t["tcId"])122 }123 case "LDT":124 guard Self.largeData else {125 board.skip(algorithm, "", "LDT (large data, full mode only)")126 continue127 }128 var out: Bytes = []129 var fed = false130 if digest == 32 {131 var h = SHA256()132 fed = Self.feedLarge(t) { h.update($0) }133 out = h.finalize()134 } else {135 var h = SHA512()136 fed = Self.feedLarge(t) { h.update($0) }137 out = h.finalize()138 }139 board.add(algorithm, "", "LDT (large data)", ok: fed && out == t.hex("md"), id: t["tcId"])140 default:141 board.skip(algorithm, "", "unknown test type \(g.str("testType"))")142 }143 }144 }145 board.finish(minimum: digest == 32 ? 612 : 1124)146 }147148 @Test(arguments: [("acvp-sha3-256.json.gz", 32), ("acvp-sha3-512.json.gz", 64)])149 func sha3(_ file: String, _ digest: Int) throws {150 let algorithm = digest == 32 ? "SHA3-256" : "SHA3-512"151 func hash(_ m: Bytes) -> Bytes { digest == 32 ? SHA3.sha3_256(m) : SHA3.sha3_512(m) }152 let rate = 200 - 2 * digest153 var board = Board(source: "NIST ACVP (FIPS 202)")154 for g in try AuditVectors.acvpGroups(AuditPaths.engineVectors("QyvoraKeccak").appendingPathComponent(file)) {155 for t in g.acvpTests {156 switch g.str("testType") {157 case "AFT":158 let msg = t.hex("msg") ?? [], len = t.integer("len") ?? 0, want = t.hex("md")159 var ok = spongeBits(rate: rate, suffix: 0x06, message: msg, bitLength: len, output: digest) == want160 if len % 8 == 0 { ok = ok && hash(Bytes(msg.prefix(len / 8))) == want }161 board.add(algorithm, "", len % 8 == 0 ? "AFT (byte-aligned)" : "AFT (bit-oriented)", ok: ok, id: t["tcId"])162 case "MCT":163 var md = t.hex("msg") ?? []164 for r in t["resultsArray"] as? [[String: Any]] ?? [] {165 for _ in 0..<1000 { md = hash(md) }166 board.add(algorithm, "", "MCT checkpoint (1000 iterations)", ok: md == r.hex("md"), id: t["tcId"])167 }168 case "LDT":169 guard Self.largeData else {170 board.skip(algorithm, "", "LDT (large data, full mode only)")171 continue172 }173 var s = KeccakSponge(rate: rate, suffix: 0x06)174 let fed = Self.feedLarge(t) { s.absorb($0) }175 board.add(algorithm, "", "LDT (large data)", ok: fed && s.squeeze(digest) == t.hex("md"), id: t["tcId"])176 default:177 board.skip(algorithm, "", "unknown test type \(g.str("testType"))")178 }179 }180 }181 board.finish(minimum: digest == 32 ? 1294 : 782)182 }183184 @Test(arguments: [("acvp-shake-128.json.gz", 128), ("acvp-shake-256.json.gz", 256)])185 func shake(_ file: String, _ bits: Int) throws {186 let algorithm = "SHAKE\(bits)"187 let rate = 200 - bits / 4188 var board = Board(source: "NIST ACVP (FIPS 202)")189 for g in try AuditVectors.acvpGroups(AuditPaths.engineVectors("QyvoraKeccak").appendingPathComponent(file)) {190 for t in g.acvpTests {191 switch g.str("testType") {192 case "AFT":193 let msg = t.hex("msg") ?? [], len = t.integer("len") ?? 0, want = t.hex("md") ?? []194 var ok = spongeBits(rate: rate, suffix: 0x1f, message: msg, bitLength: len, output: want.count) == want195 if len % 8 == 0 {196 let m = Bytes(msg.prefix(len / 8))197 ok = ok && (bits == 128 ? SHAKE.shake128(m, outputLength: want.count) : SHAKE.shake256(m, outputLength: want.count)) == want198 }199 board.add(algorithm, "", len % 8 == 0 ? "AFT (byte-aligned)" : "AFT (bit-oriented)", ok: ok, id: t["tcId"])200 case "VOT":201 let msg = t.hex("msg") ?? [], want = t.hex("md") ?? [], outBits = t.integer("outLen") ?? 0202 var x = SHAKE(bits)203 x.absorb(msg)204 var got = x.squeeze((outBits + 7) / 8)205 if outBits % 8 != 0, !got.isEmpty { got[got.count - 1] &= UInt8((1 << (outBits % 8)) - 1) }206 board.add(algorithm, "", "VOT (variable output)", ok: got == want, id: t["tcId"])207 case "MCT":208 let minBytes = (g.integer("minOutLen") ?? 0) / 8, maxBytes = (g.integer("maxOutLen") ?? 0) / 8209 let range = maxBytes - minBytes + 1210 var out = t.hex("msg") ?? []211 var outLen = maxBytes212 for r in t["resultsArray"] as? [[String: Any]] ?? [] {213 for _ in 0..<1000 {214 var msg = Bytes(out.prefix(16))215 if msg.count < 16 { msg += Bytes(repeating: 0, count: 16 - msg.count) }216 var x = SHAKE(bits)217 x.absorb(msg)218 out = x.squeeze(outLen)219 let rightmost = Int(out[out.count - 2]) << 8 | Int(out[out.count - 1])220 outLen = minBytes + rightmost % range221 }222 board.add(algorithm, "", "MCT checkpoint (1000 iterations)", ok: out == r.hex("md"), id: t["tcId"])223 }224 default:225 board.skip(algorithm, "", "unknown test type \(g.str("testType"))")226 }227 }228 }229 board.finish(minimum: 1700)230 }231}232233@Suite struct CAVPGCM {234 static func tests(_ file: String) throws -> [[String: Any]] {235 let url = AuditPaths.engineVectors("QyvoraSymmetric").appendingPathComponent(file)236 guard let root = try AuditVectors.json(url) as? [String: Any], let tests = root["tests"] as? [[String: Any]] else {237 throw AuditVectors.LoadError("unexpected layout in \(file)")238 }239 return tests240 }241242 /// NIST CAVP gcmEncryptExtIV256 / gcmDecrypt256 (96-bit IV, 128-bit tag subset selected by the engine's converter).243 @Test func aes256() throws {244 var board = Board(source: "NIST CAVP (SP 800-38D)")245 for t in try Self.tests("cavp-gcm256-encrypt.json.gz") {246 guard let key = t.hex("key"), let iv = t.hex("iv"), let pt = t.hex("pt"), let aad = t.hex("aad") else { continue }247 // 96-bit IVs through the public interface, the 8-bit and 1024-bit IVs of the file through the internal one.248 let bits = iv.count * 8249 let sealed = bits == 96250 ? try? AES256GCM.seal(key: key, nonce: iv, plaintext: pt, associatedData: aad)251 : try? AESGCM(key: key).sealAnyNonce(nonce: iv, plaintext: pt, associatedData: aad)252 board.add("AES-256-GCM", "IV \(bits) bits", "encrypt (gcmEncryptExtIV256)", ok: sealed != nil && sealed?.ciphertext == t.hex("ct") && sealed?.tag == t.hex("tag"), id: t["count"])253 }254 for t in try Self.tests("cavp-gcm256-decrypt.json.gz") {255 guard let key = t.hex("key"), let iv = t.hex("iv"), let ct = t.hex("ct"), let aad = t.hex("aad"), let tag = t.hex("tag") else { continue }256 let bits = iv.count * 8257 let opened = bits == 96258 ? try? AES256GCM.open(key: key, nonce: iv, ciphertext: ct, tag: tag, associatedData: aad)259 : try? AESGCM(key: key).openAnyNonce(nonce: iv, ciphertext: ct, tag: tag, associatedData: aad)260 let ok = t.flag("pass") ? (opened != nil && opened == t.hex("pt")) : opened == nil261 board.add("AES-256-GCM", "IV \(bits) bits", t.flag("pass") ? "decrypt, valid tag (gcmDecrypt256)" : "decrypt, forged tag refused (gcmDecrypt256)", ok: ok, id: t["count"])262 }263 board.finish(minimum: 2250)264 }265266 /// The 18 test cases of the GCM specification (McGrew & Viega), AES-128/192/256, including 64-bit and 480-bit IVs.267 @Test func specification() throws {268 var board = Board(source: "GCM specification test cases")269 for t in try Self.tests("gcm-spec-vectors.json.gz") {270 guard let key = t.hex("K"), let iv = t.hex("IV"), let p = t.hex("P"), let a = t.hex("A"), let gcm = try? AESGCM(key: key) else { continue }271 let sealed = try? gcm.sealAnyNonce(nonce: iv, plaintext: p, associatedData: a)272 board.add("AES-GCM", "AES-\(key.count * 8)", "specification test cases", ok: sealed?.ciphertext == t.hex("C") && sealed?.tag == t.hex("T"), id: t["tc"])273 }274 board.finish(minimum: 18)275 }276}277278@Suite struct BIPVectors {279 static func json(_ name: String) throws -> Any {280 try AuditVectors.json(AuditPaths.vectors.appendingPathComponent("bip/\(name)"))281 }282283 @Test func bip340() throws {284 let text = try String(contentsOf: AuditPaths.vectors.appendingPathComponent("bip/bip-0340-test-vectors.csv"), encoding: .utf8)285 var board = Board(source: "BIP-340 test-vectors.csv")286 for line in text.split(whereSeparator: \.isNewline).dropFirst() {287 let f = line.split(separator: ",", omittingEmptySubsequences: false).map(String.init)288 guard f.count >= 7, let pk = Hex.decode(f[2]), let msg = Hex.decode(f[4]), let sig = Hex.decode(f[5]) else { continue }289 let expected = f[6] == "TRUE"290 board.add("Schnorr BIP-340", "", "verify", ok: Secp256k1.schnorrVerify(signature: sig, message: msg, publicKey: pk) == expected, id: f[0])291 if !f[1].isEmpty, let sk = Hex.decode(f[1]), let aux = Hex.decode(f[3]) {292 let produced = try? Secp256k1.schnorrSign(message: msg, privateKey: sk, auxRand: aux)293 let xOnly = try? Secp256k1.xOnlyPublicKey(privateKey: sk)294 board.add("Schnorr BIP-340", "", "sign (public key and signature)", ok: produced == sig && xOnly == pk, id: f[0])295 }296 }297 board.finish(minimum: 19)298 }299300 @Test func bip32() throws {301 let root = try #require(try Self.json("bip-0032-vectors.json") as? [String: Any])302 var board = Board(source: "BIP-32 test vectors 1–5")303 for v in root["vectors"] as? [[String: Any]] ?? [] {304 let seed = v.hex("seed") ?? []305 let master = try? ExtendedKey.master(seed: seed)306 for c in v["chains"] as? [[String: Any]] ?? [] {307 var ok = false308 if let master, let path = DerivationPath(c.str("path")), let key = try? master.derive(path) {309 ok = (try? key.serialized(.xprv)) == c.str("xprv") && (try? key.neutered.serialized(.xpub)) == c.str("xpub")310 // the published strings parse back to the same key material311 if let parsed = try? ExtendedKey.parse(c.str("xprv")) {312 ok = ok && parsed.key.privateKey == key.privateKey && parsed.key.chainCode == key.chainCode313 } else {314 ok = false315 }316 }317 board.add("BIP-32", "", "derivation chain (xprv and xpub)", ok: ok, id: "vector \(v["vector"] ?? "?") \(c.str("path"))")318 }319 }320 for inv in root["invalid"] as? [[String: Any]] ?? [] {321 board.add("BIP-32", "", "invalid extended key refused (vector 5)", ok: (try? ExtendedKey.parse(inv.str("key"))) == nil, id: inv.str("reason"))322 }323 board.finish(minimum: 33)324 }325326 @Test func bip39() throws {327 let root = try #require(try Self.json("bip-0039-vectors.json") as? [String: Any])328 var board = Board(source: "BIP-39 reference vectors (trezor/python-mnemonic, English)")329 for v in root["english"] as? [[String]] ?? [] where v.count >= 4 {330 let entropy = Hex.decode(v[0]) ?? []331 let words = try? BIP39.mnemonic(entropy: entropy)332 var ok = words?.joined(separator: " ") == v[1]333 if let words {334 ok = ok && (try? BIP39.entropy(mnemonic: words)) == entropy335 let seed = try? BIP39.seed(mnemonic: words, passphrase: "TREZOR")336 ok = ok && seed.map { Hex.encode($0) } == v[2]337 if let seed, let master = try? ExtendedKey.master(seed: seed) { ok = ok && (try? master.serialized(.xprv)) == v[3] } else { ok = false }338 }339 board.add("BIP-39", "", "entropy → mnemonic → seed → master key", ok: ok, id: v[0].prefix(16))340 }341 board.finish(minimum: 24)342 }343344 @Test func bip173And350() throws {345 let root = try #require(try Self.json("bip-0173-0350-vectors.json") as? [String: Any])346 var board = Board(source: "BIP-173 / BIP-350 reference vectors (sipa/bech32)")347 for s in root["VALID_BECH32"] as? [String] ?? [] {348 board.add("Bech32", "", "valid Bech32 string", ok: Bech32.decode(s, variant: .bech32) != nil && Bech32.decode(s, variant: .bech32m) == nil, id: s.prefix(20))349 }350 for s in root["VALID_BECH32M"] as? [String] ?? [] {351 board.add("Bech32m", "", "valid Bech32m string", ok: Bech32.decode(s, variant: .bech32m) != nil && Bech32.decode(s, variant: .bech32) == nil, id: s.prefix(20))352 }353 for pair in root["VALID_ADDRESS"] as? [[String]] ?? [] where pair.count == 2 {354 let address = pair[0], script = Hex.decode(pair[1]) ?? []355 var ok = false356 for hrp in ["bc", "tb"] {357 if let d = SegWitAddress.decode(address, hrp: hrp) {358 let op: UInt8 = d.version == 0 ? 0 : 0x50 + d.version359 ok = [op, UInt8(d.program.count)] + d.program == script360 && SegWitAddress.encode(hrp: hrp, version: d.version, program: d.program) == address.lowercased()361 }362 }363 board.add("SegWit address", "", "valid address (decode, script, re-encode)", ok: ok, id: address.prefix(24))364 }365 for address in root["INVALID_ADDRESS"] as? [String] ?? [] {366 let refused = SegWitAddress.decode(address, hrp: "bc") == nil && SegWitAddress.decode(address, hrp: "tb") == nil367 board.add("SegWit address", "", "invalid address refused", ok: refused, id: address.prefix(24))368 }369 for e in root["INVALID_ADDRESS_ENC"] as? [[Any]] ?? [] where e.count == 3 {370 guard let hrp = e[0] as? String, let version = e[1] as? Int, let length = e[2] as? Int else { continue }371 let encoded = (0...255).contains(version) ? SegWitAddress.encode(hrp: hrp, version: UInt8(version), program: Bytes(repeating: 0, count: length)) : nil372 // The reference refuses an upper-case HRP; the engine's encoder normalises the HRP to lower case and373 // emits a valid all-lower-case address (allowed by BIP-173: encoders must output lower case). Counted apart.374 if hrp != hrp.lowercased(), let encoded {375 let normalised = encoded == encoded.lowercased() && SegWitAddress.decode(encoded, hrp: hrp.lowercased()) != nil376 board.add("SegWit address", "", "upper-case HRP normalised by the encoder (documented deviation from the reference)", ok: normalised, id: "\(hrp) v\(version) len \(length)")377 continue378 }379 board.add("SegWit address", "", "invalid encoding request refused", ok: encoded == nil, id: "\(hrp) v\(version) len \(length)")380 }381 board.finish(minimum: 40)382 }383}384