SPB Git

Repository Public

SLHDSA.swift 19.5 KB 423 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSLHDSA/SLHDSA.swift8// Module           : Qyvora SLHDSA9// 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 QyvoraSymmetric4546/// SLH-DSA, the stateless hash-based digital signature standard (FIPS 205, August 2024),47/// implemented from the specification for the twelve approved parameter sets.48///49/// Byte layouts (FIPS 205, sections 9.1 and 9.2):50/// - public key  `PK.seed ‖ PK.root` (2n bytes)51/// - secret key  `SK.seed ‖ SK.prf ‖ PK.seed ‖ PK.root` (4n bytes)52/// - signature   `R ‖ SIG_FORS ‖ SIG_HT`53public enum SLHDSA {54    /// The twelve parameter sets of FIPS 205, Table 2.55    public enum ParameterSet: String, CaseIterable, Sendable {56        case sha2_128s = "SLH-DSA-SHA2-128s"57        case sha2_128f = "SLH-DSA-SHA2-128f"58        case sha2_192s = "SLH-DSA-SHA2-192s"59        case sha2_192f = "SLH-DSA-SHA2-192f"60        case sha2_256s = "SLH-DSA-SHA2-256s"61        case sha2_256f = "SLH-DSA-SHA2-256f"62        case shake_128s = "SLH-DSA-SHAKE-128s"63        case shake_128f = "SLH-DSA-SHAKE-128f"64        case shake_192s = "SLH-DSA-SHAKE-192s"65        case shake_192f = "SLH-DSA-SHAKE-192f"66        case shake_256s = "SLH-DSA-SHAKE-256s"67        case shake_256f = "SLH-DSA-SHAKE-256f"6869        /// The name used by FIPS 205 and ACVP, e.g. `SLH-DSA-SHA2-128s`.70        public var name: String { rawValue }7172        /// Looks a parameter set up by its FIPS 205 name.73        public init?(name: String) { self.init(rawValue: name) }7475        var params: Params {76            switch self {77            case .sha2_128s: return Params(n: 16, h: 63, d: 7, hPrime: 9, a: 12, k: 14, m: 30, shake: false)78            case .sha2_128f: return Params(n: 16, h: 66, d: 22, hPrime: 3, a: 6, k: 33, m: 34, shake: false)79            case .sha2_192s: return Params(n: 24, h: 63, d: 7, hPrime: 9, a: 14, k: 17, m: 39, shake: false)80            case .sha2_192f: return Params(n: 24, h: 66, d: 22, hPrime: 3, a: 8, k: 33, m: 42, shake: false)81            case .sha2_256s: return Params(n: 32, h: 64, d: 8, hPrime: 8, a: 14, k: 22, m: 47, shake: false)82            case .sha2_256f: return Params(n: 32, h: 68, d: 17, hPrime: 4, a: 9, k: 35, m: 49, shake: false)83            case .shake_128s: return Params(n: 16, h: 63, d: 7, hPrime: 9, a: 12, k: 14, m: 30, shake: true)84            case .shake_128f: return Params(n: 16, h: 66, d: 22, hPrime: 3, a: 6, k: 33, m: 34, shake: true)85            case .shake_192s: return Params(n: 24, h: 63, d: 7, hPrime: 9, a: 14, k: 17, m: 39, shake: true)86            case .shake_192f: return Params(n: 24, h: 66, d: 22, hPrime: 3, a: 8, k: 33, m: 42, shake: true)87            case .shake_256s: return Params(n: 32, h: 64, d: 8, hPrime: 8, a: 14, k: 22, m: 47, shake: true)88            case .shake_256f: return Params(n: 32, h: 68, d: 17, hPrime: 4, a: 9, k: 35, m: 49, shake: true)89            }90        }9192        /// The security parameter n in bytes (16, 24 or 32): the length of each seed and hash value.93        public var n: Int { params.n }94        /// NIST security category (1, 3 or 5).95        public var securityCategory: Int { params.n == 16 ? 1 : (params.n == 24 ? 3 : 5) }96        /// Public key size in bytes (2n).97        public var publicKeySize: Int { 2 * params.n }98        /// Secret key size in bytes (4n).99        public var secretKeySize: Int { 4 * params.n }100        /// Signature size in bytes.101        public var signatureSize: Int { params.signatureSize }102    }103104    /// Numeric parameters of one set (FIPS 205, Table 2). lg_w = 4 for every approved set.105    struct Params: Sendable {106        let n: Int107        let h: Int108        let d: Int109        let hPrime: Int110        let a: Int111        let k: Int112        let m: Int113        let shake: Bool114115        var lgw: Int { 4 }116        var w: Int { 16 }117        var len1: Int { 2 * n }118        var len2: Int { 3 }119        var len: Int { 2 * n + 3 }120        var forsSignatureSize: Int { k * (1 + a) * n }121        var signatureSize: Int { (1 + k * (1 + a) + h + d * len) * n }122        var mdBytes: Int { (k * a + 7) / 8 }123        var treeBytes: Int { (h - hPrime + 7) / 8 }124        var leafBytes: Int { (hPrime + 7) / 8 }125    }126127    public enum Error: Swift.Error, Equatable, Sendable {128        /// A seed passed to key generation is not n bytes long.129        case invalidSeedLength130        /// The secret key is not 4n bytes long.131        case invalidSecretKeyLength132        /// The public key is not 2n bytes long.133        case invalidPublicKeyLength134        /// Explicit additional randomness is not n bytes long.135        case invalidRandomnessLength136        /// The context string is longer than 255 bytes.137        case contextTooLong138    }139140    public struct KeyPair: Sendable, Equatable {141        public let publicKey: Bytes142        public let secretKey: Bytes143144        public init(publicKey: Bytes, secretKey: Bytes) {145            self.publicKey = publicKey146            self.secretKey = secretKey147        }148    }149150    /// How the randomizer input `opt_rand` of a signature is chosen (FIPS 205, section 9.2).151    public enum Randomization: Sendable, Equatable {152        /// Hedged signing, the default: n fresh bytes from the system generator.153        case hedged154        /// Deterministic signing: `opt_rand = PK.seed`.155        case deterministic156        /// Caller-supplied n bytes of additional randomness (known-answer tests, external generators).157        case explicit(Bytes)158    }159160    /// Hash functions and XOFs usable for HashSLH-DSA pre-hashing (FIPS 205, section 10.2).161    public enum PreHash: String, CaseIterable, Sendable {162        case sha224 = "SHA2-224"163        case sha256 = "SHA2-256"164        case sha384 = "SHA2-384"165        case sha512 = "SHA2-512"166        case sha512_224 = "SHA2-512/224"167        case sha512_256 = "SHA2-512/256"168        case sha3_224 = "SHA3-224"169        case sha3_256 = "SHA3-256"170        case sha3_384 = "SHA3-384"171        case sha3_512 = "SHA3-512"172        /// SHAKE128 with 256 bits of output.173        case shake128 = "SHAKE-128"174        /// SHAKE256 with 512 bits of output.175        case shake256 = "SHAKE-256"176177        /// Last arc of the NIST hash algorithm OID 2.16.840.1.101.3.4.2.x.178        var oidArc: UInt8 {179            switch self {180            case .sha256: return 1181            case .sha384: return 2182            case .sha512: return 3183            case .sha224: return 4184            case .sha512_224: return 5185            case .sha512_256: return 6186            case .sha3_224: return 7187            case .sha3_256: return 8188            case .sha3_384: return 9189            case .sha3_512: return 10190            case .shake128: return 11191            case .shake256: return 12192            }193        }194195        /// DER encoding of the hash OID (11 bytes: `06 09 60 86 48 01 65 03 04 02 xx`).196        public var oid: Bytes { [0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, oidArc] }197198        /// Digest length in bytes of PH(M).199        public var digestSize: Int {200            switch self {201            case .sha224, .sha512_224, .sha3_224: return 28202            case .sha256, .sha512_256, .sha3_256, .shake128: return 32203            case .sha384, .sha3_384: return 48204            case .sha512, .sha3_512, .shake256: return 64205            }206        }207208        /// PH(M).209        public func digest(_ message: Bytes) -> Bytes {210            switch self {211            case .sha224: return SHA2Core.digest256(iv: SHA2Core.iv224, message, outLen: 28)212            case .sha256: return SHA256.hash(message)213            case .sha384: return SHA2Core.digest512(iv: SHA2Core.iv384, message, outLen: 48)214            case .sha512: return SHA512.hash(message)215            case .sha512_224: return SHA2Core.digest512(iv: SHA2Core.iv512_224, message, outLen: 28)216            case .sha512_256: return SHA2Core.digest512(iv: SHA2Core.iv512_256, message, outLen: 32)217            case .sha3_224: return SHA3.sha3_224(message)218            case .sha3_256: return SHA3.sha3_256(message)219            case .sha3_384: return SHA3.sha3_384(message)220            case .sha3_512: return SHA3.sha3_512(message)221            case .shake128: return SHAKE.shake128(message, outputLength: 32)222            case .shake256: return SHAKE.shake256(message, outputLength: 64)223            }224        }225    }226227    // MARK: Key generation228229    /// slh_keygen (Algorithm 21): a fresh key pair from the system random generator.230    public static func generateKeyPair(_ parameterSet: ParameterSet) -> KeyPair {231        let n = parameterSet.n232        var seeds = SystemRandom.bytes(3 * n)233        defer { SecureMemory.zero(&seeds) }234        var skSeed = Bytes(seeds[0..<n])235        var skPrf = Bytes(seeds[n..<(2 * n)])236        defer {237            SecureMemory.zero(&skSeed)238            SecureMemory.zero(&skPrf)239        }240        // the three seeds have the right length by construction241        return try! keyGenInternal(parameterSet, skSeed: skSeed, skPrf: skPrf, pkSeed: Bytes(seeds[(2 * n)...]))242    }243244    /// slh_keygen_internal (Algorithm 18): the key pair determined by three n-byte seeds.245    public static func keyGenInternal(_ parameterSet: ParameterSet, skSeed: Bytes, skPrf: Bytes, pkSeed: Bytes) throws -> KeyPair {246        let dit = DataIndependentTiming.enable()247        defer { DataIndependentTiming.restore(dit) }248        let p = parameterSet.params249        let n = p.n250        guard skSeed.count == n, skPrf.count == n, pkSeed.count == n else { throw Error.invalidSeedLength }251        var root = Bytes(repeating: 0, count: n)252        skSeed.withUnsafeBufferPointer { sk in253            pkSeed.withUnsafeBufferPointer { pk in254                root.withUnsafeMutableBufferPointer { r in255                    Core(p, pkSeed: pk.baseAddress!).topRoot(skSeed: sk.baseAddress!, r.baseAddress!)256                }257            }258        }259        return KeyPair(publicKey: pkSeed + root, secretKey: skSeed + skPrf + pkSeed + root)260    }261262    /// The public key embedded in a secret key (`PK.seed ‖ PK.root`).263    public static func publicKey(_ parameterSet: ParameterSet, fromSecretKey secretKey: Bytes) throws -> Bytes {264        let n = parameterSet.n265        guard secretKey.count == 4 * n else { throw Error.invalidSecretKeyLength }266        return Bytes(secretKey[(2 * n)...])267    }268269    // MARK: Internal interface (section 9)270271    /// Splits the H_msg digest into `md`, `idx_tree` and `idx_leaf` (Algorithm 19, lines 6 to 10).272    static func splitDigest(_ p: Params, _ digest: Bytes) -> (md: Bytes, idxTree: UInt64, idxLeaf: UInt32) {273        let md = Bytes(digest[0..<p.mdBytes])274        var tree: UInt64 = 0275        for b in digest[p.mdBytes..<(p.mdBytes + p.treeBytes)] { tree = (tree << 8) | UInt64(b) }276        let treeBits = p.h - p.hPrime277        if treeBits < 64 { tree &= (UInt64(1) << UInt64(treeBits)) - 1 }278        var leaf: UInt64 = 0279        for b in digest[(p.mdBytes + p.treeBytes)..<(p.mdBytes + p.treeBytes + p.leafBytes)] { leaf = (leaf << 8) | UInt64(b) }280        leaf &= (UInt64(1) << UInt64(p.hPrime)) - 1281        return (md, tree, UInt32(leaf))282    }283284    /// slh_sign_internal (Algorithm 19). `addrnd` is the n-byte additional randomness of the hedged285    /// variant; `nil` selects the deterministic variant (`opt_rand = PK.seed`).286    public static func signInternal(_ parameterSet: ParameterSet, message: Bytes, secretKey: Bytes, addrnd: Bytes?) throws -> Bytes {287        let dit = DataIndependentTiming.enable()288        defer { DataIndependentTiming.restore(dit) }289        let p = parameterSet.params290        let n = p.n291        guard secretKey.count == 4 * n else { throw Error.invalidSecretKeyLength }292        if let addrnd, addrnd.count != n { throw Error.invalidRandomnessLength }293        var skPrf = Bytes(secretKey[n..<(2 * n)])294        defer { SecureMemory.zero(&skPrf) }295        let pkSeed = Bytes(secretKey[(2 * n)..<(3 * n)])296        let pkRoot = Bytes(secretKey[(3 * n)..<(4 * n)])297298        let r = MessageHash.prfMsg(p, skPrf: skPrf, optRand: addrnd ?? pkSeed, message: message)299        let digest = MessageHash.hMsg(p, r: r, pkSeed: pkSeed, pkRoot: pkRoot, message: message)300        let (md, idxTree, idxLeaf) = splitDigest(p, digest)301302        var signature = Bytes(repeating: 0, count: p.signatureSize)303        signature.replaceSubrange(0..<n, with: r)304        secretKey.withUnsafeBufferPointer { sk in305            signature.withUnsafeMutableBufferPointer { sig in306                let skSeed = sk.baseAddress!307                let core = Core(p, pkSeed: skSeed + 2 * n)308                withUnsafeTemporaryAllocation(of: UInt8.self, capacity: n) { pkFors in309                    core.forsSign(md: md, skSeed: skSeed, idxTree: idxTree, idxLeaf: idxLeaf,310                                  sig.baseAddress! + n, pk: pkFors.baseAddress!)311                    core.htSign(pkFors.baseAddress!, skSeed: skSeed, idxTree: idxTree, idxLeaf: idxLeaf,312                                sig.baseAddress! + n + p.forsSignatureSize)313                }314            }315        }316        return signature317    }318319    /// slh_verify_internal (Algorithm 20). Returns false for any malformed input.320    public static func verifyInternal(_ parameterSet: ParameterSet, message: Bytes, signature: Bytes, publicKey: Bytes) -> Bool {321        let p = parameterSet.params322        let n = p.n323        guard publicKey.count == 2 * n, signature.count == p.signatureSize else { return false }324        let pkSeed = Bytes(publicKey[0..<n])325        let pkRoot = Bytes(publicKey[n...])326        let r = Bytes(signature[0..<n])327        let digest = MessageHash.hMsg(p, r: r, pkSeed: pkSeed, pkRoot: pkRoot, message: message)328        let (md, idxTree, idxLeaf) = splitDigest(p, digest)329330        var root = Bytes(repeating: 0, count: n)331        publicKey.withUnsafeBufferPointer { pk in332            signature.withUnsafeBufferPointer { sig in333                root.withUnsafeMutableBufferPointer { out in334                    let core = Core(p, pkSeed: pk.baseAddress!)335                    withUnsafeTemporaryAllocation(of: UInt8.self, capacity: n) { pkFors in336                        core.forsPkFromSig(sig.baseAddress! + n, md: md, idxTree: idxTree, idxLeaf: idxLeaf, pkFors.baseAddress!)337                        core.htRoot(pkFors.baseAddress!, sig.baseAddress! + n + p.forsSignatureSize,338                                    idxTree: idxTree, idxLeaf: idxLeaf, out.baseAddress!)339                    }340                }341            }342        }343        return ConstantTime.equal(root, pkRoot)344    }345346    // MARK: External interface (section 10)347348    private static func additionalRandomness(_ parameterSet: ParameterSet, _ randomization: Randomization) throws -> Bytes? {349        switch randomization {350        case .hedged: return SystemRandom.bytes(parameterSet.n)351        case .deterministic: return nil352        case .explicit(let bytes):353            guard bytes.count == parameterSet.n else { throw Error.invalidRandomnessLength }354            return bytes355        }356    }357358    /// M' of pure SLH-DSA: `toByte(0, 1) ‖ toByte(|ctx|, 1) ‖ ctx ‖ M`.359    static func pureMessage(_ message: Bytes, context: Bytes) -> Bytes {360        var out = Bytes()361        out.reserveCapacity(2 + context.count + message.count)362        out.append(0)363        out.append(UInt8(context.count))364        out.append(contentsOf: context)365        out.append(contentsOf: message)366        return out367    }368369    /// M' of HashSLH-DSA: `toByte(1, 1) ‖ toByte(|ctx|, 1) ‖ ctx ‖ OID ‖ PH(M)`.370    static func preHashMessage(_ message: Bytes, context: Bytes, preHash: PreHash) -> Bytes {371        var out = Bytes()372        out.append(1)373        out.append(UInt8(context.count))374        out.append(contentsOf: context)375        out.append(contentsOf: preHash.oid)376        out.append(contentsOf: preHash.digest(message))377        return out378    }379380    /// slh_sign (Algorithm 22): pure SLH-DSA signature of `message` under a context string of at most 255 bytes.381    public static func sign(382        _ parameterSet: ParameterSet, message: Bytes, context: Bytes = [], secretKey: Bytes,383        randomization: Randomization = .hedged384    ) throws -> Bytes {385        guard context.count <= 255 else { throw Error.contextTooLong }386        guard secretKey.count == parameterSet.secretKeySize else { throw Error.invalidSecretKeyLength }387        let addrnd = try additionalRandomness(parameterSet, randomization)388        return try signInternal(parameterSet, message: pureMessage(message, context: context), secretKey: secretKey, addrnd: addrnd)389    }390391    /// slh_verify (Algorithm 24). Returns false for a context longer than 255 bytes and for any malformed input.392    public static func verify(393        _ parameterSet: ParameterSet, message: Bytes, signature: Bytes, context: Bytes = [], publicKey: Bytes394    ) -> Bool {395        guard context.count <= 255 else { return false }396        guard publicKey.count == parameterSet.publicKeySize, signature.count == parameterSet.signatureSize else { return false }397        return verifyInternal(parameterSet, message: pureMessage(message, context: context), signature: signature, publicKey: publicKey)398    }399400    /// hash_slh_sign (Algorithm 23): HashSLH-DSA signature; the message is first hashed with `preHash`.401    public static func signPreHash(402        _ parameterSet: ParameterSet, message: Bytes, context: Bytes = [], preHash: PreHash, secretKey: Bytes,403        randomization: Randomization = .hedged404    ) throws -> Bytes {405        guard context.count <= 255 else { throw Error.contextTooLong }406        guard secretKey.count == parameterSet.secretKeySize else { throw Error.invalidSecretKeyLength }407        let addrnd = try additionalRandomness(parameterSet, randomization)408        return try signInternal(409            parameterSet, message: preHashMessage(message, context: context, preHash: preHash), secretKey: secretKey, addrnd: addrnd)410    }411412    /// hash_slh_verify (Algorithm 25).413    public static func verifyPreHash(414        _ parameterSet: ParameterSet, message: Bytes, signature: Bytes, context: Bytes = [], preHash: PreHash, publicKey: Bytes415    ) -> Bool {416        guard context.count <= 255 else { return false }417        guard publicKey.count == parameterSet.publicKeySize, signature.count == parameterSet.signatureSize else { return false }418        return verifyInternal(419            parameterSet, message: preHashMessage(message, context: context, preHash: preHash), signature: signature,420            publicKey: publicKey)421    }422}423
Files main
Menu

Theme