SPB Git

Repository Public

SP800185.swift 10.1 KB 242 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraKeccak/SP800185.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/// Encoding primitives of NIST SP 800-185, section 2.3.44public enum SP800185 {45    /// Minimal big-endian encoding of `x` on at least one byte.46    @inline(__always) static func minimalBigEndian(_ x: UInt64) -> Bytes {47        var out = Bytes()48        var started = false49        for shift in stride(from: 56, through: 0, by: -8) {50            let b = UInt8(truncatingIfNeeded: x >> UInt64(shift))51            if b != 0 || started || shift == 0 {52                out.append(b)53                started = true54            }55        }56        return out57    }5859    /// `left_encode(x)`: the byte count of the encoding, then `x` in big-endian order.60    public static func leftEncode(_ x: UInt64) -> Bytes {61        let v = minimalBigEndian(x)62        return [UInt8(v.count)] + v63    }6465    /// `right_encode(x)`: `x` in big-endian order, then the byte count of the encoding.66    public static func rightEncode(_ x: UInt64) -> Bytes {67        let v = minimalBigEndian(x)68        return v + [UInt8(v.count)]69    }7071    /// `encode_string(S)`: `left_encode(len(S) in bits) || S`.72    public static func encodeString(_ s: Bytes) -> Bytes {73        leftEncode(UInt64(s.count) &* 8) + s74    }7576    /// `bytepad(X, w)`: `left_encode(w) || X`, padded with zero bytes to a multiple of `w` bytes.77    public static func bytepad(_ x: Bytes, _ w: Int) -> Bytes {78        precondition(w > 0)79        var z = leftEncode(UInt64(w)) + x80        let r = z.count % w81        if r != 0 { z.append(contentsOf: Bytes(repeating: 0, count: w - r)) }82        return z83    }84}8586/// cSHAKE128 and cSHAKE256, the customizable SHAKE of NIST SP 800-185, section 3.87///88/// With an empty function name and an empty customization string, cSHAKE is SHAKE (section 3.3).89public struct CSHAKE: Sendable {90    @usableFromInline var sponge: KeccakSponge9192    /// `securityBits` is 128 or 256. `functionName` is N (reserved for NIST-defined functions),93    /// `customization` is S.94    public init(_ securityBits: Int, functionName: Bytes = [], customization: Bytes = []) {95        precondition(securityBits == 128 || securityBits == 256)96        let rate = 200 - securityBits / 497        if functionName.isEmpty && customization.isEmpty {98            sponge = KeccakSponge(rate: rate, suffix: 0x1f)99        } else {100            sponge = KeccakSponge(rate: rate, suffix: 0x04)101            sponge.absorb(SP800185.bytepad(SP800185.encodeString(functionName) + SP800185.encodeString(customization), rate))102        }103    }104105    public mutating func absorb(_ data: Bytes) { sponge.absorb(data) }106    public mutating func squeeze(_ count: Int) -> Bytes { sponge.squeeze(count) }107    public mutating func squeeze(into out: UnsafeMutableBufferPointer<UInt8>) { sponge.squeeze(into: out) }108    public mutating func wipe() { sponge.wipe() }109110    public static func cshake128(_ data: Bytes, outputLength: Int, functionName: Bytes = [], customization: Bytes = []) -> Bytes {111        var x = CSHAKE(128, functionName: functionName, customization: customization)112        x.absorb(data)113        return x.sponge.squeezeAndWipe(outputLength)114    }115116    public static func cshake256(_ data: Bytes, outputLength: Int, functionName: Bytes = [], customization: Bytes = []) -> Bytes {117        var x = CSHAKE(256, functionName: functionName, customization: customization)118        x.absorb(data)119        return x.sponge.squeezeAndWipe(outputLength)120    }121}122123/// KMAC128 and KMAC256, the Keccak message authentication code of NIST SP 800-185, section 4,124/// with its fixed-length form (`finalize(outputLength:)`) and its extendable-output form KMACXOF125/// (`finalizeXOF()` then `squeeze`).126///127/// The output length is part of the fixed-length computation: two tags of different lengths are unrelated.128public struct KMAC: Sendable {129    @usableFromInline var sponge: KeccakSponge130    @usableFromInline var finished = false131132    /// `securityBits` is 128 or 256. SP 800-185 expects a key of at least `securityBits` bits;133    /// shorter keys are accepted (as in the standard's definition) but weaken the function.134    public init(_ securityBits: Int, key: Bytes, customization: Bytes = []) {135        precondition(securityBits == 128 || securityBits == 256)136        let rate = 200 - securityBits / 4137        sponge = KeccakSponge(rate: rate, suffix: 0x04)138        let name: Bytes = [0x4b, 0x4d, 0x41, 0x43] // "KMAC"139        sponge.absorb(SP800185.bytepad(SP800185.encodeString(name) + SP800185.encodeString(customization), rate))140        var padded = SP800185.bytepad(SP800185.encodeString(key), rate)141        sponge.absorb(padded)142        SecureMemory.zero(&padded)143    }144145    public mutating func update(_ data: Bytes) {146        precondition(!finished, "update after finalize")147        sponge.absorb(data)148    }149150    /// Fixed-length KMAC: returns `outputLength` bytes and erases the state.151    public mutating func finalize(outputLength: Int) -> Bytes {152        precondition(!finished, "finalize called twice")153        precondition(outputLength >= 0)154        finished = true155        sponge.absorb(SP800185.rightEncode(UInt64(outputLength) &* 8))156        let out = sponge.squeeze(outputLength)157        sponge.wipe()158        return out159    }160161    /// KMACXOF: closes the input; `squeeze` then yields an arbitrary amount of output.162    public mutating func finalizeXOF() {163        precondition(!finished, "finalize called twice")164        finished = true165        sponge.absorb(SP800185.rightEncode(0))166    }167168    /// Next `count` bytes of the KMACXOF output. Valid only after `finalizeXOF()`.169    public mutating func squeeze(_ count: Int) -> Bytes {170        precondition(finished, "squeeze before finalizeXOF")171        return sponge.squeeze(count)172    }173174    public mutating func wipe() { sponge.wipe() }175176    public static func kmac128(key: Bytes, message: Bytes, outputLength: Int, customization: Bytes = []) -> Bytes {177        var m = KMAC(128, key: key, customization: customization)178        m.update(message)179        return m.finalize(outputLength: outputLength)180    }181182    public static func kmac256(key: Bytes, message: Bytes, outputLength: Int, customization: Bytes = []) -> Bytes {183        var m = KMAC(256, key: key, customization: customization)184        m.update(message)185        return m.finalize(outputLength: outputLength)186    }187188    public static func kmacxof128(key: Bytes, message: Bytes, outputLength: Int, customization: Bytes = []) -> Bytes {189        var m = KMAC(128, key: key, customization: customization)190        m.update(message)191        m.finalizeXOF()192        let out = m.squeeze(outputLength)193        m.wipe()194        return out195    }196197    public static func kmacxof256(key: Bytes, message: Bytes, outputLength: Int, customization: Bytes = []) -> Bytes {198        var m = KMAC(256, key: key, customization: customization)199        m.update(message)200        m.finalizeXOF()201        let out = m.squeeze(outputLength)202        m.wipe()203        return out204    }205206    /// Shortest tag `verify` accepts, in bytes. SP 800-185, section 8.4.2: a MAC output shorter than207    /// 32 bits is forbidden and one shorter than 64 bits needs a specific risk analysis.208    public static let minimumTagSize = 8209210    /// Constant-time verification of a fixed-length KMAC tag.211    ///212    /// The tag length comes from the (possibly hostile) sender: a tag shorter than `minimumTagSize` is213    /// refused, otherwise an empty tag would verify against any message and a one-byte tag would be214    /// guessed in 256 tries. A protocol with a fixed tag length must also check that length itself.215    public static func verify(_ securityBits: Int, key: Bytes, message: Bytes, tag: Bytes, customization: Bytes = []) -> Bool {216        guard tag.count >= minimumTagSize else { return false }217        var m = KMAC(securityBits, key: key, customization: customization)218        m.update(message)219        return ConstantTime.equal(m.finalize(outputLength: tag.count), tag)220    }221}222223/// Incremental SHA3-224 conforming to `HashFunction`.224public struct SHA3_224: HashFunction {225    public static let blockSize = 144226    public static let digestSize = 28227    var sponge = KeccakSponge(rate: 144, suffix: 0x06)228    public init() {}229    public mutating func update(_ data: Bytes) { sponge.absorb(data) }230    public mutating func finalize() -> Bytes { sponge.squeezeAndWipe(28) }231}232233/// Incremental SHA3-384 conforming to `HashFunction`.234public struct SHA3_384: HashFunction {235    public static let blockSize = 104236    public static let digestSize = 48237    var sponge = KeccakSponge(rate: 104, suffix: 0x06)238    public init() {}239    public mutating func update(_ data: Bytes) { sponge.absorb(data) }240    public mutating func finalize() -> Bytes { sponge.squeezeAndWipe(48) }241}242
Files main
Menu

Theme