SPB Git

Repository Public

Keccak.swift 13.1 KB 312 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraKeccak/Keccak.swift8// Module           : Qyvora Keccak9// 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/// Keccak-f[1600] permutation (FIPS 202, section 3.3), 24 rounds over 25 lanes of 64 bits.44public enum KeccakF1600 {45    @usableFromInline static let roundConstants: [UInt64] = [46        0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000,47        0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,48        0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a,49        0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003,50        0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a,51        0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,52    ]5354    @inline(__always) static func rotl(_ x: UInt64, _ n: UInt64) -> UInt64 {55        (x << n) | (x >> (64 &- n))56    }5758    /// Applies the permutation in place. `a` points to 25 lanes, lane (x, y) at index x + 5y.59    public static func permute(_ a: UnsafeMutablePointer<UInt64>) {60        roundConstants.withUnsafeBufferPointer { rc in61            var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a04 = a[4]62            var a05 = a[5], a06 = a[6], a07 = a[7], a08 = a[8], a09 = a[9]63            var a10 = a[10], a11 = a[11], a12 = a[12], a13 = a[13], a14 = a[14]64            var a15 = a[15], a16 = a[16], a17 = a[17], a18 = a[18], a19 = a[19]65            var a20 = a[20], a21 = a[21], a22 = a[22], a23 = a[23], a24 = a[24]6667            for round in 0..<24 {68                // θ69                let c0 = a00 ^ a05 ^ a10 ^ a15 ^ a2070                let c1 = a01 ^ a06 ^ a11 ^ a16 ^ a2171                let c2 = a02 ^ a07 ^ a12 ^ a17 ^ a2272                let c3 = a03 ^ a08 ^ a13 ^ a18 ^ a2373                let c4 = a04 ^ a09 ^ a14 ^ a19 ^ a2474                let d0 = c4 ^ rotl(c1, 1)75                let d1 = c0 ^ rotl(c2, 1)76                let d2 = c1 ^ rotl(c3, 1)77                let d3 = c2 ^ rotl(c4, 1)78                let d4 = c3 ^ rotl(c0, 1)79                a00 ^= d0; a05 ^= d0; a10 ^= d0; a15 ^= d0; a20 ^= d080                a01 ^= d1; a06 ^= d1; a11 ^= d1; a16 ^= d1; a21 ^= d181                a02 ^= d2; a07 ^= d2; a12 ^= d2; a17 ^= d2; a22 ^= d282                a03 ^= d3; a08 ^= d3; a13 ^= d3; a18 ^= d3; a23 ^= d383                a04 ^= d4; a09 ^= d4; a14 ^= d4; a19 ^= d4; a24 ^= d48485                // ρ and π: B[y, 2x + 3y] = rot(A[x, y], r[x, y])86                let b00 = a0087                let b10 = rotl(a01, 1)88                let b20 = rotl(a02, 62)89                let b05 = rotl(a03, 28)90                let b15 = rotl(a04, 27)91                let b16 = rotl(a05, 36)92                let b01 = rotl(a06, 44)93                let b11 = rotl(a07, 6)94                let b21 = rotl(a08, 55)95                let b06 = rotl(a09, 20)96                let b07 = rotl(a10, 3)97                let b17 = rotl(a11, 10)98                let b02 = rotl(a12, 43)99                let b12 = rotl(a13, 25)100                let b22 = rotl(a14, 39)101                let b23 = rotl(a15, 41)102                let b08 = rotl(a16, 45)103                let b18 = rotl(a17, 15)104                let b03 = rotl(a18, 21)105                let b13 = rotl(a19, 8)106                let b14 = rotl(a20, 18)107                let b24 = rotl(a21, 2)108                let b09 = rotl(a22, 61)109                let b19 = rotl(a23, 56)110                let b04 = rotl(a24, 14)111112                // χ113                a00 = b00 ^ (~b01 & b02); a01 = b01 ^ (~b02 & b03); a02 = b02 ^ (~b03 & b04)114                a03 = b03 ^ (~b04 & b00); a04 = b04 ^ (~b00 & b01)115                a05 = b05 ^ (~b06 & b07); a06 = b06 ^ (~b07 & b08); a07 = b07 ^ (~b08 & b09)116                a08 = b08 ^ (~b09 & b05); a09 = b09 ^ (~b05 & b06)117                a10 = b10 ^ (~b11 & b12); a11 = b11 ^ (~b12 & b13); a12 = b12 ^ (~b13 & b14)118                a13 = b13 ^ (~b14 & b10); a14 = b14 ^ (~b10 & b11)119                a15 = b15 ^ (~b16 & b17); a16 = b16 ^ (~b17 & b18); a17 = b17 ^ (~b18 & b19)120                a18 = b18 ^ (~b19 & b15); a19 = b19 ^ (~b15 & b16)121                a20 = b20 ^ (~b21 & b22); a21 = b21 ^ (~b22 & b23); a22 = b22 ^ (~b23 & b24)122                a23 = b23 ^ (~b24 & b20); a24 = b24 ^ (~b20 & b21)123124                // ι125                a00 ^= rc[round]126            }127128            a[0] = a00; a[1] = a01; a[2] = a02; a[3] = a03; a[4] = a04129            a[5] = a05; a[6] = a06; a[7] = a07; a[8] = a08; a[9] = a09130            a[10] = a10; a[11] = a11; a[12] = a12; a[13] = a13; a[14] = a14131            a[15] = a15; a[16] = a16; a[17] = a17; a[18] = a18; a[19] = a19132            a[20] = a20; a[21] = a21; a[22] = a22; a[23] = a23; a[24] = a24133        }134    }135}136137/// Sponge construction over Keccak-f[1600] with byte-aligned input and output.138///139/// `suffix` carries the domain-separation bits together with the first padding bit:140/// 0x06 for SHA-3, 0x1f for SHAKE, 0x04 for cSHAKE, 0x01 for the original Keccak (Ethereum).141public struct KeccakSponge: Sendable {142    @usableFromInline var state = [UInt64](repeating: 0, count: 25)143    public let rate: Int144    public let suffix: UInt8145    @usableFromInline var position = 0146    @usableFromInline var squeezing = false147148    public init(rate: Int, suffix: UInt8) {149        precondition(rate > 0 && rate < 200 && rate % 8 == 0)150        self.rate = rate151        self.suffix = suffix152    }153154    public mutating func absorb(_ data: Bytes) {155        precondition(!squeezing, "absorb after squeeze")156        let rate = self.rate157        var pos = position158        state.withUnsafeMutableBufferPointer { s in159            data.withUnsafeBufferPointer { d in160                var i = 0161                let n = d.count162                while i < n {163                    // whole lanes when aligned164                    if pos & 7 == 0 {165                        while n - i >= 8 && rate - pos >= 8 {166                            s[pos >> 3] ^= Endian.loadLE64(d.baseAddress! + i)167                            pos += 8168                            i += 8169                            if pos == rate {170                                KeccakF1600.permute(s.baseAddress!)171                                pos = 0172                            }173                        }174                        if i == n { break }175                    }176                    s[pos >> 3] ^= UInt64(d[i]) << UInt64((pos & 7) << 3)177                    pos += 1178                    i += 1179                    if pos == rate {180                        KeccakF1600.permute(s.baseAddress!)181                        pos = 0182                    }183                }184            }185        }186        position = pos187    }188189    @usableFromInline mutating func pad() {190        state[position >> 3] ^= UInt64(suffix) << UInt64((position & 7) << 3)191        state[(rate - 1) >> 3] ^= 0x80 << UInt64(((rate - 1) & 7) << 3)192        state.withUnsafeMutableBufferPointer { KeccakF1600.permute($0.baseAddress!) }193        position = 0194        squeezing = true195    }196197    /// Produces the next `count` output bytes. May be called repeatedly (extendable output).198    public mutating func squeeze(_ count: Int) -> Bytes {199        var out = Bytes(repeating: 0, count: count)200        out.withUnsafeMutableBufferPointer { squeeze(into: $0) }201        return out202    }203204    public mutating func squeeze(into out: UnsafeMutableBufferPointer<UInt8>) {205        if !squeezing { pad() }206        let rate = self.rate207        var pos = position208        let n = out.count209        guard n > 0, let base = out.baseAddress else { return }210        state.withUnsafeMutableBufferPointer { s in211            var i = 0212            while i < n {213                if pos == rate {214                    KeccakF1600.permute(s.baseAddress!)215                    pos = 0216                }217                // whole lanes when aligned (the rate is a multiple of 8, so a full lane is available)218                if pos & 7 == 0 && n - i >= 8 {219                    UnsafeMutableRawPointer(base + i).storeBytes(of: s[pos >> 3].littleEndian, as: UInt64.self)220                    pos += 8221                    i += 8222                } else {223                    base[i] = UInt8(truncatingIfNeeded: s[pos >> 3] >> UInt64((pos & 7) << 3))224                    pos += 1225                    i += 1226                }227            }228        }229        position = pos230    }231232    /// Erases the internal state (call when the sponge absorbed secret material).233    public mutating func wipe() {234        SecureMemory.zero(&state)235        position = 0236    }237238    /// Produces `count` output bytes, then erases the internal state. Keccak-f is a permutation: a state239    /// left in memory can be run backwards to the last absorbed block, so the one-shot functions (which240    /// hash seeds and keys) never leave it behind. The instance must not be used afterwards.241    public mutating func squeezeAndWipe(_ count: Int) -> Bytes {242        let out = squeeze(count)243        wipe()244        return out245    }246}247248/// Extendable-output functions SHAKE128 and SHAKE256 (FIPS 202, section 6.2).249public struct SHAKE: Sendable {250    @usableFromInline var sponge: KeccakSponge251252    /// `securityBits` is 128 or 256.253    public init(_ securityBits: Int) {254        precondition(securityBits == 128 || securityBits == 256)255        sponge = KeccakSponge(rate: 200 - securityBits / 4, suffix: 0x1f)256    }257258    public mutating func absorb(_ data: Bytes) { sponge.absorb(data) }259    public mutating func squeeze(_ count: Int) -> Bytes { sponge.squeeze(count) }260    public mutating func squeeze(into out: UnsafeMutableBufferPointer<UInt8>) { sponge.squeeze(into: out) }261    public mutating func wipe() { sponge.wipe() }262263    public static func shake128(_ data: Bytes, outputLength: Int) -> Bytes {264        var x = SHAKE(128)265        x.absorb(data)266        return x.sponge.squeezeAndWipe(outputLength)267    }268269    public static func shake256(_ data: Bytes, outputLength: Int) -> Bytes {270        var x = SHAKE(256)271        x.absorb(data)272        return x.sponge.squeezeAndWipe(outputLength)273    }274}275276/// Fixed-output SHA-3 functions (FIPS 202, section 6.1) and the original Keccak-256 used by Ethereum.277public enum SHA3 {278    static func fixed(_ data: Bytes, digest: Int, suffix: UInt8) -> Bytes {279        var s = KeccakSponge(rate: 200 - 2 * digest, suffix: suffix)280        s.absorb(data)281        return s.squeezeAndWipe(digest)282    }283284    public static func sha3_224(_ data: Bytes) -> Bytes { fixed(data, digest: 28, suffix: 0x06) }285    public static func sha3_256(_ data: Bytes) -> Bytes { fixed(data, digest: 32, suffix: 0x06) }286    public static func sha3_384(_ data: Bytes) -> Bytes { fixed(data, digest: 48, suffix: 0x06) }287    public static func sha3_512(_ data: Bytes) -> Bytes { fixed(data, digest: 64, suffix: 0x06) }288289    /// Keccak-256 with the pre-standard padding (0x01), as used by Ethereum. Not SHA3-256.290    public static func keccak256(_ data: Bytes) -> Bytes { fixed(data, digest: 32, suffix: 0x01) }291}292293/// Incremental SHA3-256 conforming to `HashFunction` (HMAC-SHA3, generic callers).294public struct SHA3_256: HashFunction {295    public static let blockSize = 136296    public static let digestSize = 32297    var sponge = KeccakSponge(rate: 136, suffix: 0x06)298    public init() {}299    public mutating func update(_ data: Bytes) { sponge.absorb(data) }300    public mutating func finalize() -> Bytes { sponge.squeezeAndWipe(32) }301}302303/// Incremental SHA3-512 conforming to `HashFunction`.304public struct SHA3_512: HashFunction {305    public static let blockSize = 72306    public static let digestSize = 64307    var sponge = KeccakSponge(rate: 72, suffix: 0x06)308    public init() {}309    public mutating func update(_ data: Bytes) { sponge.absorb(data) }310    public mutating func finalize() -> Bytes { sponge.squeezeAndWipe(64) }311}312
Files main
Menu

Theme