SPB Git

Repository Public

SHA2.swift 12.7 KB 297 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSymmetric/SHA2.swift8// Module           : Qyvora Symmetric9// 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 QyvoraMath4243/// SHA-2 round constants (FIPS 180-4, sections 4.2.2 and 4.2.3).44/// The SHA-256 constants are the upper 32 bits of the first 64 SHA-512 constants45/// (both are fractional parts of the cube roots of the same primes).46enum SHA2Constants {47    static let k512: [UInt64] = [48        0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,49        0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,50        0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,51        0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,52        0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,53        0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,54        0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,55        0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,56        0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,57        0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,58        0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,59        0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,60        0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,61        0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,62        0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,63        0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,64        0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,65        0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,66        0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,67        0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817,68    ]6970    static let k256: [UInt32] = k512.prefix(64).map { UInt32(truncatingIfNeeded: $0 >> 32) }71}7273/// SHA-256 (FIPS 180-4).74public struct SHA256: HashFunction {75    public static let blockSize = 6476    public static let digestSize = 327778    var h: [UInt32] = [79        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,80    ]81    var buffer = Bytes()82    var length: UInt64 = 08384    public init() { buffer.reserveCapacity(64) }8586    public mutating func update(_ data: Bytes) {87        length &+= UInt64(data.count)88        var offset = 089        if !buffer.isEmpty {90            let take = min(64 - buffer.count, data.count)91            buffer.append(contentsOf: data[0..<take])92            offset = take93            if buffer.count == 64 {94                buffer.withUnsafeBufferPointer { compress($0.baseAddress!) }95                SecureMemory.zero(&buffer)96                buffer.removeAll(keepingCapacity: true)97            }98        }99        data.withUnsafeBufferPointer { d in100            while data.count - offset >= 64 {101                compress(d.baseAddress! + offset)102                offset += 64103            }104        }105        if offset < data.count { buffer.append(contentsOf: data[offset...]) }106    }107108    public mutating func finalize() -> Bytes {109        let bitLength = length &* 8110        // capacity reserved up front: the tail never reallocates, so no partial copy is left behind111        var tail = Bytes()112        tail.reserveCapacity(128)113        tail.append(contentsOf: buffer)114        tail.append(0x80)115        while tail.count % 64 != 56 { tail.append(0) }116        tail.append(contentsOf: Endian.be64(bitLength))117        tail.withUnsafeBufferPointer { t in118            var o = 0119            while o < t.count {120                compress(t.baseAddress! + o)121                o += 64122            }123        }124        // The tail and the pending buffer hold the end of the message: key material when the hash runs125        // inside HMAC, HKDF, PBKDF2 or RFC 6979.126        SecureMemory.zero(&tail)127        SecureMemory.zero(&buffer)128        var out = Bytes(repeating: 0, count: 32)129        for i in 0..<32 { out[i] = UInt8(truncatingIfNeeded: h[i >> 2] >> UInt32(24 - 8 * (i & 3))) }130        // The chaining state now equals the digest. When the digest is a secret (an HMAC output used as a key, an131        // RFC 6979 value, a derived child key) the caller erases its copy: this one must not outlive it (QYV-CRY-005).132        SecureMemory.zero(&h)133        return out134    }135136    @inline(__always) private static func rotr(_ x: UInt32, _ n: UInt32) -> UInt32 { (x >> n) | (x << (32 &- n)) }137138    private mutating func compress(_ block: UnsafePointer<UInt8>) {139        withUnsafeTemporaryAllocation(of: UInt32.self, capacity: 64) { w in140            for i in 0..<16 { w[i] = Endian.loadBE32(block + 4 * i) }141            for i in 16..<64 {142                let s0 = Self.rotr(w[i - 15], 7) ^ Self.rotr(w[i - 15], 18) ^ (w[i - 15] >> 3)143                let s1 = Self.rotr(w[i - 2], 17) ^ Self.rotr(w[i - 2], 19) ^ (w[i - 2] >> 10)144                w[i] = w[i - 16] &+ s0 &+ w[i - 7] &+ s1145            }146            var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]147            SHA2Constants.k256.withUnsafeBufferPointer { k in148                for i in 0..<64 {149                    let s1 = Self.rotr(e, 6) ^ Self.rotr(e, 11) ^ Self.rotr(e, 25)150                    let ch = (e & f) ^ (~e & g)151                    let t1 = hh &+ s1 &+ ch &+ k[i] &+ w[i]152                    let s0 = Self.rotr(a, 2) ^ Self.rotr(a, 13) ^ Self.rotr(a, 22)153                    let maj = (a & b) ^ (a & c) ^ (b & c)154                    let t2 = s0 &+ maj155                    hh = g; g = f; f = e; e = d &+ t1156                    d = c; c = b; b = a; a = t1 &+ t2157                }158            }159            h[0] &+= a; h[1] &+= b; h[2] &+= c; h[3] &+= d160            h[4] &+= e; h[5] &+= f; h[6] &+= g; h[7] &+= hh161        }162    }163164    /// SHA-256(SHA-256(data)), the Bitcoin double hash.165    public static func double(_ data: Bytes) -> Bytes { hash(hash(data)) }166}167168/// SHA-512 (FIPS 180-4).169public struct SHA512: HashFunction {170    public static let blockSize = 128171    public static let digestSize = 64172173    var h: [UInt64] = [174        0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,175        0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,176    ]177    var buffer = Bytes()178    var length: UInt64 = 0179180    public init() { buffer.reserveCapacity(128) }181182    public mutating func update(_ data: Bytes) {183        length &+= UInt64(data.count)184        var offset = 0185        if !buffer.isEmpty {186            let take = min(128 - buffer.count, data.count)187            buffer.append(contentsOf: data[0..<take])188            offset = take189            if buffer.count == 128 {190                buffer.withUnsafeBufferPointer { compress($0.baseAddress!) }191                SecureMemory.zero(&buffer)192                buffer.removeAll(keepingCapacity: true)193            }194        }195        data.withUnsafeBufferPointer { d in196            while data.count - offset >= 128 {197                compress(d.baseAddress! + offset)198                offset += 128199            }200        }201        if offset < data.count { buffer.append(contentsOf: data[offset...]) }202    }203204    public mutating func finalize() -> Bytes {205        let bitLength = length &* 8206        var tail = Bytes()207        tail.reserveCapacity(256)208        tail.append(contentsOf: buffer)209        tail.append(0x80)210        while tail.count % 128 != 112 { tail.append(0) }211        // 128-bit length; messages longer than 2^61 bytes are out of reach212        tail.append(contentsOf: Endian.be64(length >> 61))213        tail.append(contentsOf: Endian.be64(bitLength))214        tail.withUnsafeBufferPointer { t in215            var o = 0216            while o < t.count {217                compress(t.baseAddress! + o)218                o += 128219            }220        }221        SecureMemory.zero(&tail)222        SecureMemory.zero(&buffer)223        var out = Bytes(repeating: 0, count: 64)224        for i in 0..<64 { out[i] = UInt8(truncatingIfNeeded: h[i >> 3] >> UInt64(56 - 8 * (i & 7))) }225        // The chaining state now equals the digest: the expanded Ed25519 key SHA-512(seed), the signing nonce226        // SHA-512(prefix ‖ message), a SLIP-0010 or BIP-32 child key. The caller erases its copy of the digest;227        // this one must not outlive it (QYV-CRY-005). `finalize` ends the computation: the instance is not reusable.228        SecureMemory.zero(&h)229        return out230    }231232    @inline(__always) private static func rotr(_ x: UInt64, _ n: UInt64) -> UInt64 { (x >> n) | (x << (64 &- n)) }233234    private mutating func compress(_ block: UnsafePointer<UInt8>) {235        withUnsafeTemporaryAllocation(of: UInt64.self, capacity: 80) { w in236            for i in 0..<16 { w[i] = Endian.loadBE64(block + 8 * i) }237            for i in 16..<80 {238                let s0 = Self.rotr(w[i - 15], 1) ^ Self.rotr(w[i - 15], 8) ^ (w[i - 15] >> 7)239                let s1 = Self.rotr(w[i - 2], 19) ^ Self.rotr(w[i - 2], 61) ^ (w[i - 2] >> 6)240                w[i] = w[i - 16] &+ s0 &+ w[i - 7] &+ s1241            }242            var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]243            SHA2Constants.k512.withUnsafeBufferPointer { k in244                for i in 0..<80 {245                    let s1 = Self.rotr(e, 14) ^ Self.rotr(e, 18) ^ Self.rotr(e, 41)246                    let ch = (e & f) ^ (~e & g)247                    let t1 = hh &+ s1 &+ ch &+ k[i] &+ w[i]248                    let s0 = Self.rotr(a, 28) ^ Self.rotr(a, 34) ^ Self.rotr(a, 39)249                    let maj = (a & b) ^ (a & c) ^ (b & c)250                    let t2 = s0 &+ maj251                    hh = g; g = f; f = e; e = d &+ t1252                    d = c; c = b; b = a; a = t1 &+ t2253                }254            }255            h[0] &+= a; h[1] &+= b; h[2] &+= c; h[3] &+= d256            h[4] &+= e; h[5] &+= f; h[6] &+= g; h[7] &+= hh257        }258    }259}260261/// HMAC (FIPS 198-1 / RFC 2104) over any `HashFunction` of the engine.262public struct HMAC<H: HashFunction>: Sendable {263    var inner: H264    var outerKey: Bytes265266    public init(key: Bytes) {267        var k = key.count > H.blockSize ? H.hash(key) : key268        k.append(contentsOf: Bytes(repeating: 0, count: H.blockSize - k.count))269        inner = H()270        var innerKey = k.map { $0 ^ 0x36 }271        inner.update(innerKey)272        outerKey = k.map { $0 ^ 0x5c }273        SecureMemory.zero(&innerKey)274        SecureMemory.zero(&k)275    }276277    public mutating func update(_ data: Bytes) { inner.update(data) }278279    public mutating func finalize() -> Bytes {280        var innerDigest = inner.finalize()281        var outer = H()282        outer.update(outerKey)283        outer.update(innerDigest)284        SecureMemory.zero(&outerKey)285        SecureMemory.zero(&innerDigest)286        return outer.finalize()287    }288289    public static func authenticate(key: Bytes, message: Bytes) -> Bytes {290        let dit = DataIndependentTiming.enable()291        defer { DataIndependentTiming.restore(dit) }292        var m = HMAC<H>(key: key)293        m.update(message)294        return m.finalize()295    }296}297
Files main
Menu

Theme