SPB Git

Repository Public

ACVPSHA2Tests.swift 6.5 KB 156 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraSymmetricTests/ACVPSHA2Tests.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 Testing43import QyvoraMath44@testable import QyvoraSymmetric4546private let largeDataEnabled = ProcessInfo.processInfo.environment["QYVORA_LDT"] == "1"4748/// NIST ACVP vectors for SHA2-256 and SHA2-512: AFT and MCT groups.49/// The LDT groups (messages of 1 to 8 GiB) run only when `QYVORA_LDT=1`.50@Suite struct ACVPSHA2Tests {51    struct Algorithm: Sendable, CustomStringConvertible {52        let file: String, digest: Int, aft: Int53        var description: String { file }54    }5556    static let algorithms = [57        Algorithm(file: "acvp-sha2-256.json.gz", digest: 32, aft: 512),58        Algorithm(file: "acvp-sha2-512.json.gz", digest: 64, aft: 1024),59    ]6061    static func hash(_ digest: Int, _ m: Bytes) -> Bytes {62        digest == 32 ? QyvoraSymmetric.SHA256.hash(m) : QyvoraSymmetric.SHA512.hash(m)63    }6465    @Test(arguments: algorithms) func aft(_ p: Algorithm) throws {66        let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "AFT" }67        var count = 068        var rng = SystemRandomNumberGenerator()69        for g in groups {70            for t in g.list("tests") {71                let len = t.int("len")72                #expect(len % 8 == 0)73                let msg = Bytes(t.bytes("msg").prefix(len / 8)), want = t.bytes("md")74                #expect(Self.hash(p.digest, msg) == want, "tcId \(t.str("tcId"))")75                // same message through the incremental interface, split at a random point76                let cut = msg.isEmpty ? 0 : Int.random(in: 0...msg.count, using: &rng)77                if p.digest == 32 {78                    var h = QyvoraSymmetric.SHA256()79                    h.update(Bytes(msg[0..<cut])); h.update(Bytes(msg[cut...]))80                    #expect(h.finalize() == want)81                } else {82                    var h = QyvoraSymmetric.SHA512()83                    h.update(Bytes(msg[0..<cut])); h.update(Bytes(msg[cut...]))84                    #expect(h.finalize() == want)85                }86                count += 187            }88        }89        #expect(count == p.aft)90    }9192    /// Monte Carlo test, "alternate" form of the ACVP SHA-2 specification: the message A || B || C is93    /// truncated or zero-padded to the length of the initial seed.94    @Test(arguments: algorithms) func mct(_ p: Algorithm) throws {95        let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "MCT" }96        var checkpoints = 097        for g in groups {98            #expect(g.str("mctVersion") == "alternate")99            for t in g.list("tests") {100                var seed = t.bytes("msg")101                let length = seed.count102                for r in t.list("resultsArray") {103                    var a = seed, b = seed, c = seed104                    for _ in 0..<1000 {105                        var m = a + b + c106                        if m.count >= length {107                            m.removeLast(m.count - length)108                        } else {109                            m += Bytes(repeating: 0, count: length - m.count)110                        }111                        a = b112                        b = c113                        c = Self.hash(p.digest, m)114                    }115                    seed = c116                    #expect(c == r.bytes("md"))117                    checkpoints += 1118                }119            }120        }121        #expect(checkpoints == 100)122    }123124    @Test(.enabled(if: largeDataEnabled), arguments: algorithms) func ldt(_ p: Algorithm) throws {125        let groups = try VectorFile.load(p.file).list("testGroups").filter { $0.str("testType") == "LDT" }126        var count = 0127        for g in groups {128            for t in g.list("tests") {129                guard let large = t["largeMsg"] as? [String: Any] else { continue }130                #expect(large.str("expansionTechnique") == "repeating")131                let content = large.bytes("content")132                let total = large.int("fullLength") / 8133                #expect(large.int("fullLength") % 8 == 0 && total % content.count == 0)134                var chunk = Bytes()135                while chunk.count < 1 << 20 { chunk += content }136                var done = 0137                let digest: Bytes138                if p.digest == 32 {139                    var h = QyvoraSymmetric.SHA256()140                    while total - done >= chunk.count { h.update(chunk); done += chunk.count }141                    if done < total { h.update(Bytes(chunk.prefix(total - done))) }142                    digest = h.finalize()143                } else {144                    var h = QyvoraSymmetric.SHA512()145                    while total - done >= chunk.count { h.update(chunk); done += chunk.count }146                    if done < total { h.update(Bytes(chunk.prefix(total - done))) }147                    digest = h.finalize()148                }149                #expect(digest == t.bytes("md"), "tcId \(t.str("tcId"))")150                count += 1151            }152        }153        #expect(count == 4)154    }155}156
Files main
Menu

Theme