Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraSymmetricTests/KDFTests.swift8// Module : Tests9// 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 CommonCrypto42import CryptoKit43import Foundation44import Testing45import QyvoraKeccak46import QyvoraMath47@testable import QyvoraSymmetric4849private typealias QSHA224 = QyvoraSymmetric.SHA22450private typealias QSHA256 = QyvoraSymmetric.SHA25651private typealias QSHA384 = QyvoraSymmetric.SHA38452private typealias QSHA512 = QyvoraSymmetric.SHA51253private typealias QHKDF = QyvoraSymmetric.HKDF5455private func randomBytes(_ n: Int) -> Bytes {56 var rng = SystemRandomNumberGenerator()57 return (0..<n).map { _ in UInt8.random(in: 0...255, using: &rng) }58}5960/// CommonCrypto PBKDF2 as an independent oracle.61private func ccPBKDF2(_ prf: Int, password: Bytes, salt: Bytes, iterations: Int, length: Int) -> Bytes {62 var out = Bytes(repeating: 0, count: length)63 let status = password.withUnsafeBufferPointer { p in64 p.withMemoryRebound(to: CChar.self) { pw in65 CCKeyDerivationPBKDF(66 CCPBKDFAlgorithm(kCCPBKDF2), pw.baseAddress, pw.count, salt, salt.count,67 CCPseudoRandomAlgorithm(prf), UInt32(iterations), &out, length)68 }69 }70 precondition(status == kCCSuccess)71 return out72}7374@Suite struct SHA2VariantTests {75 @Test func knownAnswers() {76 // FIPS 180-4 examples ("abc")77 #expect(QSHA224.hash(Array("abc".utf8)).hex == "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")78 #expect(QSHA384.hash(Array("abc".utf8)).hex79 == "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7")80 }8182 @Test func sha384DifferentialAgainstCryptoKit() {83 for n in [0, 1, 111, 112, 113, 127, 128, 129, 255, 256, 1000, 4097] {84 let m = randomBytes(n)85 #expect(QSHA384.hash(m) == Array(CryptoKit.SHA384.hash(data: Data(m))))86 var h = QSHA384()87 h.update(Array(m.prefix(n / 2))); h.update(Array(m.dropFirst(n / 2)))88 #expect(h.finalize() == Array(CryptoKit.SHA384.hash(data: Data(m))))89 let key = randomBytes(n % 300)90 let ref = CryptoKit.HMAC<CryptoKit.SHA384>.authenticationCode(for: Data(m), using: SymmetricKey(data: Data(key)))91 #expect(QyvoraSymmetric.HMAC<QSHA384>.authenticate(key: key, message: m) == Array(ref))92 }93 }9495 @Test func sha224DifferentialAgainstCommonCrypto() {96 for n in [0, 1, 55, 56, 57, 63, 64, 65, 1000] {97 let m = randomBytes(n)98 var ref = Bytes(repeating: 0, count: 28)99 _ = CC_SHA224(m, CC_LONG(m.count), &ref)100 #expect(QSHA224.hash(m) == ref)101 }102 }103}104105@Suite struct HKDFTests {106 struct Case {107 let ikm: String, salt: String, info: String, length: Int, prk: String, okm: String108 }109110 /// RFC 5869, appendix A, test cases 1 to 3 (SHA-256). Cases 4 to 7 use SHA-1, which the engine does not implement.111 static let rfc5869: [Case] = [112 Case(ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt: "000102030405060708090a0b0c",113 info: "f0f1f2f3f4f5f6f7f8f9", length: 42,114 prk: "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5",115 okm: "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"),116 Case(ikm: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f"117 + "303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f",118 salt: "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f"119 + "909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf",120 info: "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf"121 + "e0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",122 length: 82,123 prk: "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244",124 okm: "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09"125 + "da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87"),126 Case(ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt: "", info: "", length: 42,127 prk: "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04",128 okm: "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"),129 ]130131 @Test func rfc5869Vectors() {132 for c in Self.rfc5869 {133 let ikm = Bytes(hex: c.ikm)!, salt = Bytes(hex: c.salt)!, info = Bytes(hex: c.info)!134 let prk = QHKDF<QSHA256>.extract(salt: salt, inputKeyMaterial: ikm)135 #expect(prk.hex == c.prk)136 #expect(QHKDF<QSHA256>.expand(pseudoRandomKey: prk, info: info, length: c.length)?.hex == c.okm)137 #expect(QHKDF<QSHA256>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: c.length)?.hex == c.okm)138 }139 }140141 @Test func differentialAgainstCryptoKit() {142 for trial in 0..<60 {143 let ikm = randomBytes(1 + trial * 3), salt = randomBytes(trial % 7 == 0 ? 0 : trial * 2), info = randomBytes(trial % 5 == 0 ? 0 : trial)144 let length = [1, 16, 31, 32, 33, 64, 65, 100, 255, 1000][trial % 10]145 let key = SymmetricKey(data: Data(ikm))146 let r256 = CryptoKit.HKDF<CryptoKit.SHA256>.deriveKey(inputKeyMaterial: key, salt: Data(salt), info: Data(info), outputByteCount: length)147 #expect(QHKDF<QSHA256>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: length) == r256.withUnsafeBytes { Array($0) })148 let r512 = CryptoKit.HKDF<CryptoKit.SHA512>.deriveKey(inputKeyMaterial: key, salt: Data(salt), info: Data(info), outputByteCount: length)149 #expect(QHKDF<QSHA512>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: length) == r512.withUnsafeBytes { Array($0) })150 let r384 = CryptoKit.HKDF<CryptoKit.SHA384>.deriveKey(inputKeyMaterial: key, salt: Data(salt), info: Data(info), outputByteCount: length)151 #expect(QHKDF<QSHA384>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: length) == r384.withUnsafeBytes { Array($0) })152 }153 }154155 @Test func limits() {156 let prk = Bytes(repeating: 7, count: 32)157 #expect(QHKDF<QSHA256>.expand(pseudoRandomKey: prk, info: [], length: 255 * 32)?.count == 255 * 32)158 #expect(QHKDF<QSHA256>.expand(pseudoRandomKey: prk, info: [], length: 255 * 32 + 1) == nil)159 #expect(QHKDF<QSHA256>.expand(pseudoRandomKey: prk, info: [], length: -1) == nil)160 #expect(QHKDF<QSHA256>.expand(pseudoRandomKey: Bytes(repeating: 7, count: 31), info: [], length: 16) == nil)161 #expect(QHKDF<QSHA256>.expand(pseudoRandomKey: prk, info: [], length: 0) == [])162 #expect(QHKDF<QSHA256>.deriveKey(inputKeyMaterial: [1], salt: [], info: [], length: 255 * 32 + 1) == nil)163 }164}165166@Suite struct PBKDF2Tests {167 /// RFC 7914, section 11: PBKDF2-HMAC-SHA-256.168 @Test func rfc7914Vectors() {169 #expect(PBKDF2<QSHA256>.deriveKey(password: Array("passwd".utf8), salt: Array("salt".utf8), iterations: 1, length: 64).hex170 == "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc"171 + "49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783")172 #expect(PBKDF2<QSHA256>.deriveKey(password: Array("Password".utf8), salt: Array("NaCl".utf8), iterations: 80000, length: 64).hex173 == "4ddcd8f60b98be21830cee5ef22701f9641a4418d04c0414aeff08876b34ab56"174 + "a1d425a1225833549adb841b51c9b3176a272bdebba1d078478f62b397f33c8d")175 }176177 /// BIP-39 reference vector (Trezor python-mnemonic `vectors.json`, first English entry, passphrase "TREZOR"):178 /// seed = PBKDF2-HMAC-SHA512(mnemonic, "mnemonic" || passphrase, 2048, 64).179 @Test func bip39SeedVector() {180 let mnemonic = Array(repeating: "abandon", count: 11).joined(separator: " ") + " about"181 let seed = PBKDF2<QSHA512>.deriveKey(password: Array(mnemonic.utf8), salt: Array("mnemonicTREZOR".utf8), iterations: 2048, length: 64)182 #expect(seed.hex == "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141"183 + "630c7a3c4ab7c81b2f001698e7463b04")184 }185186 @Test func differentialAgainstCommonCrypto() {187 for trial in 0..<40 {188 // password lengths cross the block size (64 and 128 bytes), where the key is hashed first189 let password = randomBytes([1, 8, 63, 64, 65, 127, 128, 129, 200, 300][trial % 10])190 let salt = randomBytes(trial % 9 == 0 ? 0 : 1 + trial * 2)191 let iterations = [1, 2, 3, 10, 100, 257][trial % 6]192 let length = [1, 20, 32, 33, 64, 65, 100, 129, 200][trial % 9]193 #expect(PBKDF2<QSHA256>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)194 == ccPBKDF2(kCCPRFHmacAlgSHA256, password: password, salt: salt, iterations: iterations, length: length))195 #expect(PBKDF2<QSHA512>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)196 == ccPBKDF2(kCCPRFHmacAlgSHA512, password: password, salt: salt, iterations: iterations, length: length))197 #expect(PBKDF2<QSHA224>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)198 == ccPBKDF2(kCCPRFHmacAlgSHA224, password: password, salt: salt, iterations: iterations, length: length))199 #expect(PBKDF2<QSHA384>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)200 == ccPBKDF2(kCCPRFHmacAlgSHA384, password: password, salt: salt, iterations: iterations, length: length))201 }202 }203204 /// PBKDF2 with one iteration and one block is a single HMAC over `salt || INT(1)`.205 @Test func singleIterationIsHMAC() {206 let password = randomBytes(40), salt = randomBytes(16)207 #expect(PBKDF2<QSHA512>.deriveKey(password: password, salt: salt, iterations: 1, length: 64)208 == QyvoraSymmetric.HMAC<QSHA512>.authenticate(key: password, message: salt + [0, 0, 0, 1]))209 // generic over the Keccak hashes too210 #expect(PBKDF2<QyvoraKeccak.SHA3_256>.deriveKey(password: password, salt: salt, iterations: 1, length: 32)211 == QyvoraSymmetric.HMAC<QyvoraKeccak.SHA3_256>.authenticate(key: password, message: salt + [0, 0, 0, 1]))212 #expect(PBKDF2<QSHA256>.deriveKey(password: password, salt: salt, iterations: 5, length: 0) == [])213 }214}215216@Suite struct MGF1Tests {217 @Test func knownAnswerAndStructure() {218 // widely published MGF1-SHA256 example: seed "bar", 50 bytes219 #expect(MGF1<QSHA256>.mask(seed: Array("bar".utf8), length: 50).hex220 == "382576a7841021cc28fc4c0948753fb8312090cea942ea4c4e735d10dc724b155f9f6069f289d61daca0cb814502ef04eae1")221 let seed = randomBytes(33)222 let long = MGF1<QSHA512>.mask(seed: seed, length: 200)223 #expect(Bytes(long[0..<64]) == QSHA512.hash(seed + [0, 0, 0, 0]))224 #expect(Bytes(long[64..<128]) == QSHA512.hash(seed + [0, 0, 0, 1]))225 #expect(Bytes(long[192..<200]) == Bytes(QSHA512.hash(seed + [0, 0, 0, 3]).prefix(8)))226 #expect(MGF1<QSHA256>.mask(seed: seed, length: 0) == [])227 // a prefix of a longer mask is the shorter mask228 #expect(Bytes(long.prefix(77)) == MGF1<QSHA512>.mask(seed: seed, length: 77))229 }230}231232@Suite struct RIPEMD160Tests {233 /// Test vectors of the RIPEMD-160 reference publication (Dobbertin, Bosselaers, Preneel; also ISO/IEC 10118-3).234 static let official: [(String, String)] = [235 ("", "9c1185a5c5e9fc54612808977ee8f548b2258d31"),236 ("a", "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe"),237 ("abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"),238 ("message digest", "5d0689ef49d2fae572b881b123a85ffa21595f36"),239 ("abcdefghijklmnopqrstuvwxyz", "f71c27109c692c1b56bbdceb5b9d2865b3708dbc"),240 ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "12a053384a9c0c88e405a06c27dcf49ada62eb2b"),241 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "b0e20b6e3116640286ed3a87a5713079b21f5189"),242 (String(repeating: "1234567890", count: 8), "9b752e45573d4b39f4dbd3323cab82bf63326bfb"),243 ]244245 @Test func officialVectors() {246 for (message, digest) in Self.official {247 #expect(RIPEMD160.hash(Array(message.utf8)).hex == digest)248 }249 }250251 @Test func oneMillionA() {252 var h = RIPEMD160()253 let chunk = Bytes(repeating: 0x61, count: 1000)254 for _ in 0..<1000 { h.update(chunk) }255 #expect(h.finalize().hex == "52783243c1697bdbe16d37f97f68f08325dc1528")256 }257258 @Test func incrementalEqualsOneShot() {259 for n in [0, 1, 55, 56, 57, 63, 64, 65, 119, 120, 128, 129, 1000] {260 let m = randomBytes(n)261 let want = RIPEMD160.hash(m)262 var rng = SystemRandomNumberGenerator()263 var h = RIPEMD160()264 var i = 0265 while i < n {266 let step = min(n - i, Int.random(in: 0...70, using: &rng))267 h.update(Array(m[i..<(i + step)]))268 i += step269 }270 #expect(h.finalize() == want)271 }272 #expect(RIPEMD160.blockSize == 64 && RIPEMD160.digestSize == 20)273 }274275 @Test func hash160() {276 // Bitcoin wiki "Technical background of version 1 Bitcoin addresses": compressed public key → HASH160277 let publicKey = Bytes(hex: "0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352")!278 #expect(Hash160.hash(publicKey).hex == "f54a5851e9372b87810a8e60cdd2e7cfd80b6e31")279 #expect(Hash160.hash([]) == RIPEMD160.hash(QSHA256.hash([])))280 #expect(Hash160.hash([]).hex == "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb")281 }282}283