Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraMLKEMTests/MLKEMPropertyTests.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 QyvoraMLKEM4748@Suite struct MLKEMPropertyTests {49 static func randomPoly() -> [UInt16] {50 let b = SystemRandom.bytes(512)51 return (0..<256).map { (UInt16(b[2 * $0]) | UInt16(b[2 * $0 + 1]) << 8) % 3329 }52 }5354 @Test func sizes() {55 let expected: [(MLKEM.ParameterSet, Int, Int, Int)] = [56 (.mlkem512, 800, 1632, 768), (.mlkem768, 1184, 2400, 1088), (.mlkem1024, 1568, 3168, 1568),57 ]58 for (ps, ek, dk, ct) in expected {59 #expect(ps.encapsulationKeySize == ek)60 #expect(ps.decapsulationKeySize == dk)61 #expect(ps.ciphertextSize == ct)62 #expect(ps.sharedSecretSize == 32)63 let pair = MLKEM.generateKeyPair(ps)64 #expect(pair.encapsulationKey.count == ek)65 #expect(pair.decapsulationKey.count == dk)66 }67 }6869 @Test func zetaTable() {70 // First entries of the Montgomery-form table and the plain value zeta^BitRev7(1) = 17^64 = 1729.71 #expect(Array(MLKEM.NTT.zetas[0..<4]) == [-1044, -758, -359, -1517])72 #expect(MLKEM.Field.canonical(MLKEM.Field.montgomeryReduce(Int32(MLKEM.NTT.zetas[1]))) == 1729)73 }7475 @Test func fieldReductions() {76 for a in Int16.min...Int16.max {77 let r = MLKEM.Field.barrettReduce(a)78 #expect(r >= -1664 && r <= 1664 && (Int(a) - Int(r)) % 3329 == 0)79 let c = MLKEM.Field.canonical(a)80 #expect(c >= 0 && c < 3329 && (Int(a) - Int(c)) % 3329 == 0)81 }82 // Montgomery reduction on a spread of the admissible range |a| < q * 2^1583 var a: Int32 = -3329 * 32768 + 184 while a < 3329 * 32768 {85 let r = Int(MLKEM.Field.montgomeryReduce(a))86 #expect(r > -3329 && r < 3329)87 #expect(((r * 65536 - Int(a)) % 3329) == 0)88 a += 997389 }90 }9192 @Test func compressMatchesDefinition() {93 // Exhaustive comparison with the rational definition round(2^d x / q) mod 2^d.94 for d in [1, 4, 5, 10, 11] {95 for x in 0..<3329 {96 let reference = ((x << (d + 1)) + 3329) / (2 * 3329) % (1 << d)97 #expect(Int(MLKEM.Field.compress(UInt32(x), bits: d)) == reference)98 }99 for y in 0..<(1 << d) {100 let reference = (2 * y * 3329 + (1 << d)) / (1 << (d + 1))101 let got = Int(MLKEM.Field.decompress(UInt32(y), bits: d))102 #expect(got == reference)103 #expect(Int(MLKEM.Field.compress(UInt32(got), bits: d)) == y)104 }105 }106 }107108 @Test func nttRoundTripAndProduct() {109 for _ in 0..<20 {110 let f = Self.randomPoly(), g = Self.randomPoly()111 #expect(MLKEM.NTT.inverseNTT(MLKEM.NTT.ntt(f)) == f)112 // schoolbook product in Z_q[X] / (X^256 + 1)113 var h = [Int](repeating: 0, count: 256)114 for i in 0..<256 {115 for j in 0..<256 {116 let p = Int(f[i]) * Int(g[j]) % 3329117 if i + j < 256 { h[i + j] = (h[i + j] + p) % 3329 } else { h[i + j - 256] = (h[i + j - 256] + 3329 - p) % 3329 }118 }119 }120 let viaNTT = MLKEM.NTT.inverseNTT(MLKEM.NTT.multiplyNTTs(MLKEM.NTT.ntt(f), MLKEM.NTT.ntt(g)))121 #expect(viaNTT.map(Int.init) == h)122 }123 }124125 @Test func codingRoundTrips() {126 for d in [1, 4, 5, 10, 11] {127 // ByteDecode_d then ByteEncode_d is the identity on byte strings (Compress o Decompress = id).128 let bytes = SystemRandom.bytes(32 * d)129 var poly = [Int16](repeating: 0, count: 256)130 bytes.withUnsafeBufferPointer { b in131 poly.withUnsafeMutableBufferPointer { MLKEM.Coding.decodeDecompress(b.baseAddress!, count: 256, bits: d, into: $0.baseAddress!) }132 }133 var out = Bytes()134 poly.withUnsafeBufferPointer { MLKEM.Coding.compressEncode($0.baseAddress!, count: 256, bits: d, into: &out) }135 #expect(out == bytes)136 }137 let f = Self.randomPoly().map { Int16($0) }138 var enc = Bytes()139 f.withUnsafeBufferPointer { MLKEM.Coding.encode12($0.baseAddress!, count: 256, into: &enc) }140 #expect(enc.count == 384)141 var back = [Int16](repeating: 0, count: 256)142 enc.withUnsafeBufferPointer { b in143 back.withUnsafeMutableBufferPointer { MLKEM.Coding.decode12(b.baseAddress!, count: 256, into: $0.baseAddress!) }144 }145 #expect(back == f)146 }147148 @Test func samplePolyCBDRange() {149 for eta in [2, 3] {150 var poly = [Int16](repeating: 0, count: 256)151 var histogram = [Int](repeating: 0, count: 2 * eta + 1)152 for nonce in 0..<40 {153 poly.withUnsafeMutableBufferPointer {154 MLKEM.Sampling.samplePolyCBD(seed: Bytes(repeating: 7, count: 32), nonce: UInt8(nonce), eta: eta, into: $0.baseAddress!)155 }156 for c in poly {157 #expect(Int(c) >= -eta && Int(c) <= eta)158 histogram[Int(c) + eta] += 1159 }160 }161 #expect(histogram.allSatisfy { $0 > 0 })162 #expect(histogram[eta] > histogram[0] && histogram[eta] > histogram[2 * eta])163 }164 }165166 @Test(arguments: MLKEM.ParameterSet.allCases)167 func randomRoundTrips(_ ps: MLKEM.ParameterSet) throws {168 for _ in 0..<25 {169 let pair = MLKEM.generateKeyPair(ps)170 #expect(MLKEM.isValidEncapsulationKey(ps, pair.encapsulationKey))171 #expect(MLKEM.isValidDecapsulationKey(ps, pair.decapsulationKey))172 let enc = try MLKEM.encapsulate(ps, encapsulationKey: pair.encapsulationKey)173 #expect(enc.ciphertext.count == ps.ciphertextSize)174 #expect(enc.sharedSecret.count == 32)175 #expect(try MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: enc.ciphertext) == enc.sharedSecret)176 // another key pair does not recover the secret177 let other = MLKEM.generateKeyPair(ps)178 #expect(try MLKEM.decapsulate(ps, decapsulationKey: other.decapsulationKey, ciphertext: enc.ciphertext) != enc.sharedSecret)179 }180 }181182 @Test(arguments: MLKEM.ParameterSet.allCases)183 func deterministicAndSeedForms(_ ps: MLKEM.ParameterSet) throws {184 let d = SystemRandom.bytes(32), z = SystemRandom.bytes(32), m = SystemRandom.bytes(32)185 let a = try MLKEM.keyGenInternal(ps, d: d, z: z)186 let b = try MLKEM.keyPair(ps, seed: d + z)187 #expect(a == b)188 // layout of the decapsulation key: dkPKE || ek || H(ek) || z189 let k = ps.k190 #expect(Array(a.decapsulationKey[(384 * k)..<(768 * k + 32)]) == a.encapsulationKey)191 #expect(Array(a.decapsulationKey[(768 * k + 32)..<(768 * k + 64)]) == SHA3.sha3_256(a.encapsulationKey))192 #expect(Array(a.decapsulationKey[(768 * k + 64)...]) == z)193 let e1 = try MLKEM.encapsInternal(ps, encapsulationKey: a.encapsulationKey, m: m)194 let e2 = try MLKEM.encapsInternal(ps, encapsulationKey: a.encapsulationKey, m: m)195 #expect(e1 == e2)196 #expect(try MLKEM.decapsInternal(ps, decapsulationKey: a.decapsulationKey, ciphertext: e1.ciphertext) == e1.sharedSecret)197 }198199 /// Every single-bit flip of a ciphertext must yield a different secret, equal to the200 /// implicit-rejection value J(z || c') of FIPS 203.201 @Test(arguments: MLKEM.ParameterSet.allCases)202 func everyCiphertextBitFlipIsRejectedImplicitly(_ ps: MLKEM.ParameterSet) throws {203 let pair = MLKEM.generateKeyPair(ps)204 let enc = try MLKEM.encapsulate(ps, encapsulationKey: pair.encapsulationKey)205 let z = Array(pair.decapsulationKey[(pair.decapsulationKey.count - 32)...])206 var different = 0, implicit = 0207 for bit in 0..<(enc.ciphertext.count * 8) {208 var c = enc.ciphertext209 c[bit / 8] ^= 1 << UInt8(bit % 8)210 let k = try MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: c)211 if k != enc.sharedSecret { different += 1 }212 // checking J(z || c') on every 16th flip keeps the debug run short213 if bit % 16 == 0 {214 if k == SHAKE.shake256(z + c, outputLength: 32) { implicit += 1 }215 }216 }217 #expect(different == enc.ciphertext.count * 8)218 #expect(implicit == (enc.ciphertext.count * 8 + 15) / 16)219 }220221 @Test(arguments: MLKEM.ParameterSet.allCases)222 func wrongLengthsAreRejected(_ ps: MLKEM.ParameterSet) throws {223 let pair = MLKEM.generateKeyPair(ps)224 let enc = try MLKEM.encapsulate(ps, encapsulationKey: pair.encapsulationKey)225 for ek in [Bytes(), Array(pair.encapsulationKey.dropLast()), pair.encapsulationKey + [0]] {226 #expect(throws: MLKEM.Error.invalidEncapsulationKeyLength) { try MLKEM.encapsulate(ps, encapsulationKey: ek) }227 #expect(throws: MLKEM.Error.invalidEncapsulationKeyLength) {228 try MLKEM.encapsInternal(ps, encapsulationKey: ek, m: Bytes(repeating: 0, count: 32))229 }230 }231 for c in [Bytes(), Array(enc.ciphertext.dropLast()), enc.ciphertext + [0]] {232 #expect(throws: MLKEM.Error.invalidCiphertextLength) {233 try MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: c)234 }235 #expect(throws: MLKEM.Error.invalidCiphertextLength) {236 try MLKEM.decapsInternal(ps, decapsulationKey: pair.decapsulationKey, ciphertext: c)237 }238 }239 for dk in [Bytes(), Array(pair.decapsulationKey.dropLast()), pair.decapsulationKey + [0]] {240 #expect(throws: MLKEM.Error.invalidDecapsulationKeyLength) {241 try MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: enc.ciphertext)242 }243 #expect(throws: MLKEM.Error.invalidDecapsulationKeyLength) {244 try MLKEM.decapsInternal(ps, decapsulationKey: dk, ciphertext: enc.ciphertext)245 }246 }247 #expect(throws: MLKEM.Error.invalidSeedLength) { try MLKEM.keyGenInternal(ps, d: Bytes(repeating: 0, count: 31), z: Bytes(repeating: 0, count: 32)) }248 #expect(throws: MLKEM.Error.invalidSeedLength) { try MLKEM.keyGenInternal(ps, d: Bytes(repeating: 0, count: 32), z: Bytes(repeating: 0, count: 33)) }249 #expect(throws: MLKEM.Error.invalidSeedLength) { try MLKEM.keyPair(ps, seed: Bytes(repeating: 0, count: 63)) }250 #expect(throws: MLKEM.Error.invalidSeedLength) {251 try MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: Bytes(repeating: 0, count: 16))252 }253 // keys of another parameter set254 for other in MLKEM.ParameterSet.allCases where other != ps {255 let foreign = MLKEM.generateKeyPair(other)256 #expect(throws: MLKEM.Error.invalidEncapsulationKeyLength) { try MLKEM.encapsulate(ps, encapsulationKey: foreign.encapsulationKey) }257 }258 }259260 @Test(arguments: MLKEM.ParameterSet.allCases)261 func encapsulationKeyModulusCheck(_ ps: MLKEM.ParameterSet) throws {262 let pair = MLKEM.generateKeyPair(ps)263 // Overwrite each coefficient in turn with a value in [q, 4095]: all must be rejected.264 for index in 0..<(256 * ps.k) {265 for value in [3329, 3330, 4095] where (index + value) % 7 == 0 || index < 4 || index >= 256 * ps.k - 4 {266 var ek = pair.encapsulationKey267 let o = (index / 2) * 3268 if index % 2 == 0 {269 ek[o] = UInt8(value & 0xff)270 ek[o + 1] = (ek[o + 1] & 0xf0) | UInt8(value >> 8)271 } else {272 ek[o + 1] = (ek[o + 1] & 0x0f) | UInt8((value & 0x0f) << 4)273 ek[o + 2] = UInt8(value >> 4)274 }275 #expect(!MLKEM.isValidEncapsulationKey(ps, ek))276 #expect(throws: MLKEM.Error.invalidEncapsulationKey) { try MLKEM.encapsulate(ps, encapsulationKey: ek) }277 }278 }279 // q - 1 everywhere is a valid encoding280 var ek = pair.encapsulationKey281 for i in stride(from: 0, to: 384 * ps.k, by: 3) {282 ek[i] = 0x00283 ek[i + 1] = 0x0d284 ek[i + 2] = 0xd0285 }286 #expect(MLKEM.isValidEncapsulationKey(ps, ek))287 // changing rho keeps the key well formed288 ek = pair.encapsulationKey289 ek[ek.count - 1] ^= 0xff290 #expect(MLKEM.isValidEncapsulationKey(ps, ek))291 }292293 @Test(arguments: MLKEM.ParameterSet.allCases)294 func decapsulationKeyHashCheck(_ ps: MLKEM.ParameterSet) throws {295 let pair = MLKEM.generateKeyPair(ps)296 let enc = try MLKEM.encapsulate(ps, encapsulationKey: pair.encapsulationKey)297 let k = ps.k298 // any flip inside ek or H(ek) breaks the hash check299 for position in [384 * k, 384 * k + 5, 768 * k + 31, 768 * k + 32, 768 * k + 63] {300 var dk = pair.decapsulationKey301 dk[position] ^= 0x01302 #expect(!MLKEM.isValidDecapsulationKey(ps, dk))303 #expect(throws: MLKEM.Error.invalidDecapsulationKey) {304 try MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: enc.ciphertext)305 }306 }307 // a flip in z passes the check and only changes the rejection secret308 var dk = pair.decapsulationKey309 dk[dk.count - 1] ^= 0x01310 #expect(MLKEM.isValidDecapsulationKey(ps, dk))311 #expect(try MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: enc.ciphertext) == enc.sharedSecret)312 }313}314