SPB Git

Repository Public

AES.swift 11.2 KB 262 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSymmetric/AES.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/// Errors of the symmetric ciphers and AEAD constructions.44public enum SymmetricCipherError: Error, Equatable, Sendable {45    case invalidKeyLength46    case invalidNonceLength47    case invalidTagLength48    case invalidBlockLength49    /// The message exceeds what the mode can protect under one key and nonce.50    case messageTooLong51    /// The input is shorter than a nonce plus a tag.52    case truncatedInput53    /// Tag verification failed: the ciphertext, the tag, the associated data, the nonce or the key is wrong.54    /// No plaintext is released.55    case authenticationFailed56}5758/// AES block cipher (FIPS 197) with 128, 192 or 256-bit keys, written without any table lookup.59///60/// The state is held in two 64-bit words (eight bytes each, column-major) and every step is a fixed61/// sequence of word operations: the S-box is computed algebraically (inversion in GF(2^8) as x^254, then62/// the affine map) on all bytes in parallel, so no memory index and no branch depends on the key or the data.63/// This trades speed for a simple constant-time structure (see the module notes on residual risks:64/// the Swift compiler gives no formal constant-time guarantee).65public struct AES: Sendable {66    public static let blockSize = 166768    /// Round keys, two words per round.69    var roundKeys: [UInt64]70    let rounds: Int7172    /// `key` must be 16, 24 or 32 bytes.73    public init(key: Bytes) throws {74        guard key.count == 16 || key.count == 24 || key.count == 32 else { throw SymmetricCipherError.invalidKeyLength }75        let nk = key.count / 476        rounds = nk + 677        var w = [UInt32](repeating: 0, count: 4 * (rounds + 1))78        key.withUnsafeBufferPointer { k in79            for i in 0..<nk { w[i] = Endian.loadLE32(k.baseAddress! + 4 * i) }80        }81        var rcon: UInt32 = 182        for i in nk..<w.count {83            var temp = w[i - 1]84            if i % nk == 0 {85                // RotWord, SubWord, round constant (bytes are in little-endian order inside the word)86                temp = (temp >> 8) | (temp << 24)87                temp = UInt32(truncatingIfNeeded: Self.subBytes(UInt64(temp))) ^ rcon88                rcon = (rcon << 1) ^ ((rcon >> 7) &* 0x11b)89            } else if nk > 6 && i % nk == 4 {90                temp = UInt32(truncatingIfNeeded: Self.subBytes(UInt64(temp)))91            }92            w[i] = w[i - nk] ^ temp93        }94        roundKeys = [UInt64](repeating: 0, count: 2 * (rounds + 1))95        for r in 0...rounds {96            roundKeys[2 * r] = UInt64(w[4 * r]) | UInt64(w[4 * r + 1]) << 3297            roundKeys[2 * r + 1] = UInt64(w[4 * r + 2]) | UInt64(w[4 * r + 3]) << 3298        }99        SecureMemory.zero(&w)100    }101102    /// Erases the round keys. The instance must not be used afterwards.103    public mutating func wipe() { SecureMemory.zero(&roundKeys) }104105    /// Encrypts one 16-byte block.106    public func encryptBlock(_ block: Bytes) throws -> Bytes {107        guard block.count == 16 else { throw SymmetricCipherError.invalidBlockLength }108        let (lo, hi) = block.withUnsafeBufferPointer { (Endian.loadLE64($0.baseAddress!), Endian.loadLE64($0.baseAddress! + 8)) }109        let (a, b) = encrypt(lo, hi)110        return Endian.le64(a) + Endian.le64(b)111    }112113    /// Decrypts one 16-byte block.114    public func decryptBlock(_ block: Bytes) throws -> Bytes {115        guard block.count == 16 else { throw SymmetricCipherError.invalidBlockLength }116        let (lo, hi) = block.withUnsafeBufferPointer { (Endian.loadLE64($0.baseAddress!), Endian.loadLE64($0.baseAddress! + 8)) }117        let (a, b) = decrypt(lo, hi)118        return Endian.le64(a) + Endian.le64(b)119    }120121    // MARK: - Word-level cipher (state byte i = 4 * column + row; `lo` holds bytes 0...7)122123    func encrypt(_ lo: UInt64, _ hi: UInt64) -> (UInt64, UInt64) {124        roundKeys.withUnsafeBufferPointer { rk in125            var a = lo ^ rk[0], b = hi ^ rk[1]126            for r in 1..<rounds {127                a = Self.subBytes(a)128                b = Self.subBytes(b)129                (a, b) = Self.shiftRows(a, b)130                a = Self.mixColumns(a) ^ rk[2 * r]131                b = Self.mixColumns(b) ^ rk[2 * r + 1]132            }133            a = Self.subBytes(a)134            b = Self.subBytes(b)135            (a, b) = Self.shiftRows(a, b)136            return (a ^ rk[2 * rounds], b ^ rk[2 * rounds + 1])137        }138    }139140    func decrypt(_ lo: UInt64, _ hi: UInt64) -> (UInt64, UInt64) {141        roundKeys.withUnsafeBufferPointer { rk in142            var a = lo ^ rk[2 * rounds], b = hi ^ rk[2 * rounds + 1]143            for r in stride(from: rounds - 1, through: 1, by: -1) {144                (a, b) = Self.invShiftRows(a, b)145                a = Self.invSubBytes(a) ^ rk[2 * r]146                b = Self.invSubBytes(b) ^ rk[2 * r + 1]147                a = Self.invMixColumns(a)148                b = Self.invMixColumns(b)149            }150            (a, b) = Self.invShiftRows(a, b)151            return (Self.invSubBytes(a) ^ rk[0], Self.invSubBytes(b) ^ rk[1])152        }153    }154155    // MARK: - GF(2^8) arithmetic on eight bytes at once (polynomial x^8 + x^4 + x^3 + x + 1)156157    private static let ones: UInt64 = 0x0101_0101_0101_0101158159    /// Multiplication by x of every byte.160    @inline(__always) private static func xtime(_ a: UInt64) -> UInt64 {161        ((a & 0x7f7f_7f7f_7f7f_7f7f) << 1) ^ (((a >> 7) & ones) &* 0x1b)162    }163164    /// Byte-wise product. Fixed eight steps; the multiplier bits are spread into masks, never branched on.165    @inline(__always) private static func multiply(_ x: UInt64, _ y: UInt64) -> UInt64 {166        var a = x167        var r: UInt64 = 0168        for i: UInt64 in 0..<8 {169            r ^= a & (((y >> i) & ones) &* 0xff)170            a = xtime(a)171        }172        return r173    }174175    /// Byte-wise squaring, a linear map: bit i contributes x^(2i) mod the field polynomial.176    @inline(__always) private static func square(_ a: UInt64) -> UInt64 {177        var r = (a & ones)178        r ^= ((a >> 1) & ones) &* 0x04179        r ^= ((a >> 2) & ones) &* 0x10180        r ^= ((a >> 3) & ones) &* 0x40181        r ^= ((a >> 4) & ones) &* 0x1b182        r ^= ((a >> 5) & ones) &* 0x6c183        r ^= ((a >> 6) & ones) &* 0xab184        r ^= ((a >> 7) & ones) &* 0x9a185        return r186    }187188    /// Byte-wise inverse as x^254 (0 maps to 0): 4 multiplications and 7 squarings.189    @inline(__always) private static func inverse(_ x: UInt64) -> UInt64 {190        let x2 = square(x)191        let x3 = multiply(x2, x)192        let x12 = square(square(x3))193        let x15 = multiply(x12, x3)194        let x240 = square(square(square(square(x15))))195        let x252 = multiply(x240, x12)196        return multiply(x252, x2)197    }198199    /// Rotation of every byte to the left by `k` bits (1...7).200    @inline(__always) private static func rotateBytes(_ x: UInt64, _ k: UInt64) -> UInt64 {201        let high = (0xff << k) & 0xff as UInt64202        return ((x << k) & (high &* ones)) | ((x >> (8 - k)) & ((0xff >> (8 - k)) &* ones))203    }204205    /// S-box on eight bytes: inversion then the affine transformation of FIPS 197, section 5.1.1.206    @inline(__always) static func subBytes(_ x: UInt64) -> UInt64 {207        let v = inverse(x)208        return v ^ rotateBytes(v, 1) ^ rotateBytes(v, 2) ^ rotateBytes(v, 3) ^ rotateBytes(v, 4) ^ (0x63 &* ones)209    }210211    /// Inverse S-box: inverse affine transformation then inversion.212    @inline(__always) static func invSubBytes(_ x: UInt64) -> UInt64 {213        inverse(rotateBytes(x, 1) ^ rotateBytes(x, 3) ^ rotateBytes(x, 6) ^ (0x05 &* ones))214    }215216    // Row r of the state occupies byte r of each 32-bit column.217    private static let row0: UInt64 = 0x0000_00ff_0000_00ff218    private static let row1: UInt64 = 0x0000_ff00_0000_ff00219    private static let row2: UInt64 = 0x00ff_0000_00ff_0000220    private static let row3: UInt64 = 0xff00_0000_ff00_0000221222    /// ShiftRows: row r moves r columns to the left (a rotation of the 128-bit state by 32r bits).223    @inline(__always) private static func shiftRows(_ lo: UInt64, _ hi: UInt64) -> (UInt64, UInt64) {224        let down = (lo >> 32) | (hi << 32) // columns 1, 2225        let up = (hi >> 32) | (lo << 32) // columns 3, 0226        return ((lo & row0) | (down & row1) | (hi & row2) | (up & row3),227                (hi & row0) | (up & row1) | (lo & row2) | (down & row3))228    }229230    @inline(__always) private static func invShiftRows(_ lo: UInt64, _ hi: UInt64) -> (UInt64, UInt64) {231        let down = (lo >> 32) | (hi << 32)232        let up = (hi >> 32) | (lo << 32)233        return ((lo & row0) | (up & row1) | (hi & row2) | (down & row3),234                (hi & row0) | (down & row1) | (lo & row2) | (up & row3))235    }236237    /// Rotations of each 32-bit column by one, two or three bytes (byte i receives byte i + k).238    @inline(__always) private static func rotateColumns1(_ x: UInt64) -> UInt64 {239        ((x >> 8) & 0x00ff_ffff_00ff_ffff) | ((x << 24) & 0xff00_0000_ff00_0000)240    }241242    @inline(__always) private static func rotateColumns2(_ x: UInt64) -> UInt64 {243        ((x >> 16) & 0x0000_ffff_0000_ffff) | ((x << 16) & 0xffff_0000_ffff_0000)244    }245246    @inline(__always) private static func rotateColumns3(_ x: UInt64) -> UInt64 {247        ((x >> 24) & 0x0000_00ff_0000_00ff) | ((x << 8) & 0xffff_ff00_ffff_ff00)248    }249250    /// MixColumns: b_i = 2 a_i + 3 a_(i+1) + a_(i+2) + a_(i+3).251    @inline(__always) private static func mixColumns(_ x: UInt64) -> UInt64 {252        let r1 = rotateColumns1(x)253        return xtime(x ^ r1) ^ r1 ^ rotateColumns2(x) ^ rotateColumns3(x)254    }255256    /// InvMixColumns as MixColumns after the preprocessing a_i += 4 (a_i + a_(i+2)).257    @inline(__always) private static func invMixColumns(_ x: UInt64) -> UInt64 {258        let u = xtime(xtime(x ^ rotateColumns2(x)))259        return mixColumns(x ^ u)260    }261}262
Files main
Menu

Theme