SPB Git

Repository Public

Argon2.swift 14.8 KB 348 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSymmetric/Argon2.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 Foundation42import QyvoraMath4344/// Argon2 memory-hard password hashing (RFC 9106), version 0x13.45///46/// Argon2id is the variant to use (`Argon2.id`); Argon2d and Argon2i are provided for the47/// RFC test vectors and interoperability. Lanes are filled sequentially: the result is the same as a48/// multi-threaded implementation, only the wall-clock time differs. The memory matrix is erased before return.49public enum Argon2 {50    public enum Variant: UInt32, Sendable {51        case d = 052        case i = 153        case id = 254    }5556    public enum ParameterError: Error, Equatable, Sendable {57        /// Parallelism must be 1 ... 2^24 - 1.58        case invalidParallelism59        /// Memory must be at least 8 KiB per lane and at most 2^32 - 1 KiB.60        case invalidMemory61        /// At least one pass, at most 2^32 - 1.62        case invalidIterations63        /// Tag length must be 4 ... 2^32 - 1 bytes.64        case invalidTagLength65        /// The salt must be at least 8 bytes (RFC 9106 recommends 16).66        case saltTooShort67        /// An input exceeds 2^32 - 1 bytes.68        case inputTooLong69    }7071    public struct Parameters: Sendable, Equatable {72        /// Memory size m in kibibytes.73        public var memoryKiB: Int74        /// Number of passes t.75        public var iterations: Int76        /// Degree of parallelism p (number of lanes).77        public var parallelism: Int78        /// Tag length T in bytes.79        public var tagLength: Int8081        public init(memoryKiB: Int, iterations: Int, parallelism: Int, tagLength: Int = 32) {82            self.memoryKiB = memoryKiB83            self.iterations = iterations84            self.parallelism = parallelism85            self.tagLength = tagLength86        }8788        /// RFC 9106, section 4, first recommended option: t = 1, p = 4, m = 2 GiB, 256-bit tag.89        public static let rfc9106HighMemory = Parameters(memoryKiB: 1 << 21, iterations: 1, parallelism: 4, tagLength: 32)90        /// RFC 9106, section 4, second recommended option (memory-constrained): t = 3, p = 4, m = 64 MiB, 256-bit tag.91        public static let rfc9106LowMemory = Parameters(memoryKiB: 1 << 16, iterations: 3, parallelism: 4, tagLength: 32)92    }9394    static let version: UInt32 = 0x1395    static let syncPoints = 49697    /// Argon2id with the given parameters.98    public static func id(password: Bytes, salt: Bytes, parameters: Parameters, secret: Bytes = [], associatedData: Bytes = []) throws -> Bytes {99        try hash(.id, password: password, salt: salt, parameters: parameters, secret: secret, associatedData: associatedData)100    }101102    /// Computes the Argon2 tag.103    /// - Parameters:104    ///   - secret: optional key K (pepper).105    ///   - associatedData: optional data X bound to the tag.106    public static func hash(107        _ variant: Variant, password: Bytes, salt: Bytes, parameters: Parameters,108        secret: Bytes = [], associatedData: Bytes = []109    ) throws -> Bytes {110        let dit = DataIndependentTiming.enable()111        defer { DataIndependentTiming.restore(dit) }112        let p = parameters.parallelism, t = parameters.iterations, tagLength = parameters.tagLength113        guard p >= 1, p <= 0xff_ffff else { throw ParameterError.invalidParallelism }114        guard parameters.memoryKiB >= 8 * p, UInt64(parameters.memoryKiB) <= UInt64(UInt32.max) else { throw ParameterError.invalidMemory }115        guard t >= 1, UInt64(t) <= UInt64(UInt32.max) else { throw ParameterError.invalidIterations }116        guard tagLength >= 4, UInt64(tagLength) <= UInt64(UInt32.max) else { throw ParameterError.invalidTagLength }117        guard salt.count >= 8 else { throw ParameterError.saltTooShort }118        let limit = UInt64(UInt32.max)119        guard UInt64(password.count) <= limit, UInt64(salt.count) <= limit,120              UInt64(secret.count) <= limit, UInt64(associatedData.count) <= limit else { throw ParameterError.inputTooLong }121122        // H0 (RFC 9106, section 3.2, step 1)123        var pre = BLAKE2b(digestSize: 64)124        pre.update(Endian.le32(UInt32(p)) + Endian.le32(UInt32(tagLength)) + Endian.le32(UInt32(parameters.memoryKiB))125            + Endian.le32(UInt32(t)) + Endian.le32(version) + Endian.le32(variant.rawValue))126        pre.update(Endian.le32(UInt32(password.count)))127        pre.update(password)128        pre.update(Endian.le32(UInt32(salt.count)))129        pre.update(salt)130        pre.update(Endian.le32(UInt32(secret.count)))131        pre.update(secret)132        pre.update(Endian.le32(UInt32(associatedData.count)))133        pre.update(associatedData)134        var h0 = pre.finalize()135136        let segmentLength = parameters.memoryKiB / (4 * p)137        let laneLength = 4 * segmentLength138        let blocks = laneLength * p139        var memory = [UInt64](repeating: 0, count: blocks * 128)140        defer { SecureMemory.zero(&memory) }141142        // First two blocks of every lane (steps 3 and 4)143        for lane in 0..<p {144            for index in 0..<2 {145                var seed = h0 + Endian.le32(UInt32(index)) + Endian.le32(UInt32(lane))146                var block = variableHash(seed, length: 1024)147                let base = (lane * laneLength + index) * 128148                block.withUnsafeBufferPointer { b in149                    for w in 0..<128 { memory[base + w] = Endian.loadLE64(b.baseAddress! + 8 * w) }150                }151                SecureMemory.zero(&seed)152                SecureMemory.zero(&block)153            }154        }155        SecureMemory.zero(&h0)156157        memory.withUnsafeMutableBufferPointer { mem in158            let m = mem.baseAddress!159            withUnsafeTemporaryAllocation(of: UInt64.self, capacity: 128 * 4) { scratch in160                let s = scratch.baseAddress!161                let work = s, input = s + 128, address = s + 256, zero = s + 384162                for pass in 0..<t {163                    for slice in 0..<syncPoints {164                        for lane in 0..<p {165                            fillSegment(166                                m, variant: variant, pass: pass, slice: slice, lane: lane, lanes: p,167                                laneLength: laneLength, segmentLength: segmentLength, passes: t, totalBlocks: blocks,168                                work: work, input: input, address: address, zero: zero)169                        }170                    }171                }172                // memset_s: a plain zeroing loop on scratch memory about to be released may be optimized away173                _ = memset_s(s, 128 * 4 * 8, 0, 128 * 4 * 8)174            }175        }176177        // Final block: XOR of the last column (step 7), then H' (step 8)178        var final = Bytes(repeating: 0, count: 1024)179        for w in 0..<128 {180            var acc: UInt64 = 0181            for lane in 0..<p { acc ^= memory[(lane * laneLength + laneLength - 1) * 128 + w] }182            for b in 0..<8 { final[8 * w + b] = UInt8(truncatingIfNeeded: acc >> UInt64(8 * b)) }183        }184        let tag = variableHash(final, length: tagLength)185        SecureMemory.zero(&final)186        return tag187    }188189    /// Variable-length hash H' (RFC 9106, section 3.3).190    static func variableHash(_ input: Bytes, length: Int) -> Bytes {191        let prefix = Endian.le32(UInt32(length))192        if length <= 64 {193            var b = BLAKE2b(digestSize: length)194            b.update(prefix)195            b.update(input)196            return b.finalize()197        }198        let r = (length + 31) / 32 - 2199        var out = Bytes()200        out.reserveCapacity(length)201        var b = BLAKE2b(digestSize: 64)202        b.update(prefix)203        b.update(input)204        var v = b.finalize()205        out.append(contentsOf: v[0..<32])206        if r >= 2 {207            for _ in 2...r {208                v = BLAKE2b.hash(v, digestSize: 64)209                out.append(contentsOf: v[0..<32])210            }211        }212        var last = BLAKE2b.hash(v, digestSize: length - 32 * r)213        out.append(contentsOf: last)214        SecureMemory.zero(&v)215        SecureMemory.zero(&last)216        return out217    }218219    @inline(__always) private static func rotr(_ x: UInt64, _ n: UInt64) -> UInt64 { (x >> n) | (x << (64 &- n)) }220221    /// BLAKE2b round function with the multiplicative mixing of Argon2 (RFC 9106, section 3.6).222    @inline(__always) private static func gb(_ v: UnsafeMutablePointer<UInt64>, _ a: Int, _ b: Int, _ c: Int, _ d: Int) {223        @inline(__always) func mix(_ x: UInt64, _ y: UInt64) -> UInt64 {224            x &+ y &+ 2 &* (x & 0xffff_ffff) &* (y & 0xffff_ffff)225        }226        v[a] = mix(v[a], v[b]); v[d] = rotr(v[d] ^ v[a], 32)227        v[c] = mix(v[c], v[d]); v[b] = rotr(v[b] ^ v[c], 24)228        v[a] = mix(v[a], v[b]); v[d] = rotr(v[d] ^ v[a], 16)229        v[c] = mix(v[c], v[d]); v[b] = rotr(v[b] ^ v[c], 63)230    }231232    @inline(__always) private static func permute(233        _ v: UnsafeMutablePointer<UInt64>,234        _ i0: Int, _ i1: Int, _ i2: Int, _ i3: Int, _ i4: Int, _ i5: Int, _ i6: Int, _ i7: Int,235        _ i8: Int, _ i9: Int, _ i10: Int, _ i11: Int, _ i12: Int, _ i13: Int, _ i14: Int, _ i15: Int236    ) {237        gb(v, i0, i4, i8, i12)238        gb(v, i1, i5, i9, i13)239        gb(v, i2, i6, i10, i14)240        gb(v, i3, i7, i11, i15)241        gb(v, i0, i5, i10, i15)242        gb(v, i1, i6, i11, i12)243        gb(v, i2, i7, i8, i13)244        gb(v, i3, i4, i9, i14)245    }246247    /// Compression function G (RFC 9106, section 3.5): `out = P(x ^ y) ^ x ^ y`, XORed into `out` when `xorInto`.248    /// `work` is a 128-word scratch block.249    private static func compress(250        _ x: UnsafePointer<UInt64>, _ y: UnsafePointer<UInt64>, into out: UnsafeMutablePointer<UInt64>,251        xorInto: Bool, work r: UnsafeMutablePointer<UInt64>252    ) {253        for i in 0..<128 { r[i] = x[i] ^ y[i] }254        if xorInto {255            for i in 0..<128 { out[i] ^= r[i] }256        } else {257            for i in 0..<128 { out[i] = r[i] }258        }259        for i in 0..<8 {260            let o = 16 * i261            permute(r, o, o + 1, o + 2, o + 3, o + 4, o + 5, o + 6, o + 7, o + 8, o + 9, o + 10, o + 11, o + 12, o + 13, o + 14, o + 15)262        }263        for i in 0..<8 {264            let o = 2 * i265            permute(r, o, o + 1, o + 16, o + 17, o + 32, o + 33, o + 48, o + 49, o + 64, o + 65, o + 80, o + 81, o + 96, o + 97, o + 112, o + 113)266        }267        for i in 0..<128 { out[i] ^= r[i] }268    }269270    private static func fillSegment(271        _ m: UnsafeMutablePointer<UInt64>, variant: Variant, pass: Int, slice: Int, lane: Int, lanes: Int,272        laneLength: Int, segmentLength: Int, passes: Int, totalBlocks: Int,273        work: UnsafeMutablePointer<UInt64>, input: UnsafeMutablePointer<UInt64>,274        address: UnsafeMutablePointer<UInt64>, zero: UnsafeMutablePointer<UInt64>275    ) {276        // Argon2i always, Argon2id in the first half of the first pass: indices do not depend on the password.277        let dataIndependent = variant == .i || (variant == .id && pass == 0 && slice < syncPoints / 2)278279        if dataIndependent {280            for i in 0..<128 {281                input[i] = 0282                zero[i] = 0283            }284            input[0] = UInt64(pass)285            input[1] = UInt64(lane)286            input[2] = UInt64(slice)287            input[3] = UInt64(totalBlocks)288            input[4] = UInt64(passes)289            input[5] = UInt64(variant.rawValue)290        }291292        @inline(__always) func nextAddresses() {293            input[6] &+= 1294            compress(zero, input, into: address, xorInto: false, work: work)295            compress(zero, address, into: address, xorInto: false, work: work)296        }297298        var start = 0299        if pass == 0 && slice == 0 {300            start = 2301            if dataIndependent { nextAddresses() }302        }303304        for i in start..<segmentLength {305            let column = slice * segmentLength + i306            let current = lane * laneLength + column307            let previous = column == 0 ? current + laneLength - 1 : current - 1308309            let pseudoRandom: UInt64310            if dataIndependent {311                if i % 128 == 0 { nextAddresses() }312                pseudoRandom = address[i % 128]313            } else {314                pseudoRandom = m[previous * 128]315            }316            let j1 = pseudoRandom & 0xffff_ffff317            var refLane = Int((pseudoRandom >> 32) % UInt64(lanes))318            if pass == 0 && slice == 0 { refLane = lane }319320            // Size of the reference set (RFC 9106, section 3.4.1.3)321            var area: Int322            if pass == 0 {323                if slice == 0 {324                    area = i - 1325                } else if refLane == lane {326                    area = slice * segmentLength + i - 1327                } else {328                    area = slice * segmentLength + (i == 0 ? -1 : 0)329                }330            } else {331                if refLane == lane {332                    area = laneLength - segmentLength + i - 1333                } else {334                    area = laneLength - segmentLength + (i == 0 ? -1 : 0)335                }336            }337            let x = (j1 &* j1) >> 32338            let y = (UInt64(area) &* x) >> 32339            let relative = area - 1 - Int(y)340            let startPosition = (pass != 0 && slice != syncPoints - 1) ? (slice + 1) * segmentLength : 0341            let refColumn = (startPosition + relative) % laneLength342            let reference = refLane * laneLength + refColumn343344            compress(m + previous * 128, m + reference * 128, into: m + current * 128, xorInto: pass != 0, work: work)345        }346    }347}348
Files main
Menu

Theme