SPB Git

Repository Public

ConstantTime.swift 4.2 KB 113 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraMath/ConstantTime.swift8// Module           : Qyvora Math9// 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 Foundation4243/// Operations whose running time must not depend on secret values.44///45/// Swift gives no formal constant-time guarantee: these routines avoid secret-dependent46/// branches and memory indices at the source level, and `docs/THREAT_MODEL.md` records the47/// residual risk (compiler transformations, micro-architecture).48public enum ConstantTime {49    /// Equality of two byte strings. The lengths are public; the contents are compared without early exit.50    public static func equal(_ a: Bytes, _ b: Bytes) -> Bool {51        let dit = DataIndependentTiming.enable()52        defer { DataIndependentTiming.restore(dit) }53        guard a.count == b.count else { return false }54        var acc: UInt8 = 055        for i in 0..<a.count { acc |= a[i] ^ b[i] }56        return isZeroMask(acc) == 0xff57    }5859    /// 0xff when `x == 0`, 0x00 otherwise, without branching on `x`.60    @inlinable public static func isZeroMask(_ x: UInt8) -> UInt8 {61        let v = UInt32(x)62        return UInt8(truncatingIfNeeded: (v &- 1) >> 8)63    }6465    /// Returns `a` when `mask == 0xff`, `b` when `mask == 0x00`.66    public static func select(mask: UInt8, _ a: Bytes, _ b: Bytes) -> Bytes {67        precondition(a.count == b.count)68        var out = Bytes(repeating: 0, count: a.count)69        for i in 0..<a.count { out[i] = (a[i] & mask) | (b[i] & ~mask) }70        return out71    }72}7374/// Best-effort erasure of secret material.75public enum SecureMemory {76    /// Overwrites the buffer with zeros through `memset_s`, which the optimizer may not remove.77    public static func zero(_ bytes: inout Bytes) {78        let n = bytes.count79        guard n > 0 else { return }80        bytes.withUnsafeMutableBytes { p in81            _ = memset_s(p.baseAddress, n, 0, n)82        }83    }8485    public static func zero<T: FixedWidthInteger>(_ values: inout [T]) {86        let n = values.count * MemoryLayout<T>.stride87        guard n > 0 else { return }88        values.withUnsafeMutableBytes { p in89            _ = memset_s(p.baseAddress, n, 0, n)90        }91    }92}9394/// The interface every hash function of the engine exposes (used by HMAC, HKDF, MGF1…).95public protocol HashFunction: Sendable {96    /// Internal block size in bytes (HMAC key block).97    static var blockSize: Int { get }98    /// Output size in bytes.99    static var digestSize: Int { get }100    init()101    mutating func update(_ data: Bytes)102    /// Returns the digest. The instance must not be used afterwards.103    mutating func finalize() -> Bytes104}105106public extension HashFunction {107    static func hash(_ data: Bytes) -> Bytes {108        var h = Self()109        h.update(data)110        return h.finalize()111    }112}113
Files main
Menu

Theme