Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraSLHDSA/SHA2Core.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 QyvoraMath4344/// Allocation-free SHA-2 compression core private to SLH-DSA.45///46/// The public `SHA256` / `SHA512` of QyvoraSymmetric keep their state in heap arrays, which is fine for47/// message hashing but far too slow for the millions of short tweakable-hash calls of one SLH-DSA48/// signature. This core keeps the chaining value in a SIMD register-sized value so that the midstate49/// reached after absorbing the padded `PK.seed` block (FIPS 205, section 11.2) can be copied for free.50/// It also provides the truncated SHA-2 variants needed by HashSLH-DSA pre-hashing.51enum SHA2Core {52 typealias State256 = SIMD8<UInt32>53 typealias State512 = SIMD8<UInt64>5455 static let k512: [UInt64] = [56 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,57 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,58 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,59 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,60 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,61 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,62 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,63 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,64 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,65 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,66 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,67 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,68 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,69 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,70 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,71 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,72 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,73 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,74 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,75 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817,76 ]7778 /// The SHA-256 constants are the upper halves of the first 64 SHA-512 constants.79 static let k256: [UInt32] = k512.prefix(64).map { UInt32(truncatingIfNeeded: $0 >> 32) }8081 // Initial hash values (FIPS 180-4, section 5.3).82 static let iv224 = State256(0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4)83 static let iv256 = State256(0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19)84 static let iv384 = State512(85 0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939,86 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4)87 static let iv512 = State512(88 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,89 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179)90 static let iv512_224 = State512(91 0x8c3d37c819544da2, 0x73e1996689dcd4d6, 0x1dfab7ae32ff9c82, 0x679dd514582f9fcf,92 0x0f6d2b697bd44da8, 0x77e36f7304c48942, 0x3f9d85a86a1d36c8, 0x1112e6ad91d692a1)93 static let iv512_256 = State512(94 0x22312194fc2bf72c, 0x9f555fa3c84c64c2, 0x2393b86b6f53b151, 0x963877195940eabd,95 0x96283ee2a88effe3, 0xbe5e1e2553863992, 0x2b0199fc2c85b8aa, 0x0eb72ddc81c52ca2)9697 @inline(__always) private static func rotr(_ x: UInt32, _ n: UInt32) -> UInt32 { (x >> n) | (x << (32 &- n)) }98 @inline(__always) private static func rotr(_ x: UInt64, _ n: UInt64) -> UInt64 { (x >> n) | (x << (64 &- n)) }99100 /// One SHA-256 compression of the 64-byte `block` into `s`. `k` points to the 64 round constants.101 /// `wipe` (a constant at every call site) erases the message schedule afterwards.102 @inline(__always)103 static func compress256(_ s: inout State256, _ block: UnsafeRawPointer, _ k: UnsafePointer<UInt32>, wipe: Bool = false) {104 withUnsafeTemporaryAllocation(of: UInt32.self, capacity: 64) { w in105 for i in 0..<16 {106 w[i] = UInt32(bigEndian: block.loadUnaligned(fromByteOffset: 4 &* i, as: UInt32.self))107 }108 for i in 16..<64 {109 let x = w[i &- 15], y = w[i &- 2]110 let s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3)111 let s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >> 10)112 w[i] = w[i &- 16] &+ s0 &+ w[i &- 7] &+ s1113 }114 var a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]115 for i in 0..<64 {116 let s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)117 let ch = (e & f) ^ (~e & g)118 let t1 = h &+ s1 &+ ch &+ k[i] &+ w[i]119 let s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)120 let maj = (a & b) ^ (a & c) ^ (b & c)121 let t2 = s0 &+ maj122 h = g; g = f; f = e; e = d &+ t1123 d = c; c = b; b = a; a = t1 &+ t2124 }125 s &+= State256(a, b, c, d, e, f, g, h)126 // the message schedule repeats the block: erased when the block is secret (PRF on SK.seed)127 if wipe { _ = memset_s(w.baseAddress!, 256, 0, 256) }128 }129 }130131 /// One SHA-512 compression of the 128-byte `block` into `s`. `k` points to the 80 round constants.132 @inline(__always)133 static func compress512(_ s: inout State512, _ block: UnsafeRawPointer, _ k: UnsafePointer<UInt64>) {134 withUnsafeTemporaryAllocation(of: UInt64.self, capacity: 80) { w in135 for i in 0..<16 {136 w[i] = UInt64(bigEndian: block.loadUnaligned(fromByteOffset: 8 &* i, as: UInt64.self))137 }138 for i in 16..<80 {139 let x = w[i &- 15], y = w[i &- 2]140 let s0 = rotr(x, 1) ^ rotr(x, 8) ^ (x >> 7)141 let s1 = rotr(y, 19) ^ rotr(y, 61) ^ (y >> 6)142 w[i] = w[i &- 16] &+ s0 &+ w[i &- 7] &+ s1143 }144 var a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]145 for i in 0..<80 {146 let s1 = rotr(e, 14) ^ rotr(e, 18) ^ rotr(e, 41)147 let ch = (e & f) ^ (~e & g)148 let t1 = h &+ s1 &+ ch &+ k[i] &+ w[i]149 let s0 = rotr(a, 28) ^ rotr(a, 34) ^ rotr(a, 39)150 let maj = (a & b) ^ (a & c) ^ (b & c)151 let t2 = s0 &+ maj152 h = g; g = f; f = e; e = d &+ t1153 d = c; c = b; b = a; a = t1 &+ t2154 }155 s &+= State512(a, b, c, d, e, f, g, h)156 }157 }158159 @inline(__always)160 static func store256(_ s: State256, _ out: UnsafeMutablePointer<UInt8>, _ count: Int) {161 for i in 0..<count {162 out[i] = UInt8(truncatingIfNeeded: s[i >> 2] >> UInt32(24 &- 8 &* (i & 3)))163 }164 }165166 @inline(__always)167 static func store512(_ s: State512, _ out: UnsafeMutablePointer<UInt8>, _ count: Int) {168 for i in 0..<count {169 out[i] = UInt8(truncatingIfNeeded: s[i >> 3] >> UInt64(56 &- 8 &* (i & 7)))170 }171 }172173 /// Completes a SHA-256 family computation: `state` is the chaining value reached after `absorbed`174 /// bytes (a multiple of 64); the remaining input is `head ‖ msg`. Writes the first `outLen` digest bytes.175 static func finish256(176 state: State256, absorbed: Int,177 head: UnsafePointer<UInt8>?, headCount: Int,178 msg: UnsafePointer<UInt8>?, count: Int,179 out: UnsafeMutablePointer<UInt8>, outLen: Int180 ) {181 var s = state182 k256.withUnsafeBufferPointer { kb in183 let k = kb.baseAddress!184 withUnsafeTemporaryAllocation(byteCount: 128, alignment: 8) { raw in185 let buf = raw.baseAddress!186 var fill = 0187 if headCount > 0, let head {188 precondition(headCount < 64)189 buf.copyMemory(from: head, byteCount: headCount)190 fill = headCount191 }192 var off = 0193 if count > 0, let msg {194 if fill > 0 {195 let take = min(64 - fill, count)196 (buf + fill).copyMemory(from: msg, byteCount: take)197 fill += take198 off = take199 if fill == 64 {200 compress256(&s, buf, k)201 fill = 0202 }203 }204 while count - off >= 64 {205 compress256(&s, msg + off, k)206 off += 64207 }208 if off < count {209 (buf + fill).copyMemory(from: msg + off, byteCount: count - off)210 fill += count - off211 }212 }213 buf.storeBytes(of: 0x80, toByteOffset: fill, as: UInt8.self)214 let total = fill < 56 ? 64 : 128215 for i in (fill + 1)..<(total - 8) { buf.storeBytes(of: 0, toByteOffset: i, as: UInt8.self) }216 let bits = UInt64(absorbed + headCount + count) &* 8217 buf.storeBytes(of: bits.bigEndian, toByteOffset: total - 8, as: UInt64.self)218 compress256(&s, buf, k)219 if total == 128 { compress256(&s, buf + 64, k) }220 }221 }222 store256(s, out, outLen)223 }224225 /// SHA-512 family counterpart of `finish256` (`absorbed` is a multiple of 128).226 static func finish512(227 state: State512, absorbed: Int,228 head: UnsafePointer<UInt8>?, headCount: Int,229 msg: UnsafePointer<UInt8>?, count: Int,230 out: UnsafeMutablePointer<UInt8>, outLen: Int231 ) {232 var s = state233 k512.withUnsafeBufferPointer { kb in234 let k = kb.baseAddress!235 withUnsafeTemporaryAllocation(byteCount: 256, alignment: 8) { raw in236 let buf = raw.baseAddress!237 var fill = 0238 if headCount > 0, let head {239 precondition(headCount < 128)240 buf.copyMemory(from: head, byteCount: headCount)241 fill = headCount242 }243 var off = 0244 if count > 0, let msg {245 if fill > 0 {246 let take = min(128 - fill, count)247 (buf + fill).copyMemory(from: msg, byteCount: take)248 fill += take249 off = take250 if fill == 128 {251 compress512(&s, buf, k)252 fill = 0253 }254 }255 while count - off >= 128 {256 compress512(&s, msg + off, k)257 off += 128258 }259 if off < count {260 (buf + fill).copyMemory(from: msg + off, byteCount: count - off)261 fill += count - off262 }263 }264 buf.storeBytes(of: 0x80, toByteOffset: fill, as: UInt8.self)265 let total = fill < 112 ? 128 : 256266 for i in (fill + 1)..<(total - 8) { buf.storeBytes(of: 0, toByteOffset: i, as: UInt8.self) }267 // 128-bit length field: the upper 64 bits stay zero (inputs are far below 2^61 bytes)268 let bits = UInt64(absorbed + headCount + count) &* 8269 buf.storeBytes(of: bits.bigEndian, toByteOffset: total - 8, as: UInt64.self)270 compress512(&s, buf, k)271 if total == 256 { compress512(&s, buf + 128, k) }272 }273 }274 store512(s, out, outLen)275 }276277 /// One-shot digest of the SHA-256 family (`iv224` → SHA-224, `iv256` → SHA-256).278 static func digest256(iv: State256, _ data: Bytes, outLen: Int) -> Bytes {279 var out = Bytes(repeating: 0, count: outLen)280 data.withUnsafeBufferPointer { d in281 out.withUnsafeMutableBufferPointer { o in282 finish256(state: iv, absorbed: 0, head: nil, headCount: 0, msg: d.baseAddress, count: d.count,283 out: o.baseAddress!, outLen: outLen)284 }285 }286 return out287 }288289 /// One-shot digest of the SHA-512 family (SHA-384, SHA-512, SHA-512/224, SHA-512/256).290 static func digest512(iv: State512, _ data: Bytes, outLen: Int) -> Bytes {291 var out = Bytes(repeating: 0, count: outLen)292 data.withUnsafeBufferPointer { d in293 out.withUnsafeMutableBufferPointer { o in294 finish512(state: iv, absorbed: 0, head: nil, headCount: 0, msg: d.baseAddress, count: d.count,295 out: o.baseAddress!, outLen: outLen)296 }297 }298 return out299 }300}301