SPB Git

Repository Public

AESGCM.swift 13.3 KB 301 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSymmetric/AESGCM.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/// GHASH (NIST SP 800-38D, section 6.4) without secret-dependent table index or branch.44///45/// The 128 multiples H·x^i are precomputed; the table is read in full, in a fixed order, for every46/// block, and each entry is kept or discarded with a mask derived from one bit of the accumulator.47struct GHASH {48    /// H·x^i as (high, low) words, i = 0...127.49    var table: [UInt64]50    var yHigh: UInt64 = 051    var yLow: UInt64 = 05253    init(hHigh: UInt64, hLow: UInt64) {54        table = [UInt64](repeating: 0, count: 256)55        var vh = hHigh, vl = hLow56        for i in 0..<128 {57            table[2 * i] = vh58            table[2 * i + 1] = vl59            // multiply by x: shift right (bit 0 is the most significant), reduce with R = 0xe1 || 0^12060            let carry = 0 &- (vl & 1)61            vl = (vl >> 1) | (vh << 63)62            vh = (vh >> 1) ^ (0xe100_0000_0000_0000 & carry)63        }64    }6566    /// Y = (Y xor X) · H67    @inline(__always) mutating func update(_ xHigh: UInt64, _ xLow: UInt64) {68        let a = yHigh ^ xHigh, b = yLow ^ xLow69        var zh: UInt64 = 0, zl: UInt64 = 070        table.withUnsafeBufferPointer { t in71            for i in 0..<64 {72                let m = 0 &- ((a >> UInt64(63 - i)) & 1)73                zh ^= t[2 * i] & m74                zl ^= t[2 * i + 1] & m75            }76            for i in 0..<64 {77                let m = 0 &- ((b >> UInt64(63 - i)) & 1)78                zh ^= t[128 + 2 * i] & m79                zl ^= t[129 + 2 * i] & m80            }81        }82        yHigh = zh83        yLow = zl84    }8586    /// Absorbs `data`, zero-padded to a multiple of 16 bytes.87    mutating func update(padded data: Bytes) {88        let n = data.count89        data.withUnsafeBufferPointer { d in90            var i = 091            while n - i >= 16 {92                update(Endian.loadBE64(d.baseAddress! + i), Endian.loadBE64(d.baseAddress! + i + 8))93                i += 1694            }95            if i < n {96                var hi: UInt64 = 0, lo: UInt64 = 097                for j in 0..<(n - i) {98                    let byte = UInt64(d[i + j])99                    if j < 8 { hi |= byte << UInt64(56 - 8 * j) } else { lo |= byte << UInt64(56 - 8 * (j - 8)) }100                }101                update(hi, lo)102            }103        }104    }105106    mutating func wipe() {107        SecureMemory.zero(&table)108        yHigh = 0109        yLow = 0110    }111}112113/// AES in Galois/Counter Mode (NIST SP 800-38D) with 128-bit tags.114///115/// The public interface requires the recommended 96-bit nonce. A nonce must never be used twice with116/// the same key. Decryption verifies the tag in constant time before any plaintext is produced.117public struct AESGCM: Sendable {118    public static let nonceSize = 12119    public static let tagSize = 16120    /// Largest plaintext in bytes for one (key, nonce): 2^36 - 32 (SP 800-38D, section 5.2.1.1).121    public static let maxPlaintextSize: UInt64 = (1 << 36) - 32122123    var aes: AES124    var hHigh: UInt64125    var hLow: UInt64126127    /// `key` must be 16, 24 or 32 bytes (AES-128, AES-192, AES-256).128    public init(key: Bytes) throws {129        aes = try AES(key: key)130        let (a, b) = aes.encrypt(0, 0)131        hHigh = a.byteSwapped132        hLow = b.byteSwapped133    }134135    /// Erases the key schedule and the hash subkey. The instance must not be used afterwards.136    public mutating func wipe() {137        aes.wipe()138        hHigh = 0139        hLow = 0140    }141142    /// Encrypts and authenticates. Returns the ciphertext (same length as the plaintext) and the 16-byte tag.143    public func seal(nonce: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> (ciphertext: Bytes, tag: Bytes) {144        let dit = DataIndependentTiming.enable()145        defer { DataIndependentTiming.restore(dit) }146        guard nonce.count == Self.nonceSize else { throw SymmetricCipherError.invalidNonceLength }147        return try sealAnyNonce(nonce: nonce, plaintext: plaintext, associatedData: associatedData)148    }149150    /// Verifies the tag, then decrypts. Throws `authenticationFailed` without releasing any plaintext otherwise.151    public func open(nonce: Bytes, ciphertext: Bytes, tag: Bytes, associatedData: Bytes = []) throws -> Bytes {152        let dit = DataIndependentTiming.enable()153        defer { DataIndependentTiming.restore(dit) }154        guard nonce.count == Self.nonceSize else { throw SymmetricCipherError.invalidNonceLength }155        return try openAnyNonce(nonce: nonce, ciphertext: ciphertext, tag: tag, associatedData: associatedData)156    }157158    /// `seal` with the result as `ciphertext || tag`.159    public func sealCombined(nonce: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> Bytes {160        let r = try seal(nonce: nonce, plaintext: plaintext, associatedData: associatedData)161        return r.ciphertext + r.tag162    }163164    /// `open` for an input of the form `ciphertext || tag`.165    public func openCombined(nonce: Bytes, combined: Bytes, associatedData: Bytes = []) throws -> Bytes {166        guard combined.count >= Self.tagSize else { throw SymmetricCipherError.truncatedInput }167        let split = combined.count - Self.tagSize168        return try open(nonce: nonce, ciphertext: Bytes(combined[0..<split]), tag: Bytes(combined[split...]), associatedData: associatedData)169    }170171    // MARK: - SP 800-38D with any nonce length (internal: the standard allows it, the public API does not)172173    /// Pre-counter block J0 (SP 800-38D, section 7.1, step 2) as big-endian words.174    func preCounter(_ nonce: Bytes) -> (UInt64, UInt64) {175        if nonce.count == 12 {176            return nonce.withUnsafeBufferPointer { n in177                (Endian.loadBE64(n.baseAddress!), UInt64(Endian.loadBE32(n.baseAddress! + 8)) << 32 | 1)178            }179        }180        var g = GHASH(hHigh: hHigh, hLow: hLow)181        g.update(padded: nonce)182        g.update(0, UInt64(nonce.count) &* 8)183        let j0 = (g.yHigh, g.yLow)184        g.wipe()185        return j0186    }187188    /// Counter-mode keystream XOR starting at inc32(J0).189    func counterMode(_ j0: (UInt64, UInt64), _ input: Bytes) -> Bytes {190        var out = Bytes(repeating: 0, count: input.count)191        let n = input.count192        var counter = UInt32(truncatingIfNeeded: j0.1)193        let lowPrefix = j0.1 & 0xffff_ffff_0000_0000194        let first = j0.0.byteSwapped195        input.withUnsafeBufferPointer { src in196            out.withUnsafeMutableBufferPointer { dst in197                var i = 0198                while i < n {199                    counter &+= 1200                    let (k0, k1) = aes.encrypt(first, (lowPrefix | UInt64(counter)).byteSwapped)201                    if n - i >= 16 {202                        let a = Endian.loadLE64(src.baseAddress! + i) ^ k0203                        let b = Endian.loadLE64(src.baseAddress! + i + 8) ^ k1204                        UnsafeMutableRawPointer(dst.baseAddress! + i).storeBytes(of: a.littleEndian, as: UInt64.self)205                        UnsafeMutableRawPointer(dst.baseAddress! + i + 8).storeBytes(of: b.littleEndian, as: UInt64.self)206                        i += 16207                    } else {208                        for j in 0..<(n - i) {209                            let k = j < 8 ? k0 >> UInt64(8 * j) : k1 >> UInt64(8 * (j - 8))210                            dst[i + j] = src[i + j] ^ UInt8(truncatingIfNeeded: k)211                        }212                        i = n213                    }214                }215            }216        }217        return out218    }219220    func computeTag(_ j0: (UInt64, UInt64), ciphertext: Bytes, associatedData: Bytes) -> Bytes {221        var g = GHASH(hHigh: hHigh, hLow: hLow)222        g.update(padded: associatedData)223        g.update(padded: ciphertext)224        g.update(UInt64(associatedData.count) &* 8, UInt64(ciphertext.count) &* 8)225        let (e0, e1) = aes.encrypt(j0.0.byteSwapped, j0.1.byteSwapped)226        let tag = Endian.be64(g.yHigh ^ e0.byteSwapped) + Endian.be64(g.yLow ^ e1.byteSwapped)227        g.wipe()228        return tag229    }230231    func sealAnyNonce(nonce: Bytes, plaintext: Bytes, associatedData: Bytes) throws -> (ciphertext: Bytes, tag: Bytes) {232        guard !nonce.isEmpty else { throw SymmetricCipherError.invalidNonceLength }233        guard UInt64(plaintext.count) <= Self.maxPlaintextSize else { throw SymmetricCipherError.messageTooLong }234        let j0 = preCounter(nonce)235        let ciphertext = counterMode(j0, plaintext)236        return (ciphertext, computeTag(j0, ciphertext: ciphertext, associatedData: associatedData))237    }238239    func openAnyNonce(nonce: Bytes, ciphertext: Bytes, tag: Bytes, associatedData: Bytes) throws -> Bytes {240        guard !nonce.isEmpty else { throw SymmetricCipherError.invalidNonceLength }241        guard tag.count == Self.tagSize else { throw SymmetricCipherError.invalidTagLength }242        guard UInt64(ciphertext.count) <= Self.maxPlaintextSize else { throw SymmetricCipherError.messageTooLong }243        let j0 = preCounter(nonce)244        var expected = computeTag(j0, ciphertext: ciphertext, associatedData: associatedData)245        defer { SecureMemory.zero(&expected) }246        guard ConstantTime.equal(expected, tag) else { throw SymmetricCipherError.authenticationFailed }247        return counterMode(j0, ciphertext)248    }249}250251/// AES-256-GCM, the authenticated cipher of the QYVORA vault: 32-byte key, 12-byte nonce, 16-byte tag.252public enum AES256GCM {253    public static let keySize = 32254    public static let nonceSize = 12255    public static let tagSize = 16256257    static func cipher(_ key: Bytes) throws -> AESGCM {258        guard key.count == keySize else { throw SymmetricCipherError.invalidKeyLength }259        return try AESGCM(key: key)260    }261262    public static func seal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> (ciphertext: Bytes, tag: Bytes) {263        let dit = DataIndependentTiming.enable()264        defer { DataIndependentTiming.restore(dit) }265        var c = try cipher(key)266        defer { c.wipe() }267        return try c.seal(nonce: nonce, plaintext: plaintext, associatedData: associatedData)268    }269270    public static func open(key: Bytes, nonce: Bytes, ciphertext: Bytes, tag: Bytes, associatedData: Bytes = []) throws -> Bytes {271        let dit = DataIndependentTiming.enable()272        defer { DataIndependentTiming.restore(dit) }273        var c = try cipher(key)274        defer { c.wipe() }275        return try c.open(nonce: nonce, ciphertext: ciphertext, tag: tag, associatedData: associatedData)276    }277278    /// Deterministic sealing with an explicit nonce; output is `nonce || ciphertext || tag`.279    /// The caller guarantees that the nonce is never reused with this key.280    public static func sealInternal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> Bytes {281        let r = try seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: associatedData)282        return nonce + r.ciphertext + r.tag283    }284285    /// Sealing with a fresh random 96-bit nonce from `SystemRandom`; output is `nonce || ciphertext || tag`.286    /// With random nonces, one key must not seal more than 2^32 messages (SP 800-38D, section 8.3).287    public static func seal(key: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> Bytes {288        try sealInternal(key: key, nonce: SystemRandom.bytes(nonceSize), plaintext: plaintext, associatedData: associatedData)289    }290291    /// Opens `nonce || ciphertext || tag`.292    public static func open(key: Bytes, sealed: Bytes, associatedData: Bytes = []) throws -> Bytes {293        guard key.count == keySize else { throw SymmetricCipherError.invalidKeyLength }294        guard sealed.count >= nonceSize + tagSize else { throw SymmetricCipherError.truncatedInput }295        let end = sealed.count - tagSize296        return try open(297            key: key, nonce: Bytes(sealed[0..<nonceSize]), ciphertext: Bytes(sealed[nonceSize..<end]),298            tag: Bytes(sealed[end...]), associatedData: associatedData)299    }300}301
Files main
Menu

Theme