SPB Git

Repository Public

MLKEMArithmetic.swift 18.1 KB 421 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraMLKEM/MLKEMArithmetic.swift8// Module           : Qyvora MLKEM9// 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 QyvoraKeccak42import QyvoraMath4344// FIPS 203 arithmetic layer: the field Z_q with q = 3329, the number-theoretic transform of45// section 4.3, the samplers of section 4.2.2 and the encodings of section 4.2.1.46//47// Polynomials are 256 signed 16-bit coefficients; vectors and matrices are flat buffers of48// 256-coefficient blocks. Products use signed Montgomery reduction (R = 2^16); the invariants on49// coefficient magnitudes are stated next to each routine. Nothing here branches on a secret50// coefficient or indexes memory with one.5152extension MLKEM {53    /// Arithmetic modulo q = 3329.54    public enum Field {55        public static let q: Int16 = 332956        /// q^-1 mod 2^16, as a signed 16-bit value (62209 - 65536).57        @usableFromInline static let qInverse: Int16 = -332758        /// ceil(2^36 / q): exact quotient by q for every numerator below 2^23 (see `compress`).59        @usableFromInline static let divisionMagic: UInt64 = ((1 << 36) + 3328) / 33296061        /// Signed Montgomery reduction: for |a| < q * 2^15 returns a * 2^-16 mod q in (-q, q).62        @inlinable @inline(__always)63        public static func montgomeryReduce(_ a: Int32) -> Int16 {64            let t = Int16(truncatingIfNeeded: a) &* qInverse65            return Int16(truncatingIfNeeded: (a &- Int32(t) &* 3329) >> 16)66        }6768        /// a * b * 2^-16 mod q, in (-q, q).69        @inlinable @inline(__always)70        public static func multiply(_ a: Int16, _ b: Int16) -> Int16 {71            montgomeryReduce(Int32(a) &* Int32(b))72        }7374        /// Centered Barrett reduction: any 16-bit input, output congruent in [-(q-1)/2, (q-1)/2].75        @inlinable @inline(__always)76        public static func barrettReduce(_ a: Int16) -> Int16 {77            let t = Int16(truncatingIfNeeded: (20159 &* Int32(a) &+ (1 << 25)) >> 26)78            return a &- t &* 332979        }8081        /// Canonical representative in [0, q) of any 16-bit input.82        @inlinable @inline(__always)83        public static func canonical(_ a: Int16) -> Int16 {84            let r = barrettReduce(a)85            return r &+ ((r >> 15) & 3329)86        }8788        /// Compress_d (FIPS 203, eq. 4.7) of a canonical x in [0, q): round(2^d x / q) mod 2^d.89        ///90        /// Since q is odd, round-half-up of 2^d x / q equals floor((2^d x + 1664) / q). The quotient is91        /// computed by a multiplication and a shift (no division instruction on secret data): with92        /// m = ceil(2^36 / q) and a numerator n < 2^23, n (m q - 2^36) < 2^36, hence93        /// floor(n m / 2^36) = floor(n / q).94        @inlinable @inline(__always)95        public static func compress(_ x: UInt32, bits d: Int) -> UInt32 {96            let n = UInt64((x << UInt32(d)) &+ 1664)97            return UInt32(truncatingIfNeeded: (n &* divisionMagic) >> 36) & ((1 << UInt32(d)) &- 1)98        }99100        /// Decompress_d (FIPS 203, eq. 4.8) of y in [0, 2^d): round(q y / 2^d).101        @inlinable @inline(__always)102        public static func decompress(_ y: UInt32, bits d: Int) -> UInt32 {103            (y &* 3329 &+ (1 << UInt32(d - 1))) >> UInt32(d)104        }105    }106107    /// Number-theoretic transform over Z_q[X] / (X^256 + 1) (FIPS 203, section 4.3).108    public enum NTT {109        /// zetas[i] = 17^BitRev7(i) * 2^16 mod q, centered in (-q/2, q/2] (Montgomery form of the110        /// table of FIPS 203, appendix A).111        public static let zetas: [Int16] = {112            var out = [Int16](repeating: 0, count: 128)113            for i in 0..<128 {114                var reversed = 0115                for b in 0..<7 { reversed |= ((i >> b) & 1) << (6 - b) }116                var v = 1117                for _ in 0..<reversed { v = v * 17 % 3329 }118                v = (v << 16) % 3329119                if v > 1664 { v -= 3329 }120                out[i] = Int16(v)121            }122            return out123        }()124125        /// In-place forward transform (Algorithm 9). Input coefficients bounded by q in absolute126        /// value; output bounded by 8q (each of the 7 layers adds at most q), not reduced.127        public static func forward(_ r: UnsafeMutablePointer<Int16>) {128            zetas.withUnsafeBufferPointer { table in129                let z = table.baseAddress!130                var k = 1131                var len = 128132                while len >= 2 {133                    var start = 0134                    while start < 256 {135                        let zeta = z[k]136                        k &+= 1137                        var j = start138                        let end = start &+ len139                        while j < end {140                            let t = Field.multiply(zeta, r[j &+ len])141                            r[j &+ len] = r[j] &- t142                            r[j] = r[j] &+ t143                            j &+= 1144                        }145                        start = end &+ len146                    }147                    len >>= 1148                }149            }150        }151152        /// In-place inverse transform (Algorithm 10) followed by a multiplication by 2^16153        /// ("to Montgomery"): cancels the 2^-16 factor left by `multiplyAccumulate`.154        /// Input bounded by 8q; output in (-q, q).155        public static func inverseToMontgomery(_ r: UnsafeMutablePointer<Int16>) {156            zetas.withUnsafeBufferPointer { table in157                let z = table.baseAddress!158                var k = 127159                var len = 2160                while len <= 128 {161                    var start = 0162                    while start < 256 {163                        let zeta = z[k]164                        k &-= 1165                        var j = start166                        let end = start &+ len167                        while j < end {168                            let t = r[j]169                            r[j] = Field.barrettReduce(t &+ r[j &+ len])170                            r[j &+ len] = Field.multiply(zeta, r[j &+ len] &- t)171                            j &+= 1172                        }173                        start = end &+ len174                    }175                    len <<= 1176                }177                // 1441 = 2^32 / 128 mod q178                for j in 0..<256 { r[j] = Field.multiply(r[j], 1441) }179            }180        }181182        /// MultiplyNTTs (Algorithm 11) in Montgomery arithmetic: r (+)= a * b * 2^-16.183        /// With `accumulate`, the product is added to r (at most 4 accumulations: |r| < 8q).184        public static func multiplyAccumulate(185            _ r: UnsafeMutablePointer<Int16>, _ a: UnsafePointer<Int16>, _ b: UnsafePointer<Int16>, accumulate: Bool186        ) {187            zetas.withUnsafeBufferPointer { table in188                let z = table.baseAddress!189                if !accumulate {190                    for i in 0..<256 { r[i] = 0 }191                }192                var i = 0193                while i < 64 {194                    let zeta = z[64 &+ i]195                    let o = 4 &* i196                    // (a0 + a1 X)(b0 + b1 X) mod (X^2 - zeta), then the same with -zeta197                    var r0 = Field.multiply(Field.multiply(a[o &+ 1], b[o &+ 1]), zeta)198                    r0 = r0 &+ Field.multiply(a[o], b[o])199                    let r1 = Field.multiply(a[o], b[o &+ 1]) &+ Field.multiply(a[o &+ 1], b[o])200                    r[o] = r[o] &+ r0201                    r[o &+ 1] = r[o &+ 1] &+ r1202                    var s0 = Field.multiply(Field.multiply(a[o &+ 3], b[o &+ 3]), 0 &- zeta)203                    s0 = s0 &+ Field.multiply(a[o &+ 2], b[o &+ 2])204                    let s1 = Field.multiply(a[o &+ 2], b[o &+ 3]) &+ Field.multiply(a[o &+ 3], b[o &+ 2])205                    r[o &+ 2] = r[o &+ 2] &+ s0206                    r[o &+ 3] = r[o &+ 3] &+ s1207                    i &+= 1208                }209            }210        }211212        /// Centered reduction of the 256 coefficients.213        @inline(__always)214        static func reduce(_ r: UnsafeMutablePointer<Int16>) {215            for i in 0..<256 { r[i] = Field.barrettReduce(r[i]) }216        }217218        /// Multiplies the 256 coefficients by 2^16 (1353 = 2^32 mod q).219        @inline(__always)220        static func toMontgomery(_ r: UnsafeMutablePointer<Int16>) {221            for i in 0..<256 { r[i] = Field.montgomeryReduce(Int32(r[i]) &* 1353) }222        }223224        // Specification-level wrappers (canonical coefficients in [0, q), plain domain) for tests225        // and benchmarks.226227        /// NTT (Algorithm 9) of a polynomial with 256 coefficients in [0, q).228        public static func ntt(_ f: [UInt16]) -> [UInt16] {229            precondition(f.count == 256)230            var r = f.map { Int16(truncatingIfNeeded: $0 % 3329) }231            r.withUnsafeMutableBufferPointer { forward($0.baseAddress!) }232            return r.map { UInt16(Field.canonical($0)) }233        }234235        /// NTT^-1 (Algorithm 10).236        public static func inverseNTT(_ f: [UInt16]) -> [UInt16] {237            precondition(f.count == 256)238            var r = f.map { Int16(truncatingIfNeeded: $0 % 3329) }239            r.withUnsafeMutableBufferPointer { inverseToMontgomery($0.baseAddress!) }240            return r.map { UInt16(Field.canonical(Field.montgomeryReduce(Int32($0)))) }241        }242243        /// MultiplyNTTs (Algorithm 11).244        public static func multiplyNTTs(_ f: [UInt16], _ g: [UInt16]) -> [UInt16] {245            precondition(f.count == 256 && g.count == 256)246            let a = f.map { Int16(truncatingIfNeeded: $0 % 3329) }247            let b = g.map { Int16(truncatingIfNeeded: $0 % 3329) }248            var r = [Int16](repeating: 0, count: 256)249            r.withUnsafeMutableBufferPointer { rp in250                a.withUnsafeBufferPointer { ap in251                    b.withUnsafeBufferPointer { bp in252                        multiplyAccumulate(rp.baseAddress!, ap.baseAddress!, bp.baseAddress!, accumulate: false)253                    }254                }255                toMontgomery(rp.baseAddress!)256            }257            return r.map { UInt16(Field.canonical($0)) }258        }259    }260261    // MARK: - Sampling (FIPS 203, section 4.2.2)262263    enum Sampling {264        /// SampleNTT (Algorithm 7): rejection sampling of a uniform element of T_q from265        /// SHAKE128(rho || b0 || b1). The input is public.266        static func sampleNTT(rho: Bytes, _ b0: UInt8, _ b1: UInt8, into r: UnsafeMutablePointer<Int16>) {267            var xof = SHAKE(128)268            xof.absorb(rho)269            xof.absorb([b0, b1])270            // 504 bytes = 3 SHAKE128 blocks = 336 candidates; further blocks keep the 3-byte alignment.271            var buf = Bytes(repeating: 0, count: 504)272            var count = 0273            while count < 256 {274                buf.withUnsafeMutableBufferPointer { b in275                    xof.squeeze(into: b)276                    var i = 0277                    while i < 504 && count < 256 {278                        let d1 = UInt16(b[i]) | (UInt16(b[i + 1]) & 0x0f) << 8279                        let d2 = UInt16(b[i + 1]) >> 4 | UInt16(b[i + 2]) << 4280                        if d1 < 3329 {281                            r[count] = Int16(d1)282                            count += 1283                        }284                        if d2 < 3329 && count < 256 {285                            r[count] = Int16(d2)286                            count += 1287                        }288                        i += 3289                    }290                }291            }292        }293294        /// PRF_eta(s, b) followed by SamplePolyCBD_eta (Algorithm 8). Coefficients in [-eta, eta].295        static func samplePolyCBD(seed: Bytes, nonce: UInt8, eta: Int, into r: UnsafeMutablePointer<Int16>) {296            var xof = SHAKE(256)297            xof.absorb(seed)298            xof.absorb([nonce])299            var buf = xof.squeeze(64 * eta)300            xof.wipe()301            buf.withUnsafeBufferPointer { b in302                if eta == 2 {303                    for i in 0..<32 {304                        let t = Endian.loadLE32(b.baseAddress! + 4 * i)305                        let d = (t & 0x5555_5555) &+ ((t >> 1) & 0x5555_5555)306                        for j in 0..<8 {307                            let x = Int16(truncatingIfNeeded: (d >> UInt32(4 * j)) & 3)308                            let y = Int16(truncatingIfNeeded: (d >> UInt32(4 * j + 2)) & 3)309                            r[8 * i + j] = x &- y310                        }311                    }312                } else {313                    for i in 0..<64 {314                        let t = UInt32(b[3 * i]) | UInt32(b[3 * i + 1]) << 8 | UInt32(b[3 * i + 2]) << 16315                        let d = (t & 0x0024_9249) &+ ((t >> 1) & 0x0024_9249) &+ ((t >> 2) & 0x0024_9249)316                        for j in 0..<4 {317                            let x = Int16(truncatingIfNeeded: (d >> UInt32(6 * j)) & 7)318                            let y = Int16(truncatingIfNeeded: (d >> UInt32(6 * j + 3)) & 7)319                            r[4 * i + j] = x &- y320                        }321                    }322                }323            }324            SecureMemory.zero(&buf)325        }326327        /// The matrix A-hat (or its transpose) of K-PKE: entry (i, j) = SampleNTT(rho || j || i).328        static func expandMatrix(rho: Bytes, k: Int, transposed: Bool) -> [Int16] {329            var a = [Int16](repeating: 0, count: k * k * 256)330            a.withUnsafeMutableBufferPointer { p in331                for i in 0..<k {332                    for j in 0..<k {333                        let dst = p.baseAddress! + (i * k + j) * 256334                        if transposed {335                            sampleNTT(rho: rho, UInt8(i), UInt8(j), into: dst)336                        } else {337                            sampleNTT(rho: rho, UInt8(j), UInt8(i), into: dst)338                        }339                    }340                }341            }342            return a343        }344    }345346    // MARK: - Encodings (FIPS 203, section 4.2.1)347348    enum Coding {349        /// ByteEncode_12 of `count` coefficients (any representative; canonicalized here).350        static func encode12(_ p: UnsafePointer<Int16>, count: Int, into out: inout Bytes) {351            var i = 0352            while i < count {353                let a = UInt16(bitPattern: Field.canonical(p[i]))354                let b = UInt16(bitPattern: Field.canonical(p[i + 1]))355                out.append(UInt8(truncatingIfNeeded: a))356                out.append(UInt8(truncatingIfNeeded: a >> 8 | b << 4))357                out.append(UInt8(truncatingIfNeeded: b >> 4))358                i += 2359            }360        }361362        /// ByteDecode_12 without reduction: coefficients in [0, 4096).363        static func decode12(_ src: UnsafePointer<UInt8>, count: Int, into p: UnsafeMutablePointer<Int16>) {364            var i = 0365            var o = 0366            while i < count {367                let b0 = UInt16(src[o]), b1 = UInt16(src[o + 1]), b2 = UInt16(src[o + 2])368                p[i] = Int16(b0 | (b1 & 0x0f) << 8)369                p[i + 1] = Int16(b1 >> 4 | b2 << 4)370                i += 2371                o += 3372            }373        }374375        /// ByteEncode_d(Compress_d(.)) of `count` coefficients, for d < 12.376        static func compressEncode(_ p: UnsafePointer<Int16>, count: Int, bits d: Int, into out: inout Bytes) {377            var acc: UInt64 = 0378            var filled = 0379            for i in 0..<count {380                let x = UInt32(UInt16(bitPattern: Field.canonical(p[i])))381                acc |= UInt64(Field.compress(x, bits: d)) << UInt64(filled)382                filled += d383                while filled >= 8 {384                    out.append(UInt8(truncatingIfNeeded: acc))385                    acc >>= 8386                    filled -= 8387                }388            }389        }390391        /// Decompress_d(ByteDecode_d(.)) of `count` coefficients, for d < 12. Output in [0, q).392        static func decodeDecompress(_ src: UnsafePointer<UInt8>, count: Int, bits d: Int, into p: UnsafeMutablePointer<Int16>) {393            var acc: UInt64 = 0394            var filled = 0395            var o = 0396            let mask: UInt64 = (1 << UInt64(d)) - 1397            for i in 0..<count {398                while filled < d {399                    acc |= UInt64(src[o]) << UInt64(filled)400                    o += 1401                    filled += 8402                }403                p[i] = Int16(truncatingIfNeeded: Field.decompress(UInt32(truncatingIfNeeded: acc & mask), bits: d))404                acc >>= UInt64(d)405                filled -= d406            }407        }408409        /// Decompress_1(ByteDecode_1(m)): each message bit becomes 0 or ceil(q/2) = 1665, by masking.410        static func messageToPoly(_ m: UnsafePointer<UInt8>, into p: UnsafeMutablePointer<Int16>) {411            for i in 0..<32 {412                let byte = Int16(m[i])413                for j in 0..<8 {414                    let mask = 0 &- ((byte >> Int16(j)) & 1)415                    p[8 * i + j] = mask & 1665416                }417            }418        }419    }420}421
Files main
Menu

Theme