Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraSymmetric/KDF.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/// HKDF, the HMAC-based extract-and-expand key derivation function (RFC 5869).44public enum HKDF<H: HashFunction> {45 /// HKDF-Extract (RFC 5869, section 2.2). An empty salt stands for `H.digestSize` zero bytes.46 public static func extract(salt: Bytes, inputKeyMaterial: Bytes) -> Bytes {47 let dit = DataIndependentTiming.enable()48 defer { DataIndependentTiming.restore(dit) }49 let s = salt.isEmpty ? Bytes(repeating: 0, count: H.digestSize) : salt50 return HMAC<H>.authenticate(key: s, message: inputKeyMaterial)51 }5253 /// HKDF-Expand (RFC 5869, section 2.3). Returns nil when `length` exceeds `255 * H.digestSize`54 /// or is negative, or when the pseudorandom key is shorter than the digest.55 public static func expand(pseudoRandomKey: Bytes, info: Bytes, length: Int) -> Bytes? {56 let dit = DataIndependentTiming.enable()57 defer { DataIndependentTiming.restore(dit) }58 guard length >= 0, length <= 255 * H.digestSize, pseudoRandomKey.count >= H.digestSize else { return nil }59 var okm = Bytes()60 okm.reserveCapacity(length)61 var t = Bytes()62 var counter: UInt8 = 163 while okm.count < length {64 var m = HMAC<H>(key: pseudoRandomKey)65 m.update(t)66 m.update(info)67 m.update([counter])68 SecureMemory.zero(&t)69 t = m.finalize()70 okm.append(contentsOf: t.prefix(length - okm.count))71 counter &+= 172 }73 SecureMemory.zero(&t)74 return okm75 }7677 /// Extract then expand. Returns nil when `length` exceeds `255 * H.digestSize` or is negative.78 public static func deriveKey(inputKeyMaterial: Bytes, salt: Bytes, info: Bytes, length: Int) -> Bytes? {79 var prk = extract(salt: salt, inputKeyMaterial: inputKeyMaterial)80 defer { SecureMemory.zero(&prk) }81 return expand(pseudoRandomKey: prk, info: info, length: length)82 }83}8485/// PBKDF2 with HMAC as pseudorandom function (RFC 8018, section 5.2; BIP-39 uses HMAC-SHA512, 2048 iterations).86public enum PBKDF2<H: HashFunction> {87 /// Derives `length` bytes. `iterations` must be at least 1 and `length` at most `(2^32 - 1) * H.digestSize`88 /// (programming errors, checked by precondition).89 ///90 /// The two HMAC key blocks are absorbed once; every iteration then costs two compression calls91 /// on copies of those states.92 public static func deriveKey(password: Bytes, salt: Bytes, iterations: Int, length: Int) -> Bytes {93 let dit = DataIndependentTiming.enable()94 defer { DataIndependentTiming.restore(dit) }95 precondition(iterations >= 1, "PBKDF2 needs at least one iteration")96 precondition(length >= 0 && UInt64(length) <= UInt64(UInt32.max) * UInt64(H.digestSize), "PBKDF2 output too long")9798 var key = password.count > H.blockSize ? H.hash(password) : password99 key.append(contentsOf: Bytes(repeating: 0, count: H.blockSize - key.count))100 var ipad = key.map { $0 ^ 0x36 }101 var opad = key.map { $0 ^ 0x5c }102 var innerBase = H()103 innerBase.update(ipad)104 var outerBase = H()105 outerBase.update(opad)106 SecureMemory.zero(&key)107 SecureMemory.zero(&ipad)108 SecureMemory.zero(&opad)109110 @inline(__always) func prf(_ message: Bytes) -> Bytes {111 var inner = innerBase112 inner.update(message)113 var outer = outerBase114 outer.update(inner.finalize())115 return outer.finalize()116 }117118 var out = Bytes()119 out.reserveCapacity(length)120 var block: UInt32 = 1121 while out.count < length {122 var u = prf(salt + Endian.be32(block))123 var t = u124 if iterations > 1 {125 for _ in 1..<iterations {126 u = prf(u)127 for i in 0..<t.count { t[i] ^= u[i] }128 }129 }130 out.append(contentsOf: t.prefix(length - out.count))131 SecureMemory.zero(&u)132 SecureMemory.zero(&t)133 block &+= 1134 }135 return out136 }137}138139/// MGF1, the mask generation function of PKCS #1 (RFC 8017, appendix B.2.1).140public enum MGF1<H: HashFunction> {141 /// Returns `length` mask bytes: `H(seed || 0) || H(seed || 1) || …` with a 32-bit big-endian counter.142 public static func mask(seed: Bytes, length: Int) -> Bytes {143 precondition(length >= 0 && UInt64(length) <= (UInt64(UInt32.max) + 1) * UInt64(H.digestSize), "mask too long")144 var out = Bytes()145 out.reserveCapacity(length)146 var counter: UInt32 = 0147 while out.count < length {148 var h = H()149 h.update(seed)150 h.update(Endian.be32(counter))151 out.append(contentsOf: h.finalize().prefix(length - out.count))152 counter &+= 1153 }154 return out155 }156}157