SPB Git

Repository Public

BLAKE2b.swift 9.4 KB 224 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSymmetric/BLAKE2b.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 Foundation42import QyvoraMath4344/// BLAKE2b (RFC 7693): digests of 1 to 64 bytes, optional key of up to 64 bytes (keyed mode is a MAC),45/// optional 16-byte salt and personalization (BLAKE2 specification, section 2.5).46public struct BLAKE2b: Sendable {47    public static let blockSize = 12848    public static let maxDigestSize = 6449    public static let maxKeySize = 645051    /// Output size in bytes, fixed at creation (it is part of the parameter block).52    public let digestSize: Int5354    var h: [UInt64]55    var t0: UInt64 = 056    var t1: UInt64 = 057    var buffer = Bytes(repeating: 0, count: 128)58    var buffered = 05960    static let iv: [UInt64] = [61        0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,62        0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,63    ]6465    static let sigma: [UInt8] = [66        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,67        14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,68        11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,69        7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,70        9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,71        2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,72        12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,73        13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,74        6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,75        10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,76        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,77        14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,78    ]7980    /// - Parameters:81    ///   - digestSize: 1 to 64 bytes.82    ///   - key: empty (plain hash) or up to 64 bytes (keyed hash).83    ///   - salt: empty or up to 16 bytes (zero-padded).84    ///   - personalization: empty or up to 16 bytes (zero-padded).85    /// Out-of-range sizes are programming errors (precondition).86    public init(digestSize: Int = 64, key: Bytes = [], salt: Bytes = [], personalization: Bytes = []) {87        precondition(digestSize >= 1 && digestSize <= 64, "BLAKE2b digest size must be 1...64")88        precondition(key.count <= 64, "BLAKE2b key must be at most 64 bytes")89        precondition(salt.count <= 16 && personalization.count <= 16, "BLAKE2b salt and personalization are at most 16 bytes")90        self.digestSize = digestSize91        h = Self.iv92        h[0] ^= 0x0101_0000 ^ (UInt64(key.count) << 8) ^ UInt64(digestSize)93        if !salt.isEmpty {94            let s = salt + Bytes(repeating: 0, count: 16 - salt.count)95            s.withUnsafeBufferPointer { p in96                h[4] ^= Endian.loadLE64(p.baseAddress!)97                h[5] ^= Endian.loadLE64(p.baseAddress! + 8)98            }99        }100        if !personalization.isEmpty {101            let s = personalization + Bytes(repeating: 0, count: 16 - personalization.count)102            s.withUnsafeBufferPointer { p in103                h[6] ^= Endian.loadLE64(p.baseAddress!)104                h[7] ^= Endian.loadLE64(p.baseAddress! + 8)105            }106        }107        if !key.isEmpty {108            var block = key + Bytes(repeating: 0, count: 128 - key.count)109            update(block)110            SecureMemory.zero(&block)111        }112    }113114    public mutating func update(_ data: Bytes) {115        var offset = 0116        let n = data.count117        guard n > 0 else { return }118        // The buffer is only compressed when more input follows: the last block needs the final flag.119        if buffered > 0 {120            let take = min(128 - buffered, n)121            for i in 0..<take { buffer[buffered + i] = data[i] }122            buffered += take123            offset = take124            if offset == n { return }125            addLength(128)126            buffer.withUnsafeBufferPointer { compress($0.baseAddress!, last: false) }127            buffered = 0128        }129        data.withUnsafeBufferPointer { d in130            while n - offset > 128 {131                addLength(128)132                compress(d.baseAddress! + offset, last: false)133                offset += 128134            }135        }136        for i in offset..<n { buffer[i - offset] = data[i] }137        buffered = n - offset138    }139140    /// Returns the digest and erases the state. The instance must not be used afterwards.141    public mutating func finalize() -> Bytes {142        addLength(UInt64(buffered))143        for i in buffered..<128 { buffer[i] = 0 }144        buffer.withUnsafeBufferPointer { compress($0.baseAddress!, last: true) }145        var out = Bytes(repeating: 0, count: digestSize)146        for i in 0..<digestSize { out[i] = UInt8(truncatingIfNeeded: h[i >> 3] >> UInt64(8 * (i & 7))) }147        SecureMemory.zero(&buffer)148        SecureMemory.zero(&h)149        buffered = 0150        return out151    }152153    /// One-shot BLAKE2b.154    public static func hash(_ data: Bytes, digestSize: Int = 64, key: Bytes = []) -> Bytes {155        var b = BLAKE2b(digestSize: digestSize, key: key)156        b.update(data)157        return b.finalize()158    }159160    @inline(__always) private mutating func addLength(_ n: UInt64) {161        let (sum, overflow) = t0.addingReportingOverflow(n)162        t0 = sum163        if overflow { t1 &+= 1 }164    }165166    @inline(__always) private static func rotr(_ x: UInt64, _ n: UInt64) -> UInt64 { (x >> n) | (x << (64 &- n)) }167168    private mutating func compress(_ block: UnsafePointer<UInt8>, last: Bool) {169        let t0 = self.t0, t1 = self.t1170        h.withUnsafeMutableBufferPointer { h in171            withUnsafeTemporaryAllocation(of: UInt64.self, capacity: 32) { w in172                // w[0..<16] = message words, w[16..<32] = working vector173                let m = w.baseAddress!, v = w.baseAddress! + 16174                for i in 0..<16 { m[i] = Endian.loadLE64(block + 8 * i) }175                for i in 0..<8 {176                    v[i] = h[i]177                    v[i + 8] = Self.iv[i]178                }179                v[12] ^= t0180                v[13] ^= t1181                if last { v[14] = ~v[14] }182183                @inline(__always) func g(_ a: Int, _ b: Int, _ c: Int, _ d: Int, _ x: UInt64, _ y: UInt64) {184                    v[a] = v[a] &+ v[b] &+ x185                    v[d] = Self.rotr(v[d] ^ v[a], 32)186                    v[c] = v[c] &+ v[d]187                    v[b] = Self.rotr(v[b] ^ v[c], 24)188                    v[a] = v[a] &+ v[b] &+ y189                    v[d] = Self.rotr(v[d] ^ v[a], 16)190                    v[c] = v[c] &+ v[d]191                    v[b] = Self.rotr(v[b] ^ v[c], 63)192                }193194                Self.sigma.withUnsafeBufferPointer { sigma in195                    for round in 0..<12 {196                        let s = sigma.baseAddress! + 16 * round197                        g(0, 4, 8, 12, m[Int(s[0])], m[Int(s[1])])198                        g(1, 5, 9, 13, m[Int(s[2])], m[Int(s[3])])199                        g(2, 6, 10, 14, m[Int(s[4])], m[Int(s[5])])200                        g(3, 7, 11, 15, m[Int(s[6])], m[Int(s[7])])201                        g(0, 5, 10, 15, m[Int(s[8])], m[Int(s[9])])202                        g(1, 6, 11, 12, m[Int(s[10])], m[Int(s[11])])203                        g(2, 7, 8, 13, m[Int(s[12])], m[Int(s[13])])204                        g(3, 4, 9, 14, m[Int(s[14])], m[Int(s[15])])205                    }206                }207                for i in 0..<8 { h[i] ^= v[i] ^ v[i + 8] }208                // message words and working vector: erased with memset_s, which the optimizer may not remove209                _ = memset_s(w.baseAddress!, 32 * 8, 0, 32 * 8)210            }211        }212    }213}214215/// BLAKE2b with a 64-byte digest as a `HashFunction` (generic callers: HMAC, HKDF…).216public struct BLAKE2b512: HashFunction {217    public static let blockSize = 128218    public static let digestSize = 64219    var core = BLAKE2b(digestSize: 64)220    public init() {}221    public mutating func update(_ data: Bytes) { core.update(data) }222    public mutating func finalize() -> Bytes { core.finalize() }223}224
Files main
Menu

Theme