Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraMLDSATests/MLDSAPropertyTests.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 QyvoraKeccak43import QyvoraMath44import Testing4546@testable import QyvoraMLDSA4748@Suite struct MLDSAPropertyTests {49 static let q: Int64 = 8_380_4175051 static func randomPoly() -> [Int32] {52 let b = SystemRandom.bytes(1024)53 return (0..<256).map { i in54 let v = UInt32(b[4 * i]) | UInt32(b[4 * i + 1]) << 8 | UInt32(b[4 * i + 2]) << 16 | UInt32(b[4 * i + 3]) << 2455 return Int32(v % 8_380_417)56 }57 }5859 static func mod(_ a: Int64) -> Int64 { ((a % q) + q) % q }6061 // MARK: Parameters and constants6263 @Test func sizes() {64 let expected: [(MLDSA.ParameterSet, Int, Int, Int)] = [65 (.mldsa44, 1312, 2560, 2420), (.mldsa65, 1952, 4032, 3309), (.mldsa87, 2592, 4896, 4627),66 ]67 for (ps, pk, sk, sig) in expected {68 #expect(ps.publicKeySize == pk)69 #expect(ps.privateKeySize == sk)70 #expect(ps.signatureSize == sig)71 let pair = MLDSA.generateKeyPair(ps)72 #expect(pair.publicKey.count == pk)73 #expect(pair.privateKey.count == sk)74 }75 }7677 @Test func fieldConstants() {78 #expect(UInt32(truncatingIfNeeded: Int64(MLDSA.Field.qInverse) * Self.q) == 1)79 let r = Self.mod(1 << 32)80 #expect(Self.mod(Int64(MLDSA.NTT.montgomerySquared)) == r * r % Self.q)81 // inverseScale * 256 = 2^64 (mod q)82 #expect(Self.mod(Int64(MLDSA.NTT.inverseScale) * 256) == r * r % Self.q)83 // zeta = 1753 is a primitive 512th root of unity; zetas[1] = zeta^128 in Montgomery form84 var z: Int64 = 185 for _ in 0..<256 { z = z * 1753 % Self.q }86 #expect(z == Self.q - 1)87 #expect(MLDSA.NTT.zetas[1] == 25847)88 #expect(MLDSA.NTT.zetas[255] == 1_976_782)89 #expect(MLDSA.NTT.zetas.allSatisfy { abs(Int64($0)) < Self.q / 2 + 1 })90 }9192 @Test func reductions() {93 var a: Int64 = -(1 << 31) * Self.q94 let step: Int64 = 70_368_744_177_679 // prime, about 2^4695 while a <= (1 << 31) * Self.q {96 let r = Int64(MLDSA.Field.montgomeryReduce(a))97 #expect(r > -Self.q && r < Self.q)98 #expect(Self.mod(r * Self.mod(1 << 32)) == Self.mod(a))99 a += step100 }101 var b = Int64(Int32.min)102 while b <= Int64(Int32.max) - (1 << 22) - 1 {103 let v = Int32(b)104 let r = MLDSA.Field.reduce32(v)105 #expect(r >= -6_283_008 && r <= 6_283_008 && Self.mod(Int64(r)) == Self.mod(b))106 if b > -(1 << 31) + (1 << 23) {107 let c = MLDSA.Field.canonical(v)108 #expect(c >= 0 && Int64(c) < Self.q && Int64(c) == Self.mod(b))109 }110 b += 104_729111 }112 }113114 @Test func nttRoundTripAndProduct() {115 for _ in 0..<10 {116 let f = Self.randomPoly(), g = Self.randomPoly()117 #expect(MLDSA.NTT.inverseNTT(MLDSA.NTT.ntt(f)) == f)118 var h = [Int64](repeating: 0, count: 256)119 for i in 0..<256 {120 for j in 0..<256 {121 let p = Int64(f[i]) * Int64(g[j]) % Self.q122 if i + j < 256 { h[i + j] = (h[i + j] + p) % Self.q } else { h[i + j - 256] = (h[i + j - 256] + Self.q - p) % Self.q }123 }124 }125 let viaNTT = MLDSA.NTT.inverseNTT(MLDSA.NTT.multiplyNTT(MLDSA.NTT.ntt(f), MLDSA.NTT.ntt(g)))126 #expect(viaNTT.map(Int64.init) == h)127 }128 }129130 // MARK: Rounding131132 /// Decompose as literally specified in Algorithm 36.133 static func referenceDecompose(_ r: Int64, _ gamma2: Int64) -> (Int64, Int64) {134 var r0 = r % (2 * gamma2)135 if r0 > gamma2 { r0 -= 2 * gamma2 }136 if r - r0 == q - 1 { return (0, r0 - 1) }137 return ((r - r0) / (2 * gamma2), r0)138 }139140 @Test func roundingMatchesSpecification() {141 for gamma2 in [Int32((8_380_417 - 1) / 88), Int32((8_380_417 - 1) / 32)] {142 var samples = Array(stride(from: Int32(0), to: 8_380_417, by: 61))143 // every multiple of gamma2 and its neighbours, plus the ends of the range144 var m: Int32 = 0145 while m < 8_380_417 {146 for d: Int32 in -2...2 where m + d >= 0 && m + d < 8_380_417 { samples.append(m + d) }147 m += gamma2148 }149 samples += [8_380_416, 8_380_415]150 var mismatches = 0151 for r in samples {152 let (r1, r0) = MLDSA.Rounding.decompose(r, gamma2: gamma2)153 let (e1, e0) = Self.referenceDecompose(Int64(r), Int64(gamma2))154 if Int64(r1) != e1 || Int64(r0) != e0 { mismatches += 1 }155 }156 #expect(mismatches == 0)157158 // UseHint(MakeHint(z, r), r) = HighBits(r + z) for |z| <= gamma2 (FIPS 204, Lemma 1 of section 7.4)159 let rnd = SystemRandom.bytes(8 * 4000)160 var hintFailures = 0161 for i in 0..<4000 {162 let a = UInt32(rnd[8 * i]) | UInt32(rnd[8 * i + 1]) << 8 | UInt32(rnd[8 * i + 2]) << 16 | UInt32(rnd[8 * i + 3]) << 24163 let b = UInt32(rnd[8 * i + 4]) | UInt32(rnd[8 * i + 5]) << 8 | UInt32(rnd[8 * i + 6]) << 16 | UInt32(rnd[8 * i + 7]) << 24164 let r = Int32(a % 8_380_417)165 let zSigned = Int64(b % UInt32(2 * gamma2 + 1)) - Int64(gamma2)166 let z = Int32(Self.mod(zSigned))167 let hint = MLDSA.Rounding.makeHint(z, r, gamma2: gamma2)168 let sum = Int32(Self.mod(Int64(r) + zSigned))169 if MLDSA.Rounding.useHint(hint, r, gamma2: gamma2) != MLDSA.Rounding.highBits(sum, gamma2: gamma2) { hintFailures += 1 }170 if MLDSA.Rounding.useHint(false, r, gamma2: gamma2) != MLDSA.Rounding.highBits(r, gamma2: gamma2) { hintFailures += 1 }171 }172 #expect(hintFailures == 0)173 }174 var bad = 0175 for r in stride(from: Int32(0), to: 8_380_417, by: 13) {176 let (r1, r0) = MLDSA.Rounding.power2Round(r)177 if r1 * 8192 + r0 != r || r0 <= -4096 || r0 > 4096 || r1 < 0 || r1 > 1023 { bad += 1 }178 }179 #expect(bad == 0)180 }181182 // MARK: Packing183184 @Test func bitPackingRoundTrips() {185 for (bits, base) in [(10, nil), (4, nil), (6, nil), (3, Int32(2)), (4, Int32(4)), (13, Int32(4096)), (18, Int32(1 << 17)), (20, Int32(1 << 19))]186 as [(Int, Int32?)]187 {188 let bytes = SystemRandom.bytes(32 * bits)189 var poly = [Int32](repeating: 0, count: 256)190 bytes.withUnsafeBufferPointer { b in191 poly.withUnsafeMutableBufferPointer { MLDSA.Coding.unpack(b.baseAddress!, count: 256, bits: bits, subtractFrom: base, into: $0.baseAddress!) }192 }193 var out = Bytes()194 poly.withUnsafeBufferPointer { MLDSA.Coding.pack($0.baseAddress!, count: 256, bits: bits, subtractFrom: base, into: &out) }195 #expect(out == bytes)196 if let base {197 #expect(poly.allSatisfy { $0 <= base && $0 > base - (1 << Int32(bits)) })198 }199 }200 }201202 static func decodeHint(_ y: Bytes, k: Int, omega: Int) -> [Int32]? {203 var h = [Int32](repeating: 0, count: 256 * k)204 let ok = y.withUnsafeBufferPointer { yp in205 h.withUnsafeMutableBufferPointer { MLDSA.Coding.unpackHint(yp.baseAddress!, k: k, omega: omega, into: $0.baseAddress!) }206 }207 return ok ? h : nil208 }209210 @Test(arguments: MLDSA.ParameterSet.allCases)211 func hintEncoding(_ ps: MLDSA.ParameterSet) {212 let k = ps.k, omega = ps.omega213 // round trip of random hints of every admissible weight class214 for weight in [0, 1, omega / 2, omega] {215 var h = [Int32](repeating: 0, count: 256 * k)216 var placed = 0217 let rnd = SystemRandom.bytes(4 * omega + 4)218 var i = 0219 while placed < weight {220 let position = (Int(rnd[(i * 2) % rnd.count]) << 8 | Int(rnd[(i * 2 + 1) % rnd.count]) &+ i * 7919) % (256 * k)221 if h[position] == 0 {222 h[position] = 1223 placed += 1224 }225 i += 1226 }227 var y = Bytes()228 h.withUnsafeBufferPointer { MLDSA.Coding.packHint($0.baseAddress!, k: k, omega: omega, into: &y) }229 #expect(y.count == omega + k)230 #expect(Self.decodeHint(y, k: k, omega: omega) == h)231 }232233 // a valid base: positions 3 < 9 < 200 in polynomial 0, 5 in polynomial 1234 var good = Bytes(repeating: 0, count: omega + k)235 good[0] = 3236 good[1] = 9237 good[2] = 200238 good[3] = 5239 good[omega] = 3240 for i in 1..<k { good[omega + i] = 4 }241 #expect(Self.decodeHint(good, k: k, omega: omega) != nil)242243 var bad = good244 bad[1] = 3 // repeated position245 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)246 bad = good247 bad[1] = 2 // decreasing positions248 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)249 bad = good250 bad[2] = 9 // repeated position at the end of a polynomial251 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)252 bad = good253 bad[omega + 1] = 2 // cumulative counter decreases254 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)255 bad = good256 bad[omega + k - 1] = UInt8(omega + 1) // counter above omega257 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)258 bad = good259 bad[omega + k - 1] = 255260 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)261 bad = good262 bad[4] = 1 // non-zero byte after the last used position263 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)264 bad = good265 bad[omega - 1] = 7 // non-zero padding at the very end266 #expect(Self.decodeHint(bad, k: k, omega: omega) == nil)267 // positions restart in a new polynomial: 5 after 200 is fine, and equal values across polynomials too268 var cross = good269 cross[3] = 200270 #expect(Self.decodeHint(cross, k: k, omega: omega) != nil)271 // all omega hints in the last polynomial, strictly increasing272 var full = Bytes(repeating: 0, count: omega + k)273 for i in 0..<omega { full[i] = UInt8(i * 3) }274 full[omega + k - 1] = UInt8(omega)275 #expect(Self.decodeHint(full, k: k, omega: omega)?.reduce(0, +) == Int32(omega))276 }277278 // MARK: Signatures279280 @Test(arguments: MLDSA.ParameterSet.allCases)281 func randomRoundTrips(_ ps: MLDSA.ParameterSet) throws {282 for round in 0..<6 {283 let pair = MLDSA.generateKeyPair(ps)284 let message = SystemRandom.bytes(round * 37)285 let context = SystemRandom.bytes(round == 5 ? 255 : round * 11)286 let hedged = try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: context)287 let hedged2 = try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: context)288 let det = try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: context, randomness: .deterministic)289 let det2 = try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: context, randomness: .deterministic)290 #expect(hedged.count == ps.signatureSize)291 #expect(hedged != hedged2)292 #expect(det == det2)293 #expect(det == (try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: context, randomness: .explicit(Bytes(repeating: 0, count: 32)))))294 for sig in [hedged, hedged2, det] {295 #expect(MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: context))296 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message + [0], signature: sig, context: context))297 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: context + [1]) || context.count == 255)298 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: [0x42] + context.dropFirst(1)) || context.first == 0x42)299 }300 let other = MLDSA.generateKeyPair(ps)301 #expect(!MLDSA.verify(ps, publicKey: other.publicKey, message: message, signature: det, context: context))302 }303 }304305 @Test(arguments: MLDSA.ParameterSet.allCases)306 func keyStructureAndInternalInterfaces(_ ps: MLDSA.ParameterSet) throws {307 let seed = SystemRandom.bytes(32)308 let a = try MLDSA.keyGenInternal(ps, seed: seed)309 #expect(a == (try MLDSA.keyGenInternal(ps, seed: seed)))310 // sk = rho || K || tr || ..., with rho shared with pk and tr = H(pk, 64)311 #expect(Array(a.privateKey[0..<32]) == Array(a.publicKey[0..<32]))312 #expect(Array(a.privateKey[64..<128]) == SHAKE.shake256(a.publicKey, outputLength: 64))313314 let message = SystemRandom.bytes(100), rnd = SystemRandom.bytes(32), ctx = Array("ctx".utf8)315 // the external interface is Sign_internal on M' = 0 || |ctx| || ctx || M316 let formatted = [0, UInt8(ctx.count)] + ctx + message317 let external = try MLDSA.sign(ps, privateKey: a.privateKey, message: message, context: ctx, randomness: .explicit(rnd))318 let viaInternal = try MLDSA.signInternal(ps, privateKey: a.privateKey, message: formatted, rnd: rnd)319 let mu = try #require(MLDSA.computeMu(ps, publicKey: a.publicKey, formattedMessage: formatted))320 let viaMu = try MLDSA.signInternal(ps, privateKey: a.privateKey, mu: mu, rnd: rnd)321 #expect(external == viaInternal)322 #expect(external == viaMu)323 #expect(MLDSA.verifyInternal(ps, publicKey: a.publicKey, message: formatted, signature: external))324 #expect(MLDSA.verifyInternal(ps, publicKey: a.publicKey, mu: mu, signature: external))325 #expect(!MLDSA.verifyInternal(ps, publicKey: a.publicKey, message: message, signature: external))326 }327328 @Test(arguments: MLDSA.ParameterSet.allCases)329 func preHashInterfaces(_ ps: MLDSA.ParameterSet) throws {330 let pair = MLDSA.generateKeyPair(ps)331 let message = SystemRandom.bytes(333), ctx = Array("pre-hash".utf8)332 for hash in MLDSA.KeccakPreHash.allCases {333 let sig = try MLDSA.signPreHash(ps, privateKey: pair.privateKey, message: message, hash: hash, context: ctx)334 #expect(MLDSA.verifyPreHash(ps, publicKey: pair.publicKey, message: message, signature: sig, hash: hash, context: ctx))335 #expect(MLDSA.verifyPreHashed(ps, publicKey: pair.publicKey, digest: hash.digest(message), signature: sig, hash: hash.preHash, context: ctx))336 // domain separation: not a pure signature, not valid under another hash or context337 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: ctx))338 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: hash.digest(message), signature: sig, context: ctx))339 #expect(!MLDSA.verifyPreHash(ps, publicKey: pair.publicKey, message: message, signature: sig, hash: hash, context: []))340 for otherHash in MLDSA.KeccakPreHash.allCases where otherHash != hash {341 #expect(!MLDSA.verifyPreHash(ps, publicKey: pair.publicKey, message: message, signature: sig, hash: otherHash, context: ctx))342 }343 }344 // caller-supplied digests: every approved function, plus a private OID345 for hash in MLDSA.PreHash.allCases {346 let digest = TestHashOracle.digest(hash, message)347 #expect(hash.oid.count == 11)348 let sig = try MLDSA.signPreHashed(ps, privateKey: pair.privateKey, digest: digest, hash: hash, randomness: .deterministic)349 #expect(MLDSA.verifyPreHashed(ps, publicKey: pair.publicKey, digest: digest, signature: sig, hash: hash))350 #expect(MLDSA.verifyPreHashed(ps, publicKey: pair.publicKey, digest: digest, signature: sig, oid: hash.oid))351 #expect(!MLDSA.verifyPreHashed(ps, publicKey: pair.publicKey, digest: digest + [0], signature: sig, hash: hash))352 #expect(throws: MLDSA.Error.invalidDigestLength) {353 try MLDSA.signPreHashed(ps, privateKey: pair.privateKey, digest: digest + [0], hash: hash)354 }355 }356 let privateOID: Bytes = [0x06, 0x03, 0x2a, 0x03, 0x04]357 let digest = SystemRandom.bytes(40)358 let sig = try MLDSA.signPreHashed(ps, privateKey: pair.privateKey, digest: digest, oid: privateOID)359 #expect(MLDSA.verifyPreHashed(ps, publicKey: pair.publicKey, digest: digest, signature: sig, oid: privateOID))360 #expect(!MLDSA.verifyPreHashed(ps, publicKey: pair.publicKey, digest: digest, signature: sig, oid: [0x06, 0x03, 0x2a, 0x03, 0x05]))361 for badOID in [Bytes(), [0x06], [0x06, 0x00], [0x05, 0x01, 0x00], [0x06, 0x02, 0x2a], [0x06, 0x01, 0x2a, 0x00]] as [Bytes] {362 #expect(throws: MLDSA.Error.invalidObjectIdentifier) {363 try MLDSA.signPreHashed(ps, privateKey: pair.privateKey, digest: digest, oid: badOID)364 }365 #expect(!MLDSA.verifyPreHashed(ps, publicKey: pair.publicKey, digest: digest, signature: sig, oid: badOID))366 }367 }368369 /// Every single-bit flip of a signature must be rejected (all bits, all parameter sets).370 @Test(arguments: MLDSA.ParameterSet.allCases)371 func everySignatureBitFlipIsRejected(_ ps: MLDSA.ParameterSet) throws {372 let pair = MLDSA.generateKeyPair(ps)373 let message = Array("bit flip sample".utf8)374 let sig = try MLDSA.sign(ps, privateKey: pair.privateKey, message: message)375 #expect(MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig))376 var accepted = 0, tried = 0377 for bit in 0..<(sig.count * 8) {378 var s = sig379 s[bit / 8] ^= 1 << UInt8(bit % 8)380 if MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s) { accepted += 1 }381 tried += 1382 }383 #expect(accepted == 0)384 #expect(tried == ps.signatureSize * 8)385 // flips in the public key and in the message are rejected as well (sampled)386 for bit in stride(from: 0, to: pair.publicKey.count * 8, by: 97) {387 var pk = pair.publicKey388 pk[bit / 8] ^= 1 << UInt8(bit % 8)389 #expect(!MLDSA.verify(ps, publicKey: pk, message: message, signature: sig))390 }391 for bit in 0..<(message.count * 8) {392 var m = message393 m[bit / 8] ^= 1 << UInt8(bit % 8)394 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: m, signature: sig))395 }396 }397398 @Test(arguments: MLDSA.ParameterSet.allCases)399 func malformedInputsNeverTrap(_ ps: MLDSA.ParameterSet) throws {400 let pair = MLDSA.generateKeyPair(ps)401 let message = Array("malformed".utf8)402 let sig = try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, randomness: .deterministic)403404 // wrong lengths405 for s in [Bytes(), [0], Array(sig.dropLast()), sig + [0], Bytes(repeating: 0, count: ps.signatureSize * 2)] {406 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s))407 #expect(!MLDSA.verifyInternal(ps, publicKey: pair.publicKey, message: message, signature: s))408 #expect(!MLDSA.verifyInternal(ps, publicKey: pair.publicKey, mu: Bytes(repeating: 0, count: 64), signature: s))409 }410 for pk in [Bytes(), Array(pair.publicKey.dropLast()), pair.publicKey + [0]] {411 #expect(!MLDSA.verify(ps, publicKey: pk, message: message, signature: sig))412 #expect(!MLDSA.verifyInternal(ps, publicKey: pk, mu: Bytes(repeating: 0, count: 64), signature: sig))413 #expect(MLDSA.computeMu(ps, publicKey: pk, formattedMessage: message) == nil)414 }415 #expect(!MLDSA.verifyInternal(ps, publicKey: pair.publicKey, mu: Bytes(repeating: 0, count: 63), signature: sig))416 for sk in [Bytes(), Array(pair.privateKey.dropLast()), pair.privateKey + [0]] {417 #expect(throws: MLDSA.Error.invalidPrivateKeyLength) { try MLDSA.sign(ps, privateKey: sk, message: message) }418 #expect(throws: MLDSA.Error.invalidPrivateKeyLength) {419 try MLDSA.signInternal(ps, privateKey: sk, mu: Bytes(repeating: 0, count: 64), rnd: Bytes(repeating: 0, count: 32))420 }421 }422 for other in MLDSA.ParameterSet.allCases where other != ps {423 let foreign = MLDSA.generateKeyPair(other)424 #expect(throws: MLDSA.Error.invalidPrivateKeyLength) { try MLDSA.sign(ps, privateKey: foreign.privateKey, message: message) }425 #expect(!MLDSA.verify(ps, publicKey: foreign.publicKey, message: message, signature: sig))426 }427 #expect(throws: MLDSA.Error.invalidSeedLength) { try MLDSA.keyGenInternal(ps, seed: Bytes(repeating: 0, count: 31)) }428 #expect(throws: MLDSA.Error.invalidRandomnessLength) {429 try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, randomness: .explicit(Bytes(repeating: 0, count: 31)))430 }431 #expect(throws: MLDSA.Error.invalidRandomnessLength) {432 try MLDSA.signInternal(ps, privateKey: pair.privateKey, mu: Bytes(repeating: 0, count: 64), rnd: Bytes())433 }434 #expect(throws: MLDSA.Error.invalidMuLength) {435 try MLDSA.signInternal(ps, privateKey: pair.privateKey, mu: Bytes(repeating: 0, count: 65), rnd: Bytes(repeating: 0, count: 32))436 }437438 // context longer than 255 bytes439 let longContext = Bytes(repeating: 1, count: 256)440 #expect(throws: MLDSA.Error.contextTooLong) { try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, context: longContext) }441 #expect(throws: MLDSA.Error.contextTooLong) {442 try MLDSA.signPreHash(ps, privateKey: pair.privateKey, message: message, hash: .sha3_256, context: longContext)443 }444 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: sig, context: longContext))445446 // private key with an s1 coefficient outside [-eta, eta]447 var badKey = pair.privateKey448 badKey[128] |= ps.eta == 2 ? 0x07 : 0x0f449 #expect(throws: MLDSA.Error.invalidPrivateKey) { try MLDSA.sign(ps, privateKey: badKey, message: message) }450 badKey = pair.privateKey451 badKey[128 + 32 * ps.etaBits * ps.l] |= ps.eta == 2 ? 0x07 : 0x0f // first coefficient of s2452 #expect(throws: MLDSA.Error.invalidPrivateKey) { try MLDSA.sign(ps, privateKey: badKey, message: message) }453454 // z coefficient at the bound: encoding 0 means z = gamma1 >= gamma1 - beta455 var badZ = sig456 for i in 0..<3 { badZ[ps.cTildeSize + i] = 0 }457 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: badZ))458459 // malformed hints grafted on a valid signature460 let hintStart = sig.count - ps.omega - ps.k461 var s = sig462 s[sig.count - 1] = UInt8(ps.omega + 1) // counter above omega463 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s))464 s = sig465 s[sig.count - 1] = 0 // last counter below the previous ones (signatures carry at least one hint with overwhelming probability)466 if sig[sig.count - 2] > 0 || sig[sig.count - 1] > 0 {467 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s))468 }469 s = sig470 for i in 0..<ps.omega { s[hintStart + i] = 0xff } // positions not increasing471 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s))472 s = sig473 for i in 0..<(ps.omega + ps.k) { s[hintStart + i] = 0 } // empty hint: well formed, wrong474 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s))475 let used = Int(sig[sig.count - 1])476 if used < ps.omega {477 s = sig478 s[hintStart + ps.omega - 1] = 1 // non-zero padding479 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: s))480 }481482 // random and constant garbage of the right length483 for _ in 0..<40 {484 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: SystemRandom.bytes(ps.signatureSize)))485 #expect(!MLDSA.verify(ps, publicKey: SystemRandom.bytes(ps.publicKeySize), message: message, signature: sig))486 }487 for fill: UInt8 in [0x00, 0xff, 0x55, 0xaa] {488 #expect(!MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: Bytes(repeating: fill, count: ps.signatureSize)))489 #expect(!MLDSA.verify(ps, publicKey: Bytes(repeating: fill, count: ps.publicKeySize), message: message, signature: sig))490 #expect(491 !MLDSA.verify(492 ps, publicKey: Bytes(repeating: fill, count: ps.publicKeySize), message: message,493 signature: Bytes(repeating: fill, count: ps.signatureSize)))494 }495 // random private keys of the right length either sign or report an invalid key, never trap496 for _ in 0..<5 {497 _ = try? MLDSA.sign(ps, privateKey: SystemRandom.bytes(ps.privateKeySize), message: message)498 }499 }500}501