Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraKeccakTests/ACVPKeccakTests.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 CryptoKit42import Foundation43import Testing44import QyvoraMath45@testable import QyvoraKeccak4647/// Sponge evaluation of a message of `bitLength` bits, built on the public byte-aligned sponge.48///49/// ACVP stores full bytes in the FIPS 202 order and left-aligns the trailing partial byte.50/// The partial bits are merged with the domain-separation suffix and the first padding bit;51/// when that no longer fits below bit 7 the merged byte is absorbed and the rest becomes the suffix.52private func spongeBits(rate: Int, suffix: UInt8, message: Bytes, bitLength: Int, output: Int) -> Bytes {53 let q = bitLength / 8, r = bitLength % 854 if r == 0 {55 var s = KeccakSponge(rate: rate, suffix: suffix)56 s.absorb(Bytes(message.prefix(q)))57 return s.squeeze(output)58 }59 let tail = UInt16(message[q] >> UInt8(8 - r))60 let merged = tail | UInt16(suffix) << UInt16(r)61 if merged < 0x80 {62 var s = KeccakSponge(rate: rate, suffix: UInt8(merged))63 s.absorb(Bytes(message.prefix(q)))64 return s.squeeze(output)65 }66 var s = KeccakSponge(rate: rate, suffix: UInt8(merged >> 8))67 s.absorb(Bytes(message.prefix(q)) + [UInt8(merged & 0xff)])68 return s.squeeze(output)69}7071private let largeDataEnabled = ProcessInfo.processInfo.environment["QYVORA_LDT"] == "1"7273/// NIST ACVP vectors (SHA3-256, SHA3-512, SHAKE-128, SHAKE-256): AFT, MCT and VOT groups.74/// The LDT groups (messages of 1 to 8 GiB) run only when `QYVORA_LDT=1`.75@Suite struct ACVPKeccakTests {76 struct Fixed: Sendable, CustomStringConvertible {77 let file: String, digest: Int, aft: Int78 var description: String { file }79 }8081 static let fixed = [82 Fixed(file: "acvp-sha3-256.json.gz", digest: 32, aft: 1194),83 Fixed(file: "acvp-sha3-512.json.gz", digest: 64, aft: 682),84 ]8586 struct Xof: Sendable, CustomStringConvertible {87 let file: String, bits: Int, aft: Int88 var description: String { file }89 }9091 static let xofs = [92 Xof(file: "acvp-shake-128.json.gz", bits: 128, aft: 1392),93 Xof(file: "acvp-shake-256.json.gz", bits: 256, aft: 1148),94 ]9596 static func oneShot(_ digest: Int, _ m: Bytes) -> Bytes {97 digest == 32 ? SHA3.sha3_256(m) : SHA3.sha3_512(m)98 }99100 @Test(arguments: fixed) func sha3AFT(_ p: Fixed) throws {101 let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "AFT" }102 var count = 0, bitOriented = 0103 for g in groups {104 for t in g.list("tests") {105 let msg = t.bytes("msg"), len = t.int("len"), want = t.bytes("md")106 let got = spongeBits(rate: 200 - 2 * p.digest, suffix: 0x06, message: msg, bitLength: len, output: p.digest)107 #expect(got == want, "tcId \(t.str("tcId"))")108 if len % 8 == 0 {109 #expect(Self.oneShot(p.digest, Bytes(msg.prefix(len / 8))) == want, "tcId \(t.str("tcId"))")110 } else {111 bitOriented += 1112 }113 count += 1114 }115 }116 #expect(count == p.aft)117 #expect(bitOriented > 0)118 }119120 /// Monte Carlo test of the ACVP SHA-3 specification: MD[i] = SHA3(MD[i-1]), 1000 times per checkpoint.121 @Test(arguments: fixed) func sha3MCT(_ p: Fixed) throws {122 let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "MCT" }123 var checkpoints = 0124 for g in groups {125 for t in g.list("tests") {126 var md = t.bytes("msg")127 for r in t.list("resultsArray") {128 for _ in 0..<1000 { md = Self.oneShot(p.digest, md) }129 #expect(md == r.bytes("md"))130 checkpoints += 1131 }132 }133 }134 #expect(checkpoints == 100)135 }136137 @Test(.enabled(if: largeDataEnabled), arguments: fixed) func sha3LDT(_ p: Fixed) throws {138 let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "LDT" }139 var count = 0140 for g in groups {141 for t in g.list("tests") {142 guard let large = t["largeMsg"] as? [String: Any] else { continue }143 #expect(large.str("expansionTechnique") == "repeating")144 let content = large.bytes("content")145 let total = large.int("fullLength") / 8146 #expect(large.int("fullLength") % 8 == 0 && total % content.count == 0)147 var chunk = Bytes()148 while chunk.count < 1 << 20 { chunk += content }149 var s = KeccakSponge(rate: 200 - 2 * p.digest, suffix: 0x06)150 var done = 0151 while total - done >= chunk.count {152 s.absorb(chunk)153 done += chunk.count154 }155 if done < total { s.absorb(Bytes(chunk.prefix(total - done))) }156 #expect(s.squeeze(p.digest) == t.bytes("md"), "tcId \(t.str("tcId"))")157 count += 1158 }159 }160 #expect(count == 4)161 }162163 @Test(arguments: xofs) func shakeAFT(_ p: Xof) throws {164 let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "AFT" }165 var count = 0166 for g in groups {167 for t in g.list("tests") {168 let msg = t.bytes("msg"), len = t.int("len"), want = t.bytes("md")169 #expect(t.int("outLen") == want.count * 8)170 let got = spongeBits(rate: 200 - p.bits / 4, suffix: 0x1f, message: msg, bitLength: len, output: want.count)171 #expect(got == want, "tcId \(t.str("tcId"))")172 if len % 8 == 0 {173 let m = Bytes(msg.prefix(len / 8))174 let direct = p.bits == 128 ? SHAKE.shake128(m, outputLength: want.count) : SHAKE.shake256(m, outputLength: want.count)175 #expect(direct == want, "tcId \(t.str("tcId"))")176 }177 count += 1178 }179 }180 #expect(count == p.aft)181 }182183 /// Variable output test: byte-aligned messages, output lengths in bits (the last byte keeps its low bits).184 @Test(arguments: xofs) func shakeVOT(_ p: Xof) throws {185 let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "VOT" }186 var count = 0187 for g in groups {188 for t in g.list("tests") {189 let msg = t.bytes("msg"), want = t.bytes("md"), outBits = t.int("outLen")190 #expect(t.int("len") == msg.count * 8)191 var x = SHAKE(p.bits)192 x.absorb(msg)193 var got = x.squeeze((outBits + 7) / 8)194 if outBits % 8 != 0 { got[got.count - 1] &= UInt8((1 << (outBits % 8)) - 1) }195 #expect(got == want, "tcId \(t.str("tcId"))")196 count += 1197 }198 }199 #expect(count == 512)200 }201202 /// Monte Carlo test of the ACVP SHAKE specification: the message is the leftmost 128 bits of the203 /// previous output and the next output length is derived from its last two bytes.204 @Test(arguments: xofs) func shakeMCT(_ p: Xof) throws {205 let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "MCT" }206 var checkpoints = 0207 for g in groups {208 let minBytes = g.int("minOutLen") / 8, maxBytes = g.int("maxOutLen") / 8209 let range = maxBytes - minBytes + 1210 for t in g.list("tests") {211 var out = t.bytes("msg")212 var outLen = maxBytes213 for r in t.list("resultsArray") {214 for _ in 0..<1000 {215 var msg = Bytes(out.prefix(16))216 if msg.count < 16 { msg += Bytes(repeating: 0, count: 16 - msg.count) }217 var x = SHAKE(p.bits)218 x.absorb(msg)219 out = x.squeeze(outLen)220 let rightmost = Int(out[out.count - 2]) << 8 | Int(out[out.count - 1])221 outLen = minBytes + rightmost % range222 }223 #expect(out == r.bytes("md"))224 #expect(out.count * 8 == r.int("outLen"))225 checkpoints += 1226 }227 }228 }229 #expect(checkpoints == 100)230 }231}232233/// Property and differential tests against CryptoKit (SHA-3 is available there since macOS 26).234@Suite struct KeccakDifferentialTests {235 static func random(_ n: Int) -> Bytes {236 var rng = SystemRandomNumberGenerator()237 return (0..<n).map { _ in UInt8.random(in: 0...255, using: &rng) }238 }239240 @Test func emptyMessageAnswers() {241 // FIPS 202 example values for the empty message242 #expect(SHA3.sha3_224([]).hex == "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7")243 #expect(SHA3.sha3_384([]).hex == "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004")244 #expect(SHA3_224.hash([]) == SHA3.sha3_224([]))245 #expect(SHA3_384.hash([]) == SHA3.sha3_384([]))246 }247248 @Test func sha3AgainstCryptoKit() {249 var rng = SystemRandomNumberGenerator()250 let lengths = Array(0...300) + [1000, 1087, 1088, 1089, 4096, 10_000, 65_537]251 for n in lengths {252 let m = Self.random(n)253 #expect(SHA3.sha3_256(m) == Array(CryptoKit.SHA3_256.hash(data: Data(m))))254 #expect(SHA3.sha3_384(m) == Array(CryptoKit.SHA3_384.hash(data: Data(m))))255 #expect(SHA3.sha3_512(m) == Array(CryptoKit.SHA3_512.hash(data: Data(m))))256 // incremental types with random chunking257 var a = QyvoraKeccak.SHA3_256(), b = QyvoraKeccak.SHA3_512(), c = QyvoraKeccak.SHA3_384(), d = SHA3_224()258 var i = 0259 while i < n {260 let step = min(n - i, Int.random(in: 0...200, using: &rng))261 let part = Array(m[i..<(i + step)])262 a.update(part); b.update(part); c.update(part); d.update(part)263 i += step264 }265 #expect(a.finalize() == SHA3.sha3_256(m))266 #expect(b.finalize() == SHA3.sha3_512(m))267 #expect(c.finalize() == SHA3.sha3_384(m))268 #expect(d.finalize() == SHA3.sha3_224(m))269 }270 }271272 /// The lane-wise squeeze must give the same stream whatever the split of the requests.273 @Test func squeezeSplitsAreConsistent() {274 var rng = SystemRandomNumberGenerator()275 for bits in [128, 256] {276 let m = Self.random(77)277 var whole = SHAKE(bits)278 whole.absorb(m)279 let want = whole.squeeze(2000)280 for _ in 0..<20 {281 var x = SHAKE(bits)282 x.absorb(m)283 var got = Bytes()284 while got.count < 2000 {285 let step = min(2000 - got.count, Int.random(in: 0...190, using: &rng))286 got += x.squeeze(step)287 }288 #expect(got == want)289 }290 // byte-by-byte291 var y = SHAKE(bits)292 y.absorb(m)293 var single = Bytes()294 for _ in 0..<400 { single += y.squeeze(1) }295 #expect(single == Bytes(want.prefix(400)))296 }297 }298}299