SPB Git

Repository Public

PrivateKeyValidationTests.swift 6.8 KB 131 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraMLDSATests/PrivateKeyValidationTests.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 QyvoraMath43import Testing4445@testable import QyvoraMLDSA4647/// Regression tests of QYV-FUZ-001: a private key is checked against itself and against its public key by48/// recomputation, not by one test signature.49@Suite struct MLDSAPrivateKeyValidationTests {50    static let sets: [MLDSA.ParameterSet] = [.mldsa44, .mldsa65, .mldsa87]5152    /// Offsets of the components of a private key: rho (32) ‖ K (32) ‖ tr (64) ‖ s1 ‖ s2 ‖ t0.53    static func layout(_ ps: MLDSA.ParameterSet) -> (s1: Int, s2: Int, t0: Int, end: Int) {54        let etaBytes = 32 * ps.etaBits55        return (128, 128 + etaBytes * ps.l, 128 + etaBytes * (ps.l + ps.k), ps.privateKeySize)56    }5758    @Test func thePublicKeyIsRecomputedFromThePrivateKey() throws {59        for ps in Self.sets {60            for seedByte in [UInt8(0), 0x5a, 0xff] {61                let pair = try MLDSA.keyGenInternal(ps, seed: Bytes(repeating: seedByte, count: 32))62                #expect(try MLDSA.publicKey(ps, fromPrivateKey: pair.privateKey) == pair.publicKey)63                #expect(MLDSA.isKeyPair(ps, privateKey: pair.privateKey, publicKey: pair.publicKey))64            }65            let fresh = MLDSA.generateKeyPair(ps)66            #expect(MLDSA.isKeyPair(ps, privateKey: fresh.privateKey, publicKey: fresh.publicKey))67            // another key pair's public key is not this private key's68            let other = MLDSA.generateKeyPair(ps)69            #expect(!MLDSA.isKeyPair(ps, privateKey: fresh.privateKey, publicKey: other.publicKey))70            #expect(!MLDSA.isKeyPair(ps, privateKey: Bytes(fresh.privateKey.dropLast()), publicKey: fresh.publicKey))71            #expect(throws: MLDSA.Error.invalidPrivateKeyLength) { _ = try MLDSA.publicKey(ps, fromPrivateKey: fresh.privateKey + [0]) }72        }73    }7475    /// The defect itself: one flipped bit in t0. A signature made with such a key often still verifies (t0 only76    /// enters the hint); the recomputation refuses every one of them.77    @Test func everySingleBitErrorInT0IsDetected() throws {78        for ps in Self.sets {79            let pair = try MLDSA.keyGenInternal(ps, seed: Bytes((0..<32).map { UInt8($0) }))80            let region = Self.layout(ps)81            var probesThatStillVerify = 082            let message = Bytes("QYVORA identity key check".utf8)83            // a spread of positions over the whole component, every bit of each84            for step in 0..<48 {85                let offset = region.t0 + (step * 7_919) % (region.end - region.t0)86                for bit in 0..<8 {87                    var damaged = pair.privateKey88                    damaged[offset] ^= UInt8(1 << bit)89                    #expect(throws: MLDSA.Error.invalidPrivateKey) { _ = try MLDSA.publicKey(ps, fromPrivateKey: damaged) }90                    #expect(!MLDSA.isKeyPair(ps, privateKey: damaged, publicKey: pair.publicKey))91                    if bit == 0, let signature = try? MLDSA.sign(ps, privateKey: damaged, message: message, randomness: .deterministic),92                       MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: signature) {93                        probesThatStillVerify += 194                    }95                }96            }97            // what made the old check (one test signature) insufficient: it accepts some of these damaged keys98            #expect(probesThatStillVerify > 0, "\(ps): no damaged key passed the probe signature in this sample")99        }100    }101102    @Test func damageInTheOtherComponentsIsDetectedExceptInK() throws {103        for ps in Self.sets {104            let pair = try MLDSA.keyGenInternal(ps, seed: Bytes(repeating: 0x33, count: 32))105            let region = Self.layout(ps)106            // rho, tr, s1, s2: a change gives another public key, an out-of-range vector or a wrong tr107            for offset in [0, 31, 64, 127, region.s1, region.s1 + 17, region.s2 - 1, region.s2, region.s2 + 40, region.t0 - 1] {108                var damaged = pair.privateKey109                damaged[offset] ^= 0x01110                #expect(!MLDSA.isKeyPair(ps, privateKey: damaged, publicKey: pair.publicKey), "\(ps): offset \(offset)")111            }112            // K is the seed of the signer's randomness: it has no public counterpart and cannot be validated.113            // A damaged K still gives valid signatures (other ones), so nothing depends on detecting it.114            var damagedK = pair.privateKey115            damagedK[40] ^= 0x80116            #expect(MLDSA.isKeyPair(ps, privateKey: damagedK, publicKey: pair.publicKey))117            let message: Bytes = [1, 2, 3]118            let signature = try MLDSA.sign(ps, privateKey: damagedK, message: message, randomness: .deterministic)119            #expect(MLDSA.verify(ps, publicKey: pair.publicKey, message: message, signature: signature))120            #expect(signature != (try MLDSA.sign(ps, privateKey: pair.privateKey, message: message, randomness: .deterministic)))121        }122    }123124    @Test func theFlagOfTheProcessorIsRestoredAfterValidation() throws {125        let pair = MLDSA.generateKeyPair(.mldsa44)126        _ = try MLDSA.publicKey(.mldsa44, fromPrivateKey: pair.privateKey)127        _ = try MLDSA.sign(.mldsa44, privateKey: pair.privateKey, message: [1])128        #expect(!DataIndependentTiming.isEnabled)129    }130}131
Files main
Menu

Theme