SPB Git

Repository Public

TweakableHash.swift 14.1 KB 323 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSLHDSA/TweakableHash.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#if _endian(big)47#error("QyvoraSLHDSA assumes a little-endian target")48#endif4950/// The tweakable hash functions F, H, T_l and PRF of SLH-DSA bound to one `PK.seed` (FIPS 205, section 11).51///52/// - SHAKE instantiation (11.1): `SHAKE256(PK.seed ‖ ADRS ‖ M, 8n)`.53/// - SHA-2 instantiation (11.2): `Trunc_n(SHA-x(PK.seed ‖ toByte(0, B − n) ‖ ADRSc ‖ M))` where F and PRF54///   always use SHA-256 (B = 64) and H / T_l use SHA-256 in category 1 and SHA-512 (B = 128) in55///   categories 3 and 5. The chaining value after the first padded block is computed once here.56///57/// PRF(PK.seed, SK.seed, ADRS) has exactly the shape of F with `M = SK.seed`: `PRF` is F plus the erasure58/// of its working memory.59/// Every routine reads its inputs completely before writing `out`, so `out` may alias an input.60struct TweakHash: Sendable {61    let n: Int62    /// n / 8: number of 64-bit lanes of an n-byte string.63    let nl: Int64    let shake: Bool65    /// True when H and T_l use SHA-512 (SHA-2 sets of categories 3 and 5).66    let wide: Bool67    /// PK.seed as little-endian lanes (SHAKE instantiation).68    let seed: SIMD4<UInt64>69    let mid256: SHA2Core.State25670    let mid512: SHA2Core.State5127172    init(_ p: SLHDSA.Params, pkSeed: UnsafePointer<UInt8>) {73        n = p.n74        nl = p.n / 875        shake = p.shake76        wide = !p.shake && p.n > 1677        var lanes = SIMD4<UInt64>(repeating: 0)78        for i in 0..<(p.n / 8) {79            lanes[i] = UInt64(littleEndian: UnsafeRawPointer(pkSeed).loadUnaligned(fromByteOffset: 8 * i, as: UInt64.self))80        }81        seed = lanes82        var s256 = SHA2Core.iv25683        var s512 = SHA2Core.iv51284        if !p.shake {85            let n = p.n86            withUnsafeTemporaryAllocation(byteCount: 128, alignment: 8) { raw in87                let buf = raw.baseAddress!88                for i in 0..<128 { buf.storeBytes(of: 0, toByteOffset: i, as: UInt8.self) }89                buf.copyMemory(from: pkSeed, byteCount: n)90                SHA2Core.k256.withUnsafeBufferPointer { SHA2Core.compress256(&s256, buf, $0.baseAddress!) }91                SHA2Core.k512.withUnsafeBufferPointer { SHA2Core.compress512(&s512, buf, $0.baseAddress!) }92            }93        }94        mid256 = s25695        mid512 = s51296    }9798    /// PRF(PK.seed, SK.seed, ADRS): F on the secret seed, with the working memory erased afterwards.99    /// The SHA-2 block holds SK.seed in clear and the Keccak state can be run backwards to it; both100    /// live in temporary stack memory that the next call would otherwise leave as it is.101    @inline(__always)102    func PRF(_ adrs: ADRS, _ skSeed: UnsafePointer<UInt8>, _ out: UnsafeMutablePointer<UInt8>) {103        F(adrs, skSeed, out, wipe: true)104    }105106    /// F(PK.seed, ADRS, M1) with an n-byte input. `wipe` (a compile-time constant at every call site)107    /// erases the working block before it is released: used by `PRF`, not by the public-data calls.108    @inline(__always)109    func F(_ adrs: ADRS, _ input: UnsafePointer<UInt8>, _ out: UnsafeMutablePointer<UInt8>, wipe: Bool = false) {110        let n = self.n111        if shake {112            let nl = self.nl113            withUnsafeTemporaryAllocation(of: UInt64.self, capacity: 25) { st in114                let s = st.baseAddress!115                for i in 0..<25 { s[i] = 0 }116                for i in 0..<nl { s[i] = seed[i] }117                adrs.writeLanes(to: s + nl)118                let r = UnsafeRawPointer(input)119                for i in 0..<nl {120                    s[nl &+ 4 &+ i] = UInt64(littleEndian: r.loadUnaligned(fromByteOffset: 8 &* i, as: UInt64.self))121                }122                s[2 &* nl &+ 4] ^= 0x1f123                s[16] ^= 0x8000_0000_0000_0000124                KeccakF1600.permute(s)125                let o = UnsafeMutableRawPointer(out)126                for i in 0..<nl { o.storeBytes(of: s[i].littleEndian, toByteOffset: 8 &* i, as: UInt64.self) }127                if wipe { _ = memset_s(s, 200, 0, 200) }128            }129        } else {130            // 22 + n + 1 + 8 <= 63: a single compression after the midstate131            var s = mid256132            withUnsafeTemporaryAllocation(byteCount: 64, alignment: 8) { raw in133                let buf = raw.baseAddress!134                let b = buf.assumingMemoryBound(to: UInt8.self)135                adrs.writeCompressed(to: b)136                (buf + 22).copyMemory(from: input, byteCount: n)137                b[22 &+ n] = 0x80138                for i in (23 &+ n)..<56 { b[i] = 0 }139                buf.storeBytes(of: (UInt64(64 &+ 22 &+ n) &* 8).bigEndian, toByteOffset: 56, as: UInt64.self)140                SHA2Core.k256.withUnsafeBufferPointer { SHA2Core.compress256(&s, buf, $0.baseAddress!, wipe: wipe) }141                if wipe { _ = memset_s(buf, 64, 0, 64) }142            }143            SHA2Core.store256(s, out, n)144        }145    }146147    /// H(PK.seed, ADRS, left ‖ right) with two n-byte inputs.148    @inline(__always)149    func H(_ adrs: ADRS, _ left: UnsafePointer<UInt8>, _ right: UnsafePointer<UInt8>, _ out: UnsafeMutablePointer<UInt8>) {150        let n = self.n151        if shake {152            let nl = self.nl153            withUnsafeTemporaryAllocation(of: UInt64.self, capacity: 25) { st in154                let s = st.baseAddress!155                for i in 0..<25 { s[i] = 0 }156                for i in 0..<nl { s[i] = seed[i] }157                adrs.writeLanes(to: s + nl)158                let l = UnsafeRawPointer(left), r = UnsafeRawPointer(right)159                for i in 0..<nl {160                    s[nl &+ 4 &+ i] = UInt64(littleEndian: l.loadUnaligned(fromByteOffset: 8 &* i, as: UInt64.self))161                    s[2 &* nl &+ 4 &+ i] = UInt64(littleEndian: r.loadUnaligned(fromByteOffset: 8 &* i, as: UInt64.self))162                }163                // 3·nl + 4 <= 16: still inside the first 136-byte block164                s[3 &* nl &+ 4] ^= 0x1f165                s[16] ^= 0x8000_0000_0000_0000166                KeccakF1600.permute(s)167                let o = UnsafeMutableRawPointer(out)168                for i in 0..<nl { o.storeBytes(of: s[i].littleEndian, toByteOffset: 8 &* i, as: UInt64.self) }169            }170        } else if wide {171            // 22 + 2n + 1 + 16 <= 103: a single SHA-512 compression after the midstate172            var s = mid512173            withUnsafeTemporaryAllocation(byteCount: 128, alignment: 8) { raw in174                let buf = raw.baseAddress!175                let b = buf.assumingMemoryBound(to: UInt8.self)176                adrs.writeCompressed(to: b)177                (buf + 22).copyMemory(from: left, byteCount: n)178                (buf + 22 + n).copyMemory(from: right, byteCount: n)179                let end = 22 &+ 2 &* n180                b[end] = 0x80181                for i in (end &+ 1)..<120 { b[i] = 0 }182                buf.storeBytes(of: (UInt64(128 &+ end) &* 8).bigEndian, toByteOffset: 120, as: UInt64.self)183                SHA2Core.k512.withUnsafeBufferPointer { SHA2Core.compress512(&s, buf, $0.baseAddress!) }184            }185            SHA2Core.store512(s, out, n)186        } else {187            // category 1: 22 + 32 + 1 + 8 = 63, a single SHA-256 compression188            var s = mid256189            withUnsafeTemporaryAllocation(byteCount: 64, alignment: 8) { raw in190                let buf = raw.baseAddress!191                let b = buf.assumingMemoryBound(to: UInt8.self)192                adrs.writeCompressed(to: b)193                (buf + 22).copyMemory(from: left, byteCount: n)194                (buf + 22 + n).copyMemory(from: right, byteCount: n)195                let end = 22 &+ 2 &* n196                b[end] = 0x80197                for i in (end &+ 1)..<56 { b[i] = 0 }198                buf.storeBytes(of: (UInt64(64 &+ end) &* 8).bigEndian, toByteOffset: 56, as: UInt64.self)199                SHA2Core.k256.withUnsafeBufferPointer { SHA2Core.compress256(&s, buf, $0.baseAddress!) }200            }201            SHA2Core.store256(s, out, n)202        }203    }204205    /// T_l(PK.seed, ADRS, M) for an input of `count` bytes (a multiple of n).206    func T(_ adrs: ADRS, _ input: UnsafePointer<UInt8>, _ count: Int, _ out: UnsafeMutablePointer<UInt8>) {207        let n = self.n208        precondition(count % 8 == 0)209        if shake {210            let nl = self.nl211            withUnsafeTemporaryAllocation(of: UInt64.self, capacity: 25) { st in212                let s = st.baseAddress!213                for i in 0..<25 { s[i] = 0 }214                for i in 0..<nl { s[i] = seed[i] }215                adrs.writeLanes(to: s + nl)216                var pos = nl + 4217                let r = UnsafeRawPointer(input)218                var off = 0219                while off < count {220                    if pos == 17 {221                        KeccakF1600.permute(s)222                        pos = 0223                    }224                    s[pos] ^= UInt64(littleEndian: r.loadUnaligned(fromByteOffset: off, as: UInt64.self))225                    pos += 1226                    off += 8227                }228                if pos == 17 {229                    KeccakF1600.permute(s)230                    pos = 0231                }232                s[pos] ^= 0x1f233                s[16] ^= 0x8000_0000_0000_0000234                KeccakF1600.permute(s)235                let o = UnsafeMutableRawPointer(out)236                for i in 0..<nl { o.storeBytes(of: s[i].littleEndian, toByteOffset: 8 &* i, as: UInt64.self) }237            }238        } else {239            withUnsafeTemporaryAllocation(of: UInt8.self, capacity: 22) { head in240                let h = head.baseAddress!241                adrs.writeCompressed(to: h)242                if wide {243                    SHA2Core.finish512(state: mid512, absorbed: 128, head: h, headCount: 22, msg: input, count: count,244                                       out: out, outLen: n)245                } else {246                    SHA2Core.finish256(state: mid256, absorbed: 64, head: h, headCount: 22, msg: input, count: count,247                                       out: out, outLen: n)248                }249            }250        }251    }252}253254/// Message-level functions H_msg and PRF_msg (FIPS 205, sections 11.1 and 11.2). These run once per255/// signature over the whole message, so they use the incremental hashes of the engine foundations.256enum MessageHash {257    /// MGF1 (RFC 8017, appendix B.2.1) over a hash function of the engine.258    static func mgf1<Hash: HashFunction>(_: Hash.Type, seed: Bytes, length: Int) -> Bytes {259        var out = Bytes()260        out.reserveCapacity(length + Hash.digestSize)261        var counter: UInt32 = 0262        while out.count < length {263            var h = Hash()264            h.update(seed)265            h.update(Endian.be32(counter))266            out.append(contentsOf: h.finalize())267            counter &+= 1268        }269        out.removeLast(out.count - length)270        return out271    }272273    private static func sha2HMsg<Hash: HashFunction>(_: Hash.Type, r: Bytes, pkSeed: Bytes, pkRoot: Bytes, message: Bytes, m: Int) -> Bytes {274        var h = Hash()275        h.update(r)276        h.update(pkSeed)277        h.update(pkRoot)278        h.update(message)279        let inner = h.finalize()280        return mgf1(Hash.self, seed: r + pkSeed + inner, length: m)281    }282283    private static func sha2PRFMsg<Hash: HashFunction>(_: Hash.Type, skPrf: Bytes, optRand: Bytes, message: Bytes, n: Int) -> Bytes {284        var mac = HMAC<Hash>(key: skPrf)285        mac.update(optRand)286        mac.update(message)287        return Bytes(mac.finalize().prefix(n))288    }289290    /// H_msg(R, PK.seed, PK.root, M): the m-byte message digest.291    static func hMsg(_ p: SLHDSA.Params, r: Bytes, pkSeed: Bytes, pkRoot: Bytes, message: Bytes) -> Bytes {292        if p.shake {293            var x = SHAKE(256)294            x.absorb(r)295            x.absorb(pkSeed)296            x.absorb(pkRoot)297            x.absorb(message)298            return x.squeeze(p.m)299        }300        if p.n == 16 {301            return sha2HMsg(SHA256.self, r: r, pkSeed: pkSeed, pkRoot: pkRoot, message: message, m: p.m)302        }303        return sha2HMsg(SHA512.self, r: r, pkSeed: pkSeed, pkRoot: pkRoot, message: message, m: p.m)304    }305306    /// PRF_msg(SK.prf, opt_rand, M): the n-byte signature randomizer R.307    static func prfMsg(_ p: SLHDSA.Params, skPrf: Bytes, optRand: Bytes, message: Bytes) -> Bytes {308        if p.shake {309            var x = SHAKE(256)310            x.absorb(skPrf)311            x.absorb(optRand)312            x.absorb(message)313            let out = x.squeeze(p.n)314            x.wipe()315            return out316        }317        if p.n == 16 {318            return sha2PRFMsg(SHA256.self, skPrf: skPrf, optRand: optRand, message: message, n: p.n)319        }320        return sha2PRFMsg(SHA512.self, skPrf: skPrf, optRand: optRand, message: message, n: p.n)321    }322}323
Files main
Menu

Theme