Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraSymmetricTests/BLAKE2Argon2Tests.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 Foundation42import Testing43import QyvoraMath44@testable import QyvoraSymmetric4546private func randomBytes(_ n: Int) -> Bytes {47 var rng = SystemRandomNumberGenerator()48 return (0..<n).map { _ in UInt8.random(in: 0...255, using: &rng) }49}5051private let optimizedBuild: Bool = {52 #if DEBUG53 return false54 #else55 return true56 #endif57}()5859@Suite struct BLAKE2bTests {60 /// RFC 7693, Appendix A.61 @Test func rfc7693Abc() {62 #expect(BLAKE2b.hash(Array("abc".utf8)).hex63 == "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"64 + "7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")65 }6667 /// RFC 7693, Appendix E: the self-test hashes keyed and unkeyed digests of four output sizes and68 /// six input lengths into one 256-bit result.69 @Test func rfc7693SelfTest() {70 func sequence(_ length: Int, seed: UInt32) -> Bytes {71 var a = 0xDEAD4BAD &* seed72 var b: UInt32 = 173 var out = Bytes()74 out.reserveCapacity(length)75 for _ in 0..<length {76 let t = a &+ b77 a = b78 b = t79 out.append(UInt8(truncatingIfNeeded: t >> 24))80 }81 return out82 }83 var grand = BLAKE2b(digestSize: 32)84 for outLength in [20, 32, 48, 64] {85 for inLength in [0, 3, 128, 129, 255, 1024] {86 let input = sequence(inLength, seed: UInt32(inLength))87 grand.update(BLAKE2b.hash(input, digestSize: outLength))88 let key = sequence(outLength, seed: UInt32(outLength))89 grand.update(BLAKE2b.hash(input, digestSize: outLength, key: key))90 }91 }92 #expect(grand.finalize().hex == "c23a7800d98123bd10f506c61e29da5603d763b8bbad2e737f5e765a7bccd475")93 }9495 @Test func knownAnswers() {96 #expect(BLAKE2b.hash([]).hex97 == "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"98 + "d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce")99 // salt and personalization: values cross-checked with CPython hashlib.blake2b (reference BLAKE2 code)100 var a = BLAKE2b(digestSize: 40, key: Bytes(repeating: 0x6b, count: 17), salt: Array("saltsalt".utf8), personalization: Array("qyvora-test".utf8))101 a.update(Array("qyvora".utf8))102 #expect(a.finalize().hex == "b75754300e99ac209805b55ced35a24210927fa8c5974737d0259f63f6d1d0471aca1d9127797483")103 var b = BLAKE2b(digestSize: 64, salt: (0..<16).map { UInt8($0) }, personalization: (16..<32).map { UInt8($0) })104 b.update((0..<200).map { UInt8($0) })105 #expect(b.finalize().hex106 == "25613b163da0d0e11c2f537b1ef3641ff0c7a9ba755fd7880a56dec1c416733a"107 + "e2735b759c33ecdef77e06f71cb031407bef529a6f12dba08b107f5bfac1e6fa")108 }109110 @Test func incrementalEqualsOneShot() {111 var rng = SystemRandomNumberGenerator()112 for n in [0, 1, 127, 128, 129, 255, 256, 257, 384, 1000, 5000] {113 let m = randomBytes(n)114 let key = randomBytes(n % 65)115 let size = 1 + n % 64116 let want = BLAKE2b.hash(m, digestSize: size, key: key)117 #expect(want.count == size)118 for _ in 0..<5 {119 var h = BLAKE2b(digestSize: size, key: key)120 var i = 0121 while i < n {122 let step = min(n - i, Int.random(in: 0...300, using: &rng))123 h.update(Array(m[i..<(i + step)]))124 i += step125 }126 #expect(h.finalize() == want)127 }128 #expect(BLAKE2b512.hash(m) == BLAKE2b.hash(m))129 }130 // digest size and key are part of the parameter block131 let m = randomBytes(50)132 #expect(Bytes(BLAKE2b.hash(m, digestSize: 64).prefix(32)) != BLAKE2b.hash(m, digestSize: 32))133 #expect(BLAKE2b.hash(m, key: [1]) != BLAKE2b.hash(m))134 }135}136137@Suite struct Argon2Tests {138 static let password = Bytes(repeating: 0x01, count: 32)139 static let salt = Bytes(repeating: 0x02, count: 16)140 static let secret = Bytes(repeating: 0x03, count: 8)141 static let associatedData = Bytes(repeating: 0x04, count: 12)142 static let rfcParameters = Argon2.Parameters(memoryKiB: 32, iterations: 3, parallelism: 4, tagLength: 32)143144 /// RFC 9106, section 5.3.145 @Test func rfc9106Argon2id() throws {146 let tag = try Argon2.id(password: Self.password, salt: Self.salt, parameters: Self.rfcParameters, secret: Self.secret, associatedData: Self.associatedData)147 #expect(tag.hex == "0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659")148 }149150 /// RFC 9106, sections 5.1 and 5.2.151 @Test func rfc9106Argon2dAndArgon2i() throws {152 let d = try Argon2.hash(.d, password: Self.password, salt: Self.salt, parameters: Self.rfcParameters, secret: Self.secret, associatedData: Self.associatedData)153 #expect(d.hex == "512b391b6f1162975371d30919734294f868e3be3984f3c1a13a4db9fabe4acb")154 let i = try Argon2.hash(.i, password: Self.password, salt: Self.salt, parameters: Self.rfcParameters, secret: Self.secret, associatedData: Self.associatedData)155 #expect(i.hex == "c814d9d1dc7f37aa13f0d77f2494bda1c8de6b016dd388d29952a4c4672b6ce8")156 }157158 struct Reference: Sendable, CustomStringConvertible {159 let variant: Argon2.Variant, t: Int, m: Int, p: Int, tag: String160 var description: String { "\(variant) t=\(t) m=\(m) p=\(p) T=\(tag.count / 2)" }161 }162163 /// Other shapes (one lane, memory not a multiple of 4p, long and short tags), values produced by the164 /// reference implementation (phc-winner-argon2 through argon2-cffi 25.1.0) on 2026-12-04.165 static let references: [Reference] = [166 Reference(variant: .id, t: 2, m: 64, p: 1,167 tag: "84a3fc9a71a8f33f57f6b7e55b79635a95e4735be7221e3eb8b7e24d6e1af720364b8e527837345d20616cfac96ac7717e19627d0510632db03c8858d33486ab"),168 Reference(variant: .id, t: 1, m: 8, p: 1, tag: "cef8715e"),169 Reference(variant: .id, t: 3, m: 37, p: 3,170 tag: "f98e94eecb5b527b37296a7819c0c8c8b4dc14efdab94c965dc2e959e2f378c220dac1e3baa361bf664a73988dbdb2d57a27eda6d4a36c8ad253e1485fb9243382b1036dc0791e563b8aa9179d6f77baa3f780722bffdb3f59736c18b11339d15d15cd5c"),171 Reference(variant: .id, t: 2, m: 1024, p: 2, tag: "dd7d3277756b62b3f5c953ee765d4dbc13d0dde67f6390920749eb398d933258"),172 Reference(variant: .i, t: 1, m: 250, p: 5,173 tag: "9fceece2463b927bbf0d196f0be17e5b64866e1b0dba69e1e656eb5049392d30460b0c0f2b30b6fbb5c8eb9efe98d0143741c5ddaaa72bbea30487a915a5508da7"),174 Reference(variant: .d, t: 2, m: 99, p: 4, tag: "5b9d435131b4a7401c5d18ba2f807b288b6d0aac184405fca7443bed541a7373c3"),175 ]176177 @Test(arguments: references) func referenceImplementationValues(_ r: Reference) throws {178 let tag = try Argon2.hash(179 r.variant, password: Array("correct horse battery staple".utf8), salt: Array("qyvora-salt-0001".utf8),180 parameters: Argon2.Parameters(memoryKiB: r.m, iterations: r.t, parallelism: r.p, tagLength: r.tag.count / 2))181 #expect(tag.hex == r.tag)182 }183184 /// RFC 9106 second recommended option (64 MiB, t = 3 replaced by t = 1 here to bound the run time);185 /// optimized builds only, the debug build is too slow for 64 MiB.186 @Test(.enabled(if: optimizedBuild)) func sixtyFourMebibytes() throws {187 let tag = try Argon2.id(188 password: Array("correct horse battery staple".utf8), salt: Array("qyvora-salt-0001".utf8),189 parameters: Argon2.Parameters(memoryKiB: 65536, iterations: 1, parallelism: 4, tagLength: 32))190 #expect(tag.hex == "545710c1b803f2a9b6db56afc1274c08ada40e42cabeaf409e144cd731c5807b")191 }192193 @Test func inputsAreAllBound() throws {194 let p = Argon2.Parameters(memoryKiB: 64, iterations: 1, parallelism: 2, tagLength: 32)195 let base = try Argon2.id(password: Self.password, salt: Self.salt, parameters: p)196 #expect(try Argon2.id(password: Self.password, salt: Self.salt, parameters: p) == base)197 #expect(try Argon2.id(password: Self.password + [0], salt: Self.salt, parameters: p) != base)198 #expect(try Argon2.id(password: Self.password, salt: Self.salt + [0], parameters: p) != base)199 #expect(try Argon2.id(password: Self.password, salt: Self.salt, parameters: p, secret: [0]) != base)200 #expect(try Argon2.id(password: Self.password, salt: Self.salt, parameters: p, associatedData: [0]) != base)201 #expect(try Argon2.hash(.i, password: Self.password, salt: Self.salt, parameters: p) != base)202 var q = p203 q.iterations = 2204 #expect(try Argon2.id(password: Self.password, salt: Self.salt, parameters: q) != base)205 q = p206 q.memoryKiB = 65207 #expect(try Argon2.id(password: Self.password, salt: Self.salt, parameters: q) != base)208 q = p209 q.parallelism = 1210 #expect(try Argon2.id(password: Self.password, salt: Self.salt, parameters: q) != base)211 q = p212 q.tagLength = 33213 #expect(try Bytes(Argon2.id(password: Self.password, salt: Self.salt, parameters: q).prefix(32)) != base)214 // empty password is valid215 #expect(try Argon2.id(password: [], salt: Self.salt, parameters: p).count == 32)216 }217218 @Test func parameterValidation() {219 func attempt(_ p: Argon2.Parameters, salt: Bytes = Argon2Tests.salt) -> Argon2.ParameterError? {220 do {221 _ = try Argon2.id(password: [1], salt: salt, parameters: p)222 return nil223 } catch {224 return error as? Argon2.ParameterError225 }226 }227 #expect(attempt(.init(memoryKiB: 64, iterations: 1, parallelism: 0)) == .invalidParallelism)228 #expect(attempt(.init(memoryKiB: 64, iterations: 1, parallelism: 1 << 24)) == .invalidParallelism)229 #expect(attempt(.init(memoryKiB: 7, iterations: 1, parallelism: 1)) == .invalidMemory)230 #expect(attempt(.init(memoryKiB: 31, iterations: 1, parallelism: 4)) == .invalidMemory)231 #expect(attempt(.init(memoryKiB: 64, iterations: 0, parallelism: 1)) == .invalidIterations)232 #expect(attempt(.init(memoryKiB: 64, iterations: 1, parallelism: 1, tagLength: 3)) == .invalidTagLength)233 #expect(attempt(.init(memoryKiB: 64, iterations: 1, parallelism: 1), salt: Bytes(repeating: 0, count: 7)) == .saltTooShort)234 #expect(attempt(.init(memoryKiB: -5, iterations: 1, parallelism: 1)) == .invalidMemory)235 #expect(attempt(.init(memoryKiB: 64, iterations: 1, parallelism: 1, tagLength: 4)) == nil)236 #expect(Argon2.Parameters.rfc9106LowMemory == Argon2.Parameters(memoryKiB: 65536, iterations: 3, parallelism: 4, tagLength: 32))237 #expect(Argon2.Parameters.rfc9106HighMemory.memoryKiB == 2 * 1024 * 1024)238 }239}240