SPB Git

Repository Public

MLDSA.swift 30.2 KB 682 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraMLDSA/MLDSA.swift8// Module           : Qyvora MLDSA9// 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 QyvoraKeccak42import QyvoraMath4344/// ML-DSA, the module-lattice digital signature algorithm of FIPS 204 (August 2024), written45/// from the standard: internal algorithms (section 6), external pure and pre-hash interfaces46/// (section 5), encodings (section 7.2).47public enum MLDSA {48    public static let seedSize = 3249    public static let randomnessSize = 3250    public static let muSize = 6451    public static let maximumContextSize = 2555253    public enum ParameterSet: Sendable, CaseIterable, Equatable {54        case mldsa44, mldsa65, mldsa875556        /// Matrix dimensions (k rows, l columns).57        public var k: Int {58            switch self {59            case .mldsa44: return 460            case .mldsa65: return 661            case .mldsa87: return 862            }63        }6465        public var l: Int {66            switch self {67            case .mldsa44: return 468            case .mldsa65: return 569            case .mldsa87: return 770            }71        }7273        var eta: Int { self == .mldsa65 ? 4 : 2 }74        var etaBits: Int { self == .mldsa65 ? 4 : 3 }7576        var tau: Int {77            switch self {78            case .mldsa44: return 3979            case .mldsa65: return 4980            case .mldsa87: return 6081            }82        }8384        var beta: Int32 { Int32(tau * eta) }85        var gamma1Bits: Int { self == .mldsa44 ? 17 : 19 }86        var gamma1: Int32 { 1 << Int32(gamma1Bits) }87        var gamma2: Int32 { self == .mldsa44 ? (8_380_417 - 1) / 88 : (8_380_417 - 1) / 32 }88        var w1Bits: Int { self == .mldsa44 ? 6 : 4 }8990        var omega: Int {91            switch self {92            case .mldsa44: return 8093            case .mldsa65: return 5594            case .mldsa87: return 7595            }96        }9798        /// Length of the commitment hash c-tilde (lambda / 4 bytes).99        var cTildeSize: Int {100            switch self {101            case .mldsa44: return 32102            case .mldsa65: return 48103            case .mldsa87: return 64104            }105        }106107        public var publicKeySize: Int { 32 + 320 * k }108        public var privateKeySize: Int { 32 + 32 + 64 + 32 * etaBits * (k + l) + 416 * k }109        public var signatureSize: Int { cTildeSize + l * 32 * (gamma1Bits + 1) + omega + k }110111        public var name: String {112            switch self {113            case .mldsa44: return "ML-DSA-44"114            case .mldsa65: return "ML-DSA-65"115            case .mldsa87: return "ML-DSA-87"116            }117        }118    }119120    public enum Error: Swift.Error, Equatable, Sendable {121        case invalidSeedLength122        case invalidPrivateKeyLength123        /// Private key whose s1 or s2 encoding holds a coefficient outside [-eta, eta], or (validation only) whose t0 or124        /// tr component does not follow from rho, s1 and s2.125        case invalidPrivateKey126        case invalidRandomnessLength127        case invalidMuLength128        /// Context string longer than 255 bytes.129        case contextTooLong130        /// Pre-hash digest whose length does not match the hash function.131        case invalidDigestLength132        /// Object identifier that is not a DER-encoded OID (tag 0x06, short length).133        case invalidObjectIdentifier134    }135136    public struct KeyPair: Sendable, Equatable {137        public let publicKey: Bytes138        public let privateKey: Bytes139    }140141    /// Source of the 32-byte value rnd of ML-DSA.Sign.142    public enum Randomness: Sendable, Equatable {143        /// Hedged signing (default): rnd from the system generator.144        case hedged145        /// Deterministic signing: rnd = 32 zero bytes.146        case deterministic147        /// Caller-supplied rnd (test vectors).148        case explicit(Bytes)149    }150151    /// Pre-hash functions of HashML-DSA (FIPS 204, section 5.4) with their object identifiers.152    public enum PreHash: Sendable, CaseIterable, Equatable {153        case sha2_224, sha2_256, sha2_384, sha2_512, sha2_512_224, sha2_512_256154        case sha3_224, sha3_256, sha3_384, sha3_512, shake128, shake256155156        /// Last arc of 2.16.840.1.101.3.4.2.x (NIST hash algorithms).157        var arc: UInt8 {158            switch self {159            case .sha2_256: return 1160            case .sha2_384: return 2161            case .sha2_512: return 3162            case .sha2_224: return 4163            case .sha2_512_224: return 5164            case .sha2_512_256: return 6165            case .sha3_224: return 7166            case .sha3_256: return 8167            case .sha3_384: return 9168            case .sha3_512: return 10169            case .shake128: return 11170            case .shake256: return 12171            }172        }173174        /// DER encoding of the object identifier (11 bytes).175        public var oid: Bytes { [0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, arc] }176177        /// Digest length in bytes (SHAKE128: 32, SHAKE256: 64, as fixed by FIPS 204).178        public var digestSize: Int {179            switch self {180            case .sha2_224, .sha3_224, .sha2_512_224: return 28181            case .sha2_256, .sha3_256, .sha2_512_256, .shake128: return 32182            case .sha2_384, .sha3_384: return 48183            case .sha2_512, .sha3_512, .shake256: return 64184            }185        }186    }187188    /// The pre-hash functions this module computes itself (Keccak family). The SHA-2 functions189    /// are supported through the `digest:` entry points, the caller hashing the message.190    public enum KeccakPreHash: Sendable, CaseIterable, Equatable {191        case sha3_224, sha3_256, sha3_384, sha3_512, shake128, shake256192193        public var preHash: PreHash {194            switch self {195            case .sha3_224: return .sha3_224196            case .sha3_256: return .sha3_256197            case .sha3_384: return .sha3_384198            case .sha3_512: return .sha3_512199            case .shake128: return .shake128200            case .shake256: return .shake256201            }202        }203204        public func digest(_ message: Bytes) -> Bytes {205            switch self {206            case .sha3_224: return SHA3.sha3_224(message)207            case .sha3_256: return SHA3.sha3_256(message)208            case .sha3_384: return SHA3.sha3_384(message)209            case .sha3_512: return SHA3.sha3_512(message)210            case .shake128: return SHAKE.shake128(message, outputLength: 32)211            case .shake256: return SHAKE.shake256(message, outputLength: 64)212            }213        }214    }215216    // MARK: - Key generation217218    /// ML-DSA.KeyGen (Algorithm 1): seed from the system generator.219    public static func generateKeyPair(_ parameters: ParameterSet) -> KeyPair {220        var xi = SystemRandom.bytes(32)221        defer { SecureMemory.zero(&xi) }222        return keyGenCore(parameters, xi: xi)223    }224225    /// ML-DSA.KeyGen_internal(xi) (Algorithm 6).226    public static func keyGenInternal(_ parameters: ParameterSet, seed: Bytes) throws(Error) -> KeyPair {227        guard seed.count == 32 else { throw .invalidSeedLength }228        return keyGenCore(parameters, xi: seed)229    }230231    // MARK: - Private-key validation232233    /// The public key of a private key, recomputed from the private key itself, after checking that the private key234    /// is consistent (QYV-FUZ-001).235    ///236    /// FIPS 204 defines no validation of a private key. Its encoding (ρ, K, tr, s1, s2, t0) is nevertheless redundant:237    /// t = A(ρ)·s1 + s2 and (t1, t0) = Power2Round(t) follow from ρ, s1 and s2, the public key is (ρ, t1) and238    /// tr = H(public key). This function recomputes them and throws `invalidPrivateKey` when s1 or s2 is out of range,239    /// when the stored t0 differs from the recomputed one, or when the stored tr is not the hash of the recomputed240    /// public key. Comparing the result with a public key establishes that the two belong together — which one test241    /// signature does not: t0 only enters the hint, and a signature made with a damaged t0 often still verifies.242    ///243    /// K, the 32-byte seed of the signer's randomness, has no public counterpart and cannot be validated: a damaged244    /// K changes which valid signature is produced, never whether it verifies.245    public static func publicKey(_ parameters: ParameterSet, fromPrivateKey privateKey: Bytes) throws(Error) -> Bytes {246        let ps = parameters247        let sk = privateKey248        guard sk.count == ps.privateKeySize else { throw .invalidPrivateKeyLength }249        let dit = DataIndependentTiming.enable()250        defer { DataIndependentTiming.restore(dit) }251        let k = ps.k, l = ps.l252        let eta = Int32(ps.eta)253        let rho = Array(sk[0..<32])254255        // layout: A (k l) | s1 (l) | s2 (k) | t0 (k) | t (k); the workspace is erased when it goes away256        let ws = Workspace(polynomials: k * l + l + 3 * k)257        let a = ws.poly(0)258        let s1 = ws.poly(k * l), s2 = ws.poly(k * l + l), t0 = ws.poly(k * l + l + k), t = ws.poly(k * l + l + 2 * k)259        let etaBytes = 32 * ps.etaBits260        sk.withUnsafeBufferPointer { p in261            let b = p.baseAddress! + 128262            Coding.unpack(b, count: 256 * l, bits: ps.etaBits, subtractFrom: eta, into: s1)263            Coding.unpack(b + etaBytes * l, count: 256 * k, bits: ps.etaBits, subtractFrom: eta, into: s2)264            Coding.unpack(b + etaBytes * (l + k), count: 256 * k, bits: 13, subtractFrom: 1 << 12, into: t0)265        }266        guard !exceeds(s1, count: 256 * l, bound: eta + 1), !exceeds(s2, count: 256 * k, bound: eta + 1) else { throw .invalidPrivateKey }267268        // t = NTT^-1(A-hat o NTT(s1)) + s2, then Power2Round: the computation of key generation269        Sampling.expandA(rho: rho, k: k, l: l, into: a)270        for j in 0..<l { NTT.forward(s1 + 256 * j) }271        var difference: Int32 = 0272        for i in 0..<k {273            let ti = t + 256 * i, t0i = t0 + 256 * i, s2i = s2 + 256 * i274            for j in 0..<l { NTT.pointwise(ti, a + (i * l + j) * 256, s1 + 256 * j, accumulate: j > 0) }275            NTT.reduce(ti)276            NTT.inverseToMontgomery(ti)277            for c in 0..<256 {278                let (r1, r0) = Rounding.power2Round(Field.canonical(ti[c] &+ s2i[c]))279                // accumulated without an early exit: t0 is part of the private key280                difference |= r0 ^ t0i[c]281                ti[c] = r1282            }283        }284        var pk = Bytes()285        pk.reserveCapacity(ps.publicKeySize)286        pk += rho287        Coding.pack(t, count: 256 * k, bits: 10, subtractFrom: nil, into: &pk)288        let tr = SHAKE.shake256(pk, outputLength: 64)289        guard difference == 0, ConstantTime.equal(tr, Array(sk[64..<128])) else { throw .invalidPrivateKey }290        return pk291    }292293    /// True when `privateKey` is a consistent private key whose public key is `publicKey` (see `publicKey(_:fromPrivateKey:)`).294    public static func isKeyPair(_ parameters: ParameterSet, privateKey: Bytes, publicKey: Bytes) -> Bool {295        guard let derived = try? Self.publicKey(parameters, fromPrivateKey: privateKey) else { return false }296        return derived == publicKey297    }298299    // MARK: - Pure ML-DSA (FIPS 204, section 5.2 and 5.3)300301    /// ML-DSA.Sign (Algorithm 2).302    public static func sign(303        _ parameters: ParameterSet, privateKey: Bytes, message: Bytes, context: Bytes = [], randomness: Randomness = .hedged304    ) throws(Error) -> Bytes {305        guard context.count <= 255 else { throw .contextTooLong }306        return try signMessage(parameters, privateKey, [[0, UInt8(context.count)], context, message], randomness)307    }308309    /// ML-DSA.Verify (Algorithm 3). Returns false for any malformed input.310    public static func verify(311        _ parameters: ParameterSet, publicKey: Bytes, message: Bytes, signature: Bytes, context: Bytes = []312    ) -> Bool {313        guard context.count <= 255 else { return false }314        return verifyMessage(parameters, publicKey, [[0, UInt8(context.count)], context, message], signature)315    }316317    // MARK: - HashML-DSA (FIPS 204, section 5.4)318319    /// HashML-DSA.Sign (Algorithm 4) with a Keccak-family pre-hash computed here.320    public static func signPreHash(321        _ parameters: ParameterSet, privateKey: Bytes, message: Bytes, hash: KeccakPreHash, context: Bytes = [],322        randomness: Randomness = .hedged323    ) throws(Error) -> Bytes {324        try signPreHashed(325            parameters, privateKey: privateKey, digest: hash.digest(message), hash: hash.preHash, context: context, randomness: randomness)326    }327328    /// HashML-DSA.Sign (Algorithm 4) on a digest computed by the caller with one of the approved functions.329    public static func signPreHashed(330        _ parameters: ParameterSet, privateKey: Bytes, digest: Bytes, hash: PreHash, context: Bytes = [],331        randomness: Randomness = .hedged332    ) throws(Error) -> Bytes {333        guard digest.count == hash.digestSize else { throw .invalidDigestLength }334        return try signPreHashed(parameters, privateKey: privateKey, digest: digest, oid: hash.oid, context: context, randomness: randomness)335    }336337    /// HashML-DSA.Sign on a caller-supplied digest and DER-encoded object identifier338    /// (hash functions outside the built-in list).339    public static func signPreHashed(340        _ parameters: ParameterSet, privateKey: Bytes, digest: Bytes, oid: Bytes, context: Bytes = [],341        randomness: Randomness = .hedged342    ) throws(Error) -> Bytes {343        guard context.count <= 255 else { throw .contextTooLong }344        guard isDEROID(oid) else { throw .invalidObjectIdentifier }345        return try signMessage(parameters, privateKey, [[1, UInt8(context.count)], context, oid, digest], randomness)346    }347348    /// HashML-DSA.Verify (Algorithm 5) with a Keccak-family pre-hash computed here.349    public static func verifyPreHash(350        _ parameters: ParameterSet, publicKey: Bytes, message: Bytes, signature: Bytes, hash: KeccakPreHash, context: Bytes = []351    ) -> Bool {352        verifyPreHashed(353            parameters, publicKey: publicKey, digest: hash.digest(message), signature: signature, hash: hash.preHash, context: context)354    }355356    /// HashML-DSA.Verify (Algorithm 5) on a digest computed by the caller.357    public static func verifyPreHashed(358        _ parameters: ParameterSet, publicKey: Bytes, digest: Bytes, signature: Bytes, hash: PreHash, context: Bytes = []359    ) -> Bool {360        guard digest.count == hash.digestSize else { return false }361        return verifyPreHashed(parameters, publicKey: publicKey, digest: digest, signature: signature, oid: hash.oid, context: context)362    }363364    public static func verifyPreHashed(365        _ parameters: ParameterSet, publicKey: Bytes, digest: Bytes, signature: Bytes, oid: Bytes, context: Bytes = []366    ) -> Bool {367        guard context.count <= 255, isDEROID(oid) else { return false }368        return verifyMessage(parameters, publicKey, [[1, UInt8(context.count)], context, oid, digest], signature)369    }370371    // MARK: - Internal interface (FIPS 204, section 6)372373    /// ML-DSA.Sign_internal(sk, M', rnd) (Algorithm 7): `message` is the already formatted M'.374    public static func signInternal(_ parameters: ParameterSet, privateKey: Bytes, message: Bytes, rnd: Bytes) throws(Error) -> Bytes {375        try signMessage(parameters, privateKey, [message], .explicit(rnd))376    }377378    /// ML-DSA.Sign_internal with an externally computed mu = H(tr || M', 64) ("external mu").379    public static func signInternal(_ parameters: ParameterSet, privateKey: Bytes, mu: Bytes, rnd: Bytes) throws(Error) -> Bytes {380        guard privateKey.count == parameters.privateKeySize else { throw .invalidPrivateKeyLength }381        guard mu.count == 64 else { throw .invalidMuLength }382        guard rnd.count == 32 else { throw .invalidRandomnessLength }383        return try signCore(parameters, sk: privateKey, mu: mu, rnd: rnd)384    }385386    /// ML-DSA.Verify_internal(pk, M', sigma) (Algorithm 8).387    public static func verifyInternal(_ parameters: ParameterSet, publicKey: Bytes, message: Bytes, signature: Bytes) -> Bool {388        verifyMessage(parameters, publicKey, [message], signature)389    }390391    /// ML-DSA.Verify_internal with an externally computed mu.392    public static func verifyInternal(_ parameters: ParameterSet, publicKey: Bytes, mu: Bytes, signature: Bytes) -> Bool {393        guard publicKey.count == parameters.publicKeySize, signature.count == parameters.signatureSize, mu.count == 64 else { return false }394        return verifyCore(parameters, pk: publicKey, mu: mu, sig: signature)395    }396397    /// mu = H(tr || M', 64) where tr = H(pk, 64): lets a caller hash a large message away from the private key.398    public static func computeMu(_ parameters: ParameterSet, publicKey: Bytes, formattedMessage: Bytes) -> Bytes? {399        guard publicKey.count == parameters.publicKeySize else { return nil }400        return mu(tr: SHAKE.shake256(publicKey, outputLength: 64), parts: [formattedMessage])401    }402403    // MARK: - Plumbing404405    static func isDEROID(_ oid: Bytes) -> Bool {406        oid.count >= 3 && oid.count <= 129 && oid[0] == 0x06 && Int(oid[1]) == oid.count - 2 && oid[1] < 0x80407    }408409    static func mu(tr: Bytes, parts: [Bytes]) -> Bytes {410        var h = SHAKE(256)411        h.absorb(tr)412        for p in parts { h.absorb(p) }413        return h.squeeze(64)414    }415416    static func signMessage(_ ps: ParameterSet, _ sk: Bytes, _ parts: [Bytes], _ randomness: Randomness) throws(Error) -> Bytes {417        guard sk.count == ps.privateKeySize else { throw .invalidPrivateKeyLength }418        var rnd: Bytes419        switch randomness {420        case .hedged: rnd = SystemRandom.bytes(32)421        case .deterministic: rnd = Bytes(repeating: 0, count: 32)422        case .explicit(let r):423            guard r.count == 32 else { throw .invalidRandomnessLength }424            rnd = r425        }426        defer { SecureMemory.zero(&rnd) }427        return try signCore(ps, sk: sk, mu: mu(tr: Array(sk[64..<128]), parts: parts), rnd: rnd)428    }429430    static func verifyMessage(_ ps: ParameterSet, _ pk: Bytes, _ parts: [Bytes], _ sig: Bytes) -> Bool {431        guard pk.count == ps.publicKeySize, sig.count == ps.signatureSize else { return false }432        return verifyCore(ps, pk: pk, mu: mu(tr: SHAKE.shake256(pk, outputLength: 64), parts: parts), sig: sig)433    }434435    /// OR of the "norm >= bound" indicator over `count` coefficients, without early exit.436    /// Coefficients must be the centered representatives produced by `reduce32`.437    @inline(__always)438    static func exceeds(_ a: UnsafePointer<Int32>, count: Int, bound: Int32) -> Bool {439        var bad: Int32 = 0440        for i in 0..<count {441            let v = a[i]442            let t = v &- ((v >> 31) & (2 &* v))  // |v|443            bad |= (bound &- 1 &- t) >> 31444        }445        return bad != 0446    }447448    // MARK: - Core algorithms449450    static func keyGenCore(_ ps: ParameterSet, xi: Bytes) -> KeyPair {451        let dit = DataIndependentTiming.enable()452        defer { DataIndependentTiming.restore(dit) }453        let k = ps.k, l = ps.l454        var seedInput = xi + [UInt8(k), UInt8(l)]455        var seed = SHAKE.shake256(seedInput, outputLength: 128)456        SecureMemory.zero(&seedInput)457        let rho = Array(seed[0..<32])458        var rhoPrime = Array(seed[32..<96])459        var key = Array(seed[96..<128])460461        // layout: A (k l) | s1 (l) | s1-hat (l) | s2 (k) | t (k) | t0 (k)462        let ws = Workspace(polynomials: k * l + 2 * l + 3 * k)463        let a = ws.poly(0)464        let s1 = ws.poly(k * l), s1Hat = ws.poly(k * l + l)465        let s2 = ws.poly(k * l + 2 * l), t = ws.poly(k * l + 2 * l + k), t0 = ws.poly(k * l + 2 * l + 2 * k)466467        Sampling.expandA(rho: rho, k: k, l: l, into: a)468        for r in 0..<l { Sampling.rejBoundedPoly(seed: rhoPrime, nonce: UInt16(r), eta: ps.eta, into: s1 + 256 * r) }469        for r in 0..<k { Sampling.rejBoundedPoly(seed: rhoPrime, nonce: UInt16(l + r), eta: ps.eta, into: s2 + 256 * r) }470        for i in 0..<(256 * l) { s1Hat[i] = s1[i] }471        for j in 0..<l { NTT.forward(s1Hat + 256 * j) }472473        // t = NTT^-1(A-hat o NTT(s1)) + s2, then Power2Round474        for i in 0..<k {475            let ti = t + 256 * i, t0i = t0 + 256 * i, s2i = s2 + 256 * i476            for j in 0..<l { NTT.pointwise(ti, a + (i * l + j) * 256, s1Hat + 256 * j, accumulate: j > 0) }477            NTT.reduce(ti)478            NTT.inverseToMontgomery(ti)479            for c in 0..<256 {480                let (r1, r0) = Rounding.power2Round(Field.canonical(ti[c] &+ s2i[c]))481                ti[c] = r1482                t0i[c] = r0483            }484        }485486        var pk = Bytes()487        pk.reserveCapacity(ps.publicKeySize)488        pk += rho489        Coding.pack(t, count: 256 * k, bits: 10, subtractFrom: nil, into: &pk)490        let tr = SHAKE.shake256(pk, outputLength: 64)491492        var sk = Bytes()493        sk.reserveCapacity(ps.privateKeySize)494        sk += rho495        sk += key496        sk += tr497        Coding.pack(s1, count: 256 * l, bits: ps.etaBits, subtractFrom: Int32(ps.eta), into: &sk)498        Coding.pack(s2, count: 256 * k, bits: ps.etaBits, subtractFrom: Int32(ps.eta), into: &sk)499        Coding.pack(t0, count: 256 * k, bits: 13, subtractFrom: 1 << 12, into: &sk)500501        SecureMemory.zero(&seed)502        SecureMemory.zero(&rhoPrime)503        SecureMemory.zero(&key)504        return KeyPair(publicKey: pk, privateKey: sk)505    }506507    static func signCore(_ ps: ParameterSet, sk: Bytes, mu: Bytes, rnd: Bytes) throws(Error) -> Bytes {508        let dit = DataIndependentTiming.enable()509        defer { DataIndependentTiming.restore(dit) }510        let k = ps.k, l = ps.l511        let eta = Int32(ps.eta), gamma1 = ps.gamma1, gamma2 = ps.gamma2, beta = ps.beta512        let rho = Array(sk[0..<32])513514        // layout: A (k l) | s1 (l) | s2 (k) | t0 (k) | y (l) | z (l) | w1 (k) | w0 (k) | h (k) | c (1)515        let ws = Workspace(polynomials: k * l + 3 * l + 5 * k + 1)516        let a = ws.poly(0)517        let s1 = ws.poly(k * l), s2 = ws.poly(k * l + l), t0 = ws.poly(k * l + l + k)518        let y = ws.poly(k * l + l + 2 * k), z = ws.poly(k * l + 2 * l + 2 * k)519        let w1 = ws.poly(k * l + 3 * l + 2 * k), w0 = ws.poly(k * l + 3 * l + 3 * k), h = ws.poly(k * l + 3 * l + 4 * k)520        let c = ws.poly(k * l + 3 * l + 5 * k)521522        // skDecode (Algorithm 25); the s1/s2 encodings are checked to lie in [0, 2 eta]523        // (one aggregated test, no per-coefficient exit).524        let etaBytes = 32 * ps.etaBits525        sk.withUnsafeBufferPointer { p in526            let b = p.baseAddress! + 128527            Coding.unpack(b, count: 256 * l, bits: ps.etaBits, subtractFrom: eta, into: s1)528            Coding.unpack(b + etaBytes * l, count: 256 * k, bits: ps.etaBits, subtractFrom: eta, into: s2)529            Coding.unpack(b + etaBytes * (l + k), count: 256 * k, bits: 13, subtractFrom: 1 << 12, into: t0)530        }531        guard !exceeds(s1, count: 256 * l, bound: eta + 1), !exceeds(s2, count: 256 * k, bound: eta + 1) else {532            throw .invalidPrivateKey533        }534535        // rho'' = H(K || rnd || mu, 64)536        var xof = SHAKE(256)537        var key = Array(sk[32..<64])538        xof.absorb(key)539        xof.absorb(rnd)540        xof.absorb(mu)541        var rhoPP = xof.squeeze(64)542        xof.wipe()543        SecureMemory.zero(&key)544        defer { SecureMemory.zero(&rhoPP) }545546        Sampling.expandA(rho: rho, k: k, l: l, into: a)547        for j in 0..<l { NTT.forward(s1 + 256 * j) }548        for i in 0..<k {549            NTT.forward(s2 + 256 * i)550            NTT.forward(t0 + 256 * i)551        }552553        var w1Bytes = Bytes()554        w1Bytes.reserveCapacity(32 * ps.w1Bits * k)555        var kappa = 0556        // Rejection loop (Algorithm 7, line 10). Each rejected candidate is independent of the557        // signature finally released, so the branches below reveal nothing about the key.558        while true {559            for r in 0..<l {560                Sampling.expandMaskPoly(seed: rhoPP, nonce: UInt16(truncatingIfNeeded: kappa + r), gamma1Bits: ps.gamma1Bits, into: y + 256 * r)561            }562            kappa += l563564            // w = NTT^-1(A-hat o NTT(y)), decomposed into (w1, w0)565            for i in 0..<(256 * l) { z[i] = y[i] }566            for j in 0..<l { NTT.forward(z + 256 * j) }567            for i in 0..<k {568                let w1i = w1 + 256 * i, w0i = w0 + 256 * i569                for j in 0..<l { NTT.pointwise(w1i, a + (i * l + j) * 256, z + 256 * j, accumulate: j > 0) }570                NTT.reduce(w1i)571                NTT.inverseToMontgomery(w1i)572                for x in 0..<256 {573                    let (r1, r0) = Rounding.decompose(Field.addQIfNegative(w1i[x]), gamma2: gamma2)574                    w1i[x] = r1575                    w0i[x] = r0576                }577            }578579            // c-tilde = H(mu || w1Encode(w1), lambda / 4), c = SampleInBall(c-tilde)580            w1Bytes.removeAll(keepingCapacity: true)581            Coding.pack(w1, count: 256 * k, bits: ps.w1Bits, subtractFrom: nil, into: &w1Bytes)582            var hash = SHAKE(256)583            hash.absorb(mu)584            hash.absorb(w1Bytes)585            let cTilde = hash.squeeze(ps.cTildeSize)586            Sampling.sampleInBall(seed: cTilde, tau: ps.tau, into: c)587            NTT.forward(c)588589            // z = y + c s1590            for j in 0..<l {591                let zj = z + 256 * j, yj = y + 256 * j592                NTT.pointwise(zj, c, s1 + 256 * j, accumulate: false)593                NTT.inverseToMontgomery(zj)594                for x in 0..<256 { zj[x] = Field.reduce32(zj[x] &+ yj[x]) }595            }596            if exceeds(z, count: 256 * l, bound: gamma1 - beta) { continue }597598            // r0 = LowBits(w - c s2)599            for i in 0..<k {600                let hi = h + 256 * i, w0i = w0 + 256 * i601                NTT.pointwise(hi, c, s2 + 256 * i, accumulate: false)602                NTT.inverseToMontgomery(hi)603                for x in 0..<256 { w0i[x] = Field.reduce32(w0i[x] &- hi[x]) }604            }605            if exceeds(w0, count: 256 * k, bound: gamma2 - beta) { continue }606607            // c t0, then the hint608            for i in 0..<k {609                let hi = h + 256 * i610                NTT.pointwise(hi, c, t0 + 256 * i, accumulate: false)611                NTT.inverseToMontgomery(hi)612                NTT.reduce(hi)613            }614            if exceeds(h, count: 256 * k, bound: gamma2) { continue }615            var ones = 0616            for x in 0..<(256 * k) {617                let bit = Rounding.makeHint(low: w0[x] &+ h[x], high: w1[x], gamma2: gamma2)618                h[x] = bit619                ones += Int(bit)620            }621            if ones > ps.omega { continue }622623            // sigEncode (Algorithm 26)624            var sig = Bytes()625            sig.reserveCapacity(ps.signatureSize)626            sig += cTilde627            Coding.pack(z, count: 256 * l, bits: ps.gamma1Bits + 1, subtractFrom: gamma1, into: &sig)628            Coding.packHint(h, k: k, omega: ps.omega, into: &sig)629            return sig630        }631    }632633    static func verifyCore(_ ps: ParameterSet, pk: Bytes, mu: Bytes, sig: Bytes) -> Bool {634        let k = ps.k, l = ps.l635        let gamma2 = ps.gamma2636        let rho = Array(pk[0..<32])637        let cTilde = Array(sig[0..<ps.cTildeSize])638639        // layout: A (k l) | z (l) | h (k) | w (k) | t (1) | c (1)640        let ws = Workspace(polynomials: k * l + l + 2 * k + 2)641        let a = ws.poly(0)642        let z = ws.poly(k * l), h = ws.poly(k * l + l), w = ws.poly(k * l + l + k)643        let t = ws.poly(k * l + l + 2 * k), c = ws.poly(k * l + l + 2 * k + 1)644645        // sigDecode (Algorithm 27)646        let zBytes = 32 * (ps.gamma1Bits + 1)647        let hintOK = sig.withUnsafeBufferPointer { p -> Bool in648            let b = p.baseAddress! + ps.cTildeSize649            Coding.unpack(b, count: 256 * l, bits: ps.gamma1Bits + 1, subtractFrom: ps.gamma1, into: z)650            return Coding.unpackHint(b + zBytes * l, k: k, omega: ps.omega, into: h)651        }652        guard hintOK else { return false }653        guard !exceeds(z, count: 256 * l, bound: ps.gamma1 - ps.beta) else { return false }654655        Sampling.expandA(rho: rho, k: k, l: l, into: a)656        Sampling.sampleInBall(seed: cTilde, tau: ps.tau, into: c)657        NTT.forward(c)658        for j in 0..<l { NTT.forward(z + 256 * j) }659660        // w'approx = NTT^-1(A-hat o NTT(z) - NTT(c) o NTT(t1 2^d)), w1' = UseHint(h, w'approx)661        var w1Bytes = Bytes()662        w1Bytes.reserveCapacity(32 * ps.w1Bits * k)663        pk.withUnsafeBufferPointer { p in664            for i in 0..<k {665                let wi = w + 256 * i, hi = h + 256 * i666                for j in 0..<l { NTT.pointwise(wi, a + (i * l + j) * 256, z + 256 * j, accumulate: j > 0) }667                Coding.unpack(p.baseAddress! + 32 + 320 * i, count: 256, bits: 10, subtractFrom: nil, into: t)668                for x in 0..<256 { t[x] = t[x] << 13 }669                NTT.forward(t)670                for x in 0..<256 { wi[x] = Field.reduce32(wi[x] &- Field.multiply(c[x], t[x])) }671                NTT.inverseToMontgomery(wi)672                for x in 0..<256 { wi[x] = Rounding.useHint(hi[x] != 0, Field.addQIfNegative(wi[x]), gamma2: gamma2) }673            }674        }675        Coding.pack(w, count: 256 * k, bits: ps.w1Bits, subtractFrom: nil, into: &w1Bytes)676        var hash = SHAKE(256)677        hash.absorb(mu)678        hash.absorb(w1Bytes)679        return hash.squeeze(ps.cTildeSize) == cTilde680    }681}682
Files main
Menu

Theme