Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Tests/PropertyAuditTests/LatticeProperties.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 QyvoraKeccak44import QyvoraMath45import Testing4647@testable import QyvoraMLDSA48@testable import QyvoraMLKEM49@testable import QyvoraSLHDSA5051// Arithmetic invariants of the two lattice schemes (reduction ranges, NTT, negacyclic product, rounding)52// and behavioural invariants of the three post-quantum schemes (implicit rejection, strong unforgeability53// checks by mutation, cross-key rejection).5455/// Schoolbook product in Z_q[X]/(X^256 + 1).56func negacyclicProduct(_ a: [Int64], _ b: [Int64], q: Int64) -> [Int64] {57 var out = [Int64](repeating: 0, count: 256)58 for i in 0..<256 where a[i] != 0 {59 for j in 0..<256 {60 let k = i + j61 let term = a[i] * b[j] % q62 if k < 256 { out[k] = (out[k] + term) % q } else { out[k - 256] = (out[k - 256] - term + q) % q }63 }64 }65 return out66}6768@Suite struct MLKEMArithmetic {69 typealias Field = MLKEM.Field70 static let q: Int32 = 33297172 static func mod(_ a: Int64, _ q: Int64) -> Int64 { ((a % q) + q) % q }7374 /// Montgomery reduction over its whole documented domain |a| < q·2^15 (218 million inputs).75 @Test func montgomeryReductionExhaustive() {76 var prop = Prop("Montgomery reduction: range (−q, q) and congruence, exhaustive over |a| < q·2^15", algorithm: "ML-KEM arithmetic")77 let bound = Int32(3329) << 1578 var bad = 079 var a = -bound + 180 while a < bound {81 let r = Int32(Field.montgomeryReduce(a))82 // r·2^16 ≡ a (mod q) and −q < r < q83 if r <= -3329 || r >= 3329 || (Int64(r) * 65536 - Int64(a)) % 3329 != 0 { bad += 1 }84 a += 185 }86 prop.cases = Int(bound) * 2 - 187 prop.failed = bad88 prop.finish()89 }9091 @Test func barrettAndCanonicalExhaustive() {92 var prop = Prop("Barrett reduction and canonical form, exhaustive over Int16", algorithm: "ML-KEM arithmetic")93 for v in Int16.min...Int16.max {94 let r = Int32(Field.barrettReduce(v)), c = Int32(Field.canonical(v))95 prop.check(r >= -1664 && r <= 1664 && (r - Int32(v)) % 3329 == 0, "barrett(\(v)) = \(r)")96 prop.check(c >= 0 && c < 3329 && (c - Int32(v)) % 3329 == 0, "canonical(\(v)) = \(c)")97 }98 prop.finish()99 }100101 /// The division-free Compress_d equals the definition (integer division) for every x in [0, q) and every d used.102 @Test func compressDecompressExhaustive() {103 var prop = Prop("Compress/Decompress equal their definitions, exhaustive over [0, q) × d ∈ {1,4,5,10,11}", algorithm: "ML-KEM arithmetic")104 for d in [1, 4, 5, 10, 11] {105 let two = UInt32(1) << UInt32(d)106 for x in UInt32(0)..<3329 {107 let expected = ((x << UInt32(d)) + 1664) / 3329 % two108 let c = Field.compress(x, bits: d)109 prop.check(c == expected, "compress(\(x), \(d))")110 // |Decompress(Compress(x)) − x| mod± q ≤ round(q / 2^(d+1))111 let back = Int32(Field.decompress(c, bits: d))112 var diff = abs(back - Int32(x))113 diff = min(diff, 3329 - diff)114 prop.check(diff <= Int32((3329 + (1 << (d + 1)) / 2) >> (d + 1)) && back >= 0 && back <= 3329, "decompress bound x=\(x) d=\(d)")115 }116 for y in UInt32(0)..<two {117 prop.check(Field.decompress(y, bits: d) == (y * 3329 + two / 2) / two, "decompress(\(y), \(d))")118 if d < 12 { prop.check(Field.compress(Field.decompress(y, bits: d) % 3329, bits: d) == y, "Compress∘Decompress = id") }119 }120 }121 prop.finish()122 }123124 @Test func nttInvariants() {125 let seed = AuditSeed.make("mlkem.ntt")126 var rng = AuditRNG(seed: seed)127 var prop = Prop("NTT⁻¹∘NTT = id, linearity, MultiplyNTTs = negacyclic product", algorithm: "ML-KEM arithmetic", seed: seed)128 func poly(_ kind: Int) -> [UInt16] {129 switch kind {130 case 0: return [UInt16](repeating: 0, count: 256)131 case 1: return [UInt16](repeating: 3328, count: 256)132 case 2: return (0..<256).map { $0 == 0 ? 1 : 0 }133 case 3: return (0..<256).map { $0 == 255 ? 3328 : 0 }134 default: return (0..<256).map { _ in UInt16(rng.int(0...3328)) }135 }136 }137 for i in 0..<AuditMode.cases(quick: 200, full: 2000) {138 let f = poly(i), g = poly(i / 5 + 4)139 let nf = MLKEM.NTT.ntt(f), ng = MLKEM.NTT.ntt(g)140 prop.check(nf.allSatisfy { $0 < 3329 }, "NTT output canonical")141 prop.check(MLKEM.NTT.inverseNTT(nf) == f, "NTT⁻¹(NTT(f)) = f")142 let sum = zip(f, g).map { UInt16((UInt32($0) + UInt32($1)) % 3329) }143 prop.check(MLKEM.NTT.ntt(sum) == zip(nf, ng).map { UInt16((UInt32($0) + UInt32($1)) % 3329) }, "linearity")144 let product = MLKEM.NTT.inverseNTT(MLKEM.NTT.multiplyNTTs(nf, ng))145 let expected = negacyclicProduct(f.map(Int64.init), g.map(Int64.init), q: 3329).map { UInt16($0) }146 prop.check(product == expected, "negacyclic product")147 }148 prop.finish()149 }150}151152@Suite struct MLKEMBehaviour {153 @Test(arguments: MLKEM.ParameterSet.allCases) func implicitRejection(_ ps: MLKEM.ParameterSet) throws {154 let seed = AuditSeed.make("mlkem.rejection." + ps.name)155 var rng = AuditRNG(seed: seed)156 var prop = Prop("decapsulation of mutated ciphertexts: no error, never the real secret, equals J(z‖c′)", algorithm: "ML-KEM", parameterSet: ps.name, seed: seed)157 for _ in 0..<AuditMode.cases(quick: 60, full: 600) {158 let pair = try MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))159 prop.check(MLKEM.isValidEncapsulationKey(ps, pair.encapsulationKey) && MLKEM.isValidDecapsulationKey(ps, pair.decapsulationKey), "generated keys pass the FIPS 203 input checks")160 let enc = try MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32))161 prop.check(try MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: enc.ciphertext) == enc.sharedSecret, "correctness")162 let z = Bytes(pair.decapsulationKey.suffix(32))163 for _ in 0..<8 {164 var c = enc.ciphertext165 switch rng.int(0...3) {166 case 0: c[rng.int(0...(c.count - 1))] ^= UInt8(1 << rng.int(0...7))167 case 1: c[rng.int(0...(c.count - 1))] = UInt8(truncatingIfNeeded: rng.next())168 case 2: c = rng.bytes(c.count)169 default: for i in 0..<c.count where rng.int(0...63) == 0 { c[i] ^= 0xff }170 }171 guard c != enc.ciphertext else { continue }172 let out = try? MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: c)173 prop.check(out != nil, "decapsulation threw on a well-sized ciphertext")174 prop.check(out != enc.sharedSecret, "mutated ciphertext returned the real secret")175 prop.check(out == SHAKE.shake256(z + c, outputLength: 32), "implicit rejection value J(z‖c′)")176 }177 // wrong sizes are errors, not traps178 prop.check((try? MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: Bytes(enc.ciphertext.dropLast()))) == nil, "short ciphertext")179 prop.check((try? MLKEM.decapsulate(ps, decapsulationKey: Bytes(pair.decapsulationKey.dropLast()), ciphertext: enc.ciphertext)) == nil, "short key")180 // a decapsulation key whose embedded hash does not match is refused (FIPS 203 §7.3)181 var dk = pair.decapsulationKey182 dk[dk.count - 40] ^= 1183 prop.check((try? MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: enc.ciphertext)) == nil, "decapsulation key with a wrong H(ek)")184 // an encapsulation key with a coefficient ≥ q is refused (FIPS 203 §7.2)185 var ek = pair.encapsulationKey186 ek[0] = 0xff187 ek[1] |= 0x0f188 prop.check(!MLKEM.isValidEncapsulationKey(ps, ek) && (try? MLKEM.encapsulate(ps, encapsulationKey: ek)) == nil, "non-reduced encapsulation key")189 }190 prop.finish()191 }192}193194@Suite struct MLDSAArithmetic {195 typealias Field = MLDSA.Field196 typealias Rounding = MLDSA.Rounding197 static let q: Int64 = 8_380_417198199 @Test func reductions() {200 let seed = AuditSeed.make("mldsa.reduce")201 var rng = AuditRNG(seed: seed)202 var prop = Prop("Montgomery reduction and reduce32: ranges and congruence on boundary and random inputs", algorithm: "ML-DSA arithmetic", seed: seed)203 let bound = Int64(1) << 31 * Self.q204 // Domain checked: −2^31·q ≤ a < 2^31·q. At the single point a = +2^31·q the function returns exactly q205 // (congruent, but outside the open interval its comment states): asserted below and recorded as an206 // informational finding (QYV-AUD-001); no caller can produce that product from reduced operands.207 var inputs: [Int64] = [0, 1, -1, -bound, bound - 1, -bound + 1, Self.q, -Self.q, Self.q - 1, 1 << 32, -(1 << 32), (1 << 32) - 1]208 for _ in 0..<AuditMode.cases(quick: 2_000_000, full: 50_000_000) { inputs.append(Int64.random(in: -bound..<bound, using: &rng)) }209 var bad = 0210 for a in inputs {211 let r = Int64(Field.montgomeryReduce(a))212 // r·2^32 ≡ a (mod q), −q < r < q213 if r <= -Self.q || r >= Self.q || (((r << 32) - a) % Self.q) != 0 { bad += 1 }214 }215 #expect(Int64(Field.montgomeryReduce(bound)) == Self.q, "boundary behaviour at a = 2^31·q changed: update QYV-AUD-001")216 prop.cases += inputs.count217 prop.failed += bad218 // reduce32 on its documented domain |a| ≤ 2^31 − 2^22 − 1, canonical in [0, q)219 let limit = Int32.max - (1 << 22)220 var bad32 = 0221 var values: [Int32] = [0, 1, -1, limit, -limit, limit - 1, 8_380_417, -8_380_417, 8_380_416, 4_190_208, 4_190_209, -4_190_208, -4_190_209]222 for _ in 0..<AuditMode.cases(quick: 2_000_000, full: 50_000_000) { values.append(Int32.random(in: -limit...limit, using: &rng)) }223 for a in values {224 let r = Field.reduce32(a), c = Field.canonical(a)225 if r < -6_283_008 || r > 6_283_008 || (Int64(r) - Int64(a)) % Self.q != 0 { bad32 += 1 }226 if c < 0 || c >= 8_380_417 || (Int64(c) - Int64(a)) % Self.q != 0 { bad32 += 1 }227 }228 prop.cases += values.count229 prop.failed += bad32230 prop.finish()231 }232233 /// Power2Round, Decompose, MakeHint/UseHint over EVERY r in [0, q) (8.4 million values per γ2).234 @Test func roundingExhaustive() {235 var prop = Prop("Power2Round, Decompose and UseHint∘MakeHint, exhaustive over r ∈ [0, q)", algorithm: "ML-DSA arithmetic")236 var bad = 0, count = 0237 for r in Int32(0)..<8_380_417 {238 let (r1, r0) = Rounding.power2Round(r)239 if r1 << 13 + r0 != r || r0 <= -(1 << 12) || r0 > (1 << 12) { bad += 1 }240 count += 1241 }242 for gamma2: Int32 in [95_232, 261_888] {243 let m = (8_380_417 - 1) / (2 * gamma2)244 for r in Int32(0)..<8_380_417 {245 let (r1, r0) = Rounding.decompose(r, gamma2: gamma2)246 // definition (Algorithm 36) with plain integer arithmetic247 var e0 = r % (2 * gamma2)248 if e0 > gamma2 { e0 -= 2 * gamma2 }249 var e1: Int32250 if r - e0 == 8_380_416 {251 e1 = 0252 e0 -= 1253 } else {254 e1 = (r - e0) / (2 * gamma2)255 }256 if r1 != e1 || r0 != e0 || r1 < 0 || r1 >= m { bad += 1 }257 count += 1258 }259 }260 prop.cases = count261 prop.failed = bad262 prop.finish()263 }264265 @Test func hints() {266 let seed = AuditSeed.make("mldsa.hints")267 var rng = AuditRNG(seed: seed)268 var prop = Prop("UseHint(MakeHint(z, r), r) = HighBits(r + z) for |z| ≤ γ2 (FIPS 204 Lemma)", algorithm: "ML-DSA arithmetic", seed: seed)269 for gamma2: Int32 in [95_232, 261_888] {270 for i in 0..<AuditMode.cases(quick: 300_000, full: 5_000_000) {271 let r = i < 8 ? [0, 1, 8_380_416, gamma2, gamma2 + 1, 2 * gamma2, 8_380_416 - gamma2, 4_190_208][i] : Int32(rng.int(0...8_380_416))272 let zc = i % 3 == 0 ? rng.pick([gamma2, -gamma2, 0, 1, -1]) : Int32(rng.int(Int(-gamma2)...Int(gamma2)))273 let z = zc < 0 ? zc + 8_380_417 : zc // z in [0, q)274 let sum = (r + z) % 8_380_417275 let hint = Rounding.makeHint(z, r, gamma2: gamma2)276 prop.check(Rounding.useHint(hint, r, gamma2: gamma2) == Rounding.highBits(sum, gamma2: gamma2), "r=\(r) z=\(zc) γ2=\(gamma2)")277 }278 }279 prop.finish()280 }281282 @Test func nttInvariants() {283 let seed = AuditSeed.make("mldsa.ntt")284 var rng = AuditRNG(seed: seed)285 var prop = Prop("NTT⁻¹∘NTT = id, linearity, MultiplyNTT = negacyclic product", algorithm: "ML-DSA arithmetic", seed: seed)286 func poly(_ kind: Int) -> [Int32] {287 switch kind {288 case 0: return [Int32](repeating: 0, count: 256)289 case 1: return [Int32](repeating: 8_380_416, count: 256)290 case 2: return (0..<256).map { $0 == 0 ? 1 : 0 }291 case 3: return (0..<256).map { $0 == 255 ? 8_380_416 : 0 }292 default: return (0..<256).map { _ in Int32(rng.int(0...8_380_416)) }293 }294 }295 for i in 0..<AuditMode.cases(quick: 200, full: 2000) {296 let f = poly(i), g = poly(i / 5 + 4)297 let nf = MLDSA.NTT.ntt(f), ng = MLDSA.NTT.ntt(g)298 prop.check(nf.allSatisfy { $0 >= 0 && $0 < 8_380_417 }, "NTT output canonical")299 prop.check(MLDSA.NTT.inverseNTT(nf) == f, "NTT⁻¹(NTT(f)) = f")300 let sum = zip(f, g).map { Int32((Int64($0) + Int64($1)) % Self.q) }301 prop.check(MLDSA.NTT.ntt(sum) == zip(nf, ng).map { Int32((Int64($0) + Int64($1)) % Self.q) }, "linearity")302 let product = MLDSA.NTT.inverseNTT(MLDSA.NTT.multiplyNTT(nf, ng))303 prop.check(product == negacyclicProduct(f.map(Int64.init), g.map(Int64.init), q: Self.q).map { Int32($0) }, "negacyclic product")304 }305 prop.finish()306 }307}308309@Suite struct PostQuantumSignatureBehaviour {310 @Test(arguments: MLDSA.ParameterSet.allCases) func mldsa(_ ps: MLDSA.ParameterSet) throws {311 let seed = AuditSeed.make("mldsa.behaviour." + ps.name)312 var rng = AuditRNG(seed: seed)313 var prop = Prop("sign/verify, mutation of signature, message, context and key, cross-key rejection", algorithm: "ML-DSA", parameterSet: ps.name, seed: seed)314 for _ in 0..<AuditMode.cases(quick: 12, full: 150) {315 let pair = try MLDSA.keyGenInternal(ps, seed: rng.bytes(32)), other = try MLDSA.keyGenInternal(ps, seed: rng.bytes(32))316 let message = rng.bytes(rng.int(0...200)), context = rng.bytes(rng.int(0...40))317 let sig = try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: context, randomness: .explicit(rng.bytes(32)))318 prop.check(sig.count == ps.signatureSize && MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: context), "own signature verifies")319 prop.check(!MLDSA.verify(ps, publicKey: other.publicKey, message: message, signature: sig, context: context), "cross-key")320 prop.check(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message + [0], signature: sig, context: context), "extended message")321 prop.check(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: context + [1]), "other context")322 prop.check(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: Bytes(sig.dropLast()), context: context), "truncated signature")323 prop.check(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig + [0], context: context), "extended signature")324 prop.check(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: Bytes(repeating: 0, count: 256)), "context of 256 bytes")325 prop.check((try? MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: Bytes(repeating: 0, count: 256))) == nil, "signing with a 256-byte context")326 // ML-DSA is strongly unforgeable: any single-bit change of the signature must be rejected327 for _ in 0..<40 {328 var s = sig329 s[rng.int(0...(s.count - 1))] ^= UInt8(1 << rng.int(0...7))330 prop.check(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s, context: context), "bit flip in the signature accepted")331 }332 for _ in 0..<10 {333 var pk = pair.publicKey334 pk[rng.int(0...(pk.count - 1))] ^= UInt8(1 << rng.int(0...7))335 prop.check(!MLDSA.verify(ps, publicKey: pk, message: message, signature: sig, context: context), "bit flip in the public key accepted")336 }337 }338 prop.finish()339 }340341 /// The "f" parameter sets in quick mode (a signature takes tens of milliseconds); all twelve in full mode.342 @Test(arguments: SLHDSA.ParameterSet.allCases) func slhdsa(_ set: SLHDSA.ParameterSet) throws {343 guard AuditMode.isFull || set.name.hasSuffix("f") else {344 AuditRecorder.notRun(area: "property", name: "SLH-DSA \(set.name) mutation and cross-key rejection", reason: "small ('s') sets sign slowly: full mode only")345 return346 }347 let seed = AuditSeed.make("slhdsa.behaviour." + set.name)348 var rng = AuditRNG(seed: seed)349 var prop = Prop("sign/verify, mutation of signature, message, context and key, cross-key rejection", algorithm: "SLH-DSA", parameterSet: set.name, seed: seed)350 let n = set.name.contains("128") ? 16 : set.name.contains("192") ? 24 : 32351 for _ in 0..<AuditMode.cases(quick: 2, full: 6) {352 let pair = try SLHDSA.keyGenInternal(set, skSeed: rng.bytes(n), skPrf: rng.bytes(n), pkSeed: rng.bytes(n))353 let other = try SLHDSA.keyGenInternal(set, skSeed: rng.bytes(n), skPrf: rng.bytes(n), pkSeed: rng.bytes(n))354 let message = rng.bytes(rng.int(0...100)), context = rng.bytes(rng.int(0...20))355 let sig = try SLHDSA.sign(set, message: message, context: context, secretKey: pair.secretKey, randomization: .explicit(rng.bytes(n)))356 prop.check(SLHDSA.verify(set, message: message, signature: sig, context: context, publicKey: pair.publicKey), "own signature verifies")357 prop.check(try SLHDSA.publicKey(set, fromSecretKey: pair.secretKey) == pair.publicKey, "public key from secret key")358 prop.check(!SLHDSA.verify(set, message: message, signature: sig, context: context, publicKey: other.publicKey), "cross-key")359 prop.check(!SLHDSA.verify(set, message: message + [0], signature: sig, context: context, publicKey: pair.publicKey), "extended message")360 prop.check(!SLHDSA.verify(set, message: message, signature: sig, context: context + [1], publicKey: pair.publicKey), "other context")361 prop.check(!SLHDSA.verify(set, message: message, signature: Bytes(sig.dropLast()), context: context, publicKey: pair.publicKey), "truncated signature")362 prop.check(!SLHDSA.verify(set, message: message, signature: sig + [0], context: context, publicKey: pair.publicKey), "extended signature")363 prop.check(!SLHDSA.verify(set, message: message, signature: sig, context: Bytes(repeating: 0, count: 256), publicKey: pair.publicKey), "context of 256 bytes")364 // Every byte of an SLH-DSA signature is bound by the hash chain up to the root: a bit flip must be rejected.365 for _ in 0..<60 {366 var s = sig367 s[rng.int(0...(s.count - 1))] ^= UInt8(1 << rng.int(0...7))368 prop.check(!SLHDSA.verify(set, message: message, signature: s, context: context, publicKey: pair.publicKey), "bit flip in the signature accepted")369 }370 for _ in 0..<8 {371 var pk = pair.publicKey372 pk[rng.int(0...(pk.count - 1))] ^= UInt8(1 << rng.int(0...7))373 prop.check(!SLHDSA.verify(set, message: message, signature: sig, context: context, publicKey: pk), "bit flip in the public key accepted")374 }375 }376 prop.finish()377 }378}379