SPB Git

Repository Public

MLKEM.swift 20.3 KB 449 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraMLKEM/MLKEM.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/// ML-KEM, the module-lattice key-encapsulation mechanism of FIPS 203 (August 2024),45/// written from the standard: K-PKE (section 5), the internal algorithms (section 6) and the46/// checked external interface (section 7).47public enum MLKEM {48    /// Size in bytes of the shared secret, of each seed (d, z) and of the encapsulation randomness m.49    public static let sharedSecretSize = 3250    public static let seedSize = 325152    public enum ParameterSet: Sendable, CaseIterable, Equatable {53        case mlkem512, mlkem768, mlkem10245455        /// Module rank k.56        public var k: Int {57            switch self {58            case .mlkem512: return 259            case .mlkem768: return 360            case .mlkem1024: return 461            }62        }6364        var eta1: Int { self == .mlkem512 ? 3 : 2 }65        var eta2: Int { 2 }66        var du: Int { self == .mlkem1024 ? 11 : 10 }67        var dv: Int { self == .mlkem1024 ? 5 : 4 }6869        /// Encapsulation (public) key size: 384k + 32 bytes.70        public var encapsulationKeySize: Int { 384 * k + 32 }71        /// Decapsulation (private) key size: 768k + 96 bytes.72        public var decapsulationKeySize: Int { 768 * k + 96 }73        /// Ciphertext size: 32 (du k + dv) bytes.74        public var ciphertextSize: Int { 32 * (du * k + dv) }75        public var sharedSecretSize: Int { 32 }76        public var publicKeySize: Int { encapsulationKeySize }77        public var privateKeySize: Int { decapsulationKeySize }7879        public var name: String {80            switch self {81            case .mlkem512: return "ML-KEM-512"82            case .mlkem768: return "ML-KEM-768"83            case .mlkem1024: return "ML-KEM-1024"84            }85        }86    }8788    public enum Error: Swift.Error, Equatable, Sendable {89        /// A seed or the encapsulation randomness is not 32 bytes long.90        case invalidSeedLength91        /// Encapsulation key of the wrong length (FIPS 203, section 7.2, type check).92        case invalidEncapsulationKeyLength93        /// Encapsulation key holding a coefficient outside [0, q) (section 7.2, modulus check).94        case invalidEncapsulationKey95        /// Decapsulation key of the wrong length (section 7.3, type check).96        case invalidDecapsulationKeyLength97        /// Decapsulation key whose embedded hash does not match its encapsulation key (section 7.3, hash check).98        case invalidDecapsulationKey99        /// Ciphertext of the wrong length (section 7.3, type check).100        case invalidCiphertextLength101    }102103    public struct KeyPair: Sendable, Equatable {104        public let encapsulationKey: Bytes105        public let decapsulationKey: Bytes106    }107108    public struct Encapsulation: Sendable, Equatable {109        public let sharedSecret: Bytes110        public let ciphertext: Bytes111    }112113    // MARK: - External interface (FIPS 203, section 7)114115    /// ML-KEM.KeyGen (Algorithm 19): fresh seeds d and z from the system generator.116    public static func generateKeyPair(_ parameters: ParameterSet) -> KeyPair {117        var d = SystemRandom.bytes(32)118        var z = SystemRandom.bytes(32)119        defer {120            SecureMemory.zero(&d)121            SecureMemory.zero(&z)122        }123        return keyGenCore(parameters, d: d, z: z)124    }125126    /// ML-KEM.Encaps (Algorithm 20): checks the encapsulation key (type and modulus), then127    /// encapsulates with fresh randomness.128    public static func encapsulate(_ parameters: ParameterSet, encapsulationKey: Bytes) throws(Error) -> Encapsulation {129        try validateEncapsulationKey(parameters, encapsulationKey)130        var m = SystemRandom.bytes(32)131        defer { SecureMemory.zero(&m) }132        return encapsCore(parameters, ek: encapsulationKey, m: m)133    }134135    /// ML-KEM.Decaps (Algorithm 21): checks the ciphertext length and the decapsulation key136    /// (length and hash), then decapsulates. A well-formed but invalid ciphertext does not fail:137    /// it yields the implicit-rejection secret.138    public static func decapsulate(_ parameters: ParameterSet, decapsulationKey: Bytes, ciphertext: Bytes) throws(Error) -> Bytes {139        guard ciphertext.count == parameters.ciphertextSize else { throw .invalidCiphertextLength }140        try validateDecapsulationKey(parameters, decapsulationKey)141        return decapsCore(parameters, dk: decapsulationKey, c: ciphertext)142    }143144    /// Encapsulation key check of section 7.2: length, then ByteEncode12(ByteDecode12(ek)) = ek.145    public static func validateEncapsulationKey(_ parameters: ParameterSet, _ ek: Bytes) throws(Error) {146        guard ek.count == parameters.encapsulationKeySize else { throw .invalidEncapsulationKeyLength }147        // The key is public: a data-dependent exit is acceptable, but none is needed.148        var bad: UInt32 = 0149        var i = 0150        let n = 384 * parameters.k151        while i < n {152            let b0 = UInt32(ek[i]), b1 = UInt32(ek[i + 1]), b2 = UInt32(ek[i + 2])153            let c0 = b0 | (b1 & 0x0f) << 8154            let c1 = b1 >> 4 | b2 << 4155            // (3328 - c) has its sign bit set exactly when c >= q156            bad |= (3328 &- c0) >> 31157            bad |= (3328 &- c1) >> 31158            i += 3159        }160        guard bad == 0 else { throw .invalidEncapsulationKey }161    }162163    /// Decapsulation key check of section 7.3: length, then H(ek) equals the embedded hash.164    public static func validateDecapsulationKey(_ parameters: ParameterSet, _ dk: Bytes) throws(Error) {165        guard dk.count == parameters.decapsulationKeySize else { throw .invalidDecapsulationKeyLength }166        let k = parameters.k167        let h = SHA3.sha3_256(Array(dk[(384 * k)..<(768 * k + 32)]))168        guard ConstantTime.equal(h, Array(dk[(768 * k + 32)..<(768 * k + 64)])) else { throw .invalidDecapsulationKey }169    }170171    public static func isValidEncapsulationKey(_ parameters: ParameterSet, _ ek: Bytes) -> Bool {172        (try? validateEncapsulationKey(parameters, ek)) != nil173    }174175    public static func isValidDecapsulationKey(_ parameters: ParameterSet, _ dk: Bytes) -> Bool {176        (try? validateDecapsulationKey(parameters, dk)) != nil177    }178179    // MARK: - Internal (deterministic) interface (FIPS 203, section 6)180181    /// ML-KEM.KeyGen_internal(d, z) (Algorithm 16).182    public static func keyGenInternal(_ parameters: ParameterSet, d: Bytes, z: Bytes) throws(Error) -> KeyPair {183        guard d.count == 32, z.count == 32 else { throw .invalidSeedLength }184        return keyGenCore(parameters, d: d, z: z)185    }186187    /// Key pair from the 64-byte seed d || z (the "seed" private-key format of other libraries).188    public static func keyPair(_ parameters: ParameterSet, seed: Bytes) throws(Error) -> KeyPair {189        guard seed.count == 64 else { throw .invalidSeedLength }190        var d = Array(seed[0..<32]), z = Array(seed[32..<64])191        defer {192            SecureMemory.zero(&d)193            SecureMemory.zero(&z)194        }195        return keyGenCore(parameters, d: d, z: z)196    }197198    /// ML-KEM.Encaps_internal(ek, m) (Algorithm 17). Only the lengths are checked here; the199    /// modulus check belongs to `encapsulate`.200    public static func encapsInternal(_ parameters: ParameterSet, encapsulationKey: Bytes, m: Bytes) throws(Error) -> Encapsulation {201        guard encapsulationKey.count == parameters.encapsulationKeySize else { throw .invalidEncapsulationKeyLength }202        guard m.count == 32 else { throw .invalidSeedLength }203        return encapsCore(parameters, ek: encapsulationKey, m: m)204    }205206    /// ML-KEM.Decaps_internal(dk, c) (Algorithm 18). Only the lengths are checked here; the hash207    /// check belongs to `decapsulate`.208    public static func decapsInternal(_ parameters: ParameterSet, decapsulationKey: Bytes, ciphertext: Bytes) throws(Error) -> Bytes {209        guard decapsulationKey.count == parameters.decapsulationKeySize else { throw .invalidDecapsulationKeyLength }210        guard ciphertext.count == parameters.ciphertextSize else { throw .invalidCiphertextLength }211        return decapsCore(parameters, dk: decapsulationKey, c: ciphertext)212    }213214    // MARK: - ML-KEM core215216    static func keyGenCore(_ ps: ParameterSet, d: Bytes, z: Bytes) -> KeyPair {217        let dit = DataIndependentTiming.enable()218        defer { DataIndependentTiming.restore(dit) }219        var (ek, dkPKE) = pkeKeyGen(ps, d: d)220        var dk = Bytes()221        dk.reserveCapacity(ps.decapsulationKeySize)222        dk += dkPKE223        dk += ek224        dk += SHA3.sha3_256(ek)225        dk += z226        SecureMemory.zero(&dkPKE)227        return KeyPair(encapsulationKey: ek, decapsulationKey: dk)228    }229230    static func encapsCore(_ ps: ParameterSet, ek: Bytes, m: Bytes) -> Encapsulation {231        let dit = DataIndependentTiming.enable()232        defer { DataIndependentTiming.restore(dit) }233        var gInput = m + SHA3.sha3_256(ek)234        var g = SHA3.sha3_512(gInput)235        SecureMemory.zero(&gInput)236        var r = Array(g[32..<64])237        let key = Array(g[0..<32])238        let c = pkeEncrypt(ps, ek: ek, ekOffset: 0, m: m, r: r)239        SecureMemory.zero(&g)240        SecureMemory.zero(&r)241        return Encapsulation(sharedSecret: key, ciphertext: c)242    }243244    static func decapsCore(_ ps: ParameterSet, dk: Bytes, c: Bytes) -> Bytes {245        let dit = DataIndependentTiming.enable()246        defer { DataIndependentTiming.restore(dit) }247        let k = ps.k248        var mPrime = pkeDecrypt(ps, dk: dk, c: c)249        // (K', r') = G(m' || h)250        var gInput = mPrime251        gInput += dk[(768 * k + 32)..<(768 * k + 64)]252        var g = SHA3.sha3_512(gInput)253        var kPrime = Array(g[0..<32])254        var rPrime = Array(g[32..<64])255        // K-bar = J(z || c)256        var jInput = Array(dk[(768 * k + 64)..<(768 * k + 96)])257        jInput += c258        var kBar = SHAKE.shake256(jInput, outputLength: 32)259        let cPrime = pkeEncrypt(ps, ek: dk, ekOffset: 384 * k, m: mPrime, r: rPrime)260        // Implicit rejection without a branch: accumulate the difference, turn it into a mask,261        // select K' (equal) or K-bar (different) byte by byte.262        var diff: UInt8 = 0263        for i in 0..<c.count { diff |= c[i] ^ cPrime[i] }264        let equalMask = ConstantTime.isZeroMask(diff)265        let out = ConstantTime.select(mask: equalMask, kPrime, kBar)266        SecureMemory.zero(&mPrime)267        SecureMemory.zero(&gInput)268        SecureMemory.zero(&g)269        SecureMemory.zero(&kPrime)270        SecureMemory.zero(&rPrime)271        SecureMemory.zero(&jInput)272        SecureMemory.zero(&kBar)273        return out274    }275276    // MARK: - K-PKE (FIPS 203, section 5)277278    /// K-PKE.KeyGen (Algorithm 13).279    static func pkeKeyGen(_ ps: ParameterSet, d: Bytes) -> (ek: Bytes, dk: Bytes) {280        let k = ps.k281        var gInput = d + [UInt8(k)]282        var g = SHA3.sha3_512(gInput)283        SecureMemory.zero(&gInput)284        let rho = Array(g[0..<32])285        var sigma = Array(g[32..<64])286        let a = Sampling.expandMatrix(rho: rho, k: k, transposed: false)287        var s = [Int16](repeating: 0, count: k * 256)288        var e = [Int16](repeating: 0, count: k * 256)289        var t = [Int16](repeating: 0, count: k * 256)290        var ek = Bytes()291        ek.reserveCapacity(ps.encapsulationKeySize)292        var dk = Bytes()293        dk.reserveCapacity(384 * k)294        a.withUnsafeBufferPointer { ap in295            s.withUnsafeMutableBufferPointer { sp in296                e.withUnsafeMutableBufferPointer { ep in297                    t.withUnsafeMutableBufferPointer { tp in298                        let A = ap.baseAddress!, S = sp.baseAddress!, E = ep.baseAddress!, T = tp.baseAddress!299                        for i in 0..<k {300                            Sampling.samplePolyCBD(seed: sigma, nonce: UInt8(i), eta: ps.eta1, into: S + 256 * i)301                            Sampling.samplePolyCBD(seed: sigma, nonce: UInt8(k + i), eta: ps.eta1, into: E + 256 * i)302                        }303                        for i in 0..<k {304                            NTT.forward(S + 256 * i)305                            NTT.reduce(S + 256 * i)306                            NTT.forward(E + 256 * i)307                        }308                        // t-hat = A-hat o s-hat + e-hat309                        for i in 0..<k {310                            let ti = T + 256 * i311                            for j in 0..<k {312                                NTT.multiplyAccumulate(ti, A + (i * k + j) * 256, S + 256 * j, accumulate: j > 0)313                            }314                            NTT.reduce(ti)315                            NTT.toMontgomery(ti)316                            let ei = E + 256 * i317                            for c in 0..<256 { ti[c] = ti[c] &+ Field.barrettReduce(ei[c]) }318                        }319                        Coding.encode12(T, count: 256 * k, into: &ek)320                        Coding.encode12(S, count: 256 * k, into: &dk)321                    }322                }323            }324        }325        ek += rho326        SecureMemory.zero(&s)327        SecureMemory.zero(&e)328        SecureMemory.zero(&sigma)329        SecureMemory.zero(&g)330        return (ek, dk)331    }332333    /// K-PKE.Encrypt (Algorithm 14). The encapsulation key is read at `ekOffset` of `ek`334    /// (it sits inside the decapsulation key during decapsulation).335    static func pkeEncrypt(_ ps: ParameterSet, ek: Bytes, ekOffset: Int, m: Bytes, r: Bytes) -> Bytes {336        let k = ps.k337        let rho = Array(ek[(ekOffset + 384 * k)..<(ekOffset + 384 * k + 32)])338        let at = Sampling.expandMatrix(rho: rho, k: k, transposed: true)339        var tHat = [Int16](repeating: 0, count: k * 256)340        var y = [Int16](repeating: 0, count: k * 256)341        var e1 = [Int16](repeating: 0, count: k * 256)342        var e2 = [Int16](repeating: 0, count: 256)343        var u = [Int16](repeating: 0, count: k * 256)344        var v = [Int16](repeating: 0, count: 256)345        var mu = [Int16](repeating: 0, count: 256)346        var c = Bytes()347        c.reserveCapacity(ps.ciphertextSize)348        ek.withUnsafeBufferPointer { ekp in349            tHat.withUnsafeMutableBufferPointer { Coding.decode12(ekp.baseAddress! + ekOffset, count: 256 * k, into: $0.baseAddress!) }350        }351        m.withUnsafeBufferPointer { mp in352            mu.withUnsafeMutableBufferPointer { Coding.messageToPoly(mp.baseAddress!, into: $0.baseAddress!) }353        }354        at.withUnsafeBufferPointer { ap in355            tHat.withUnsafeBufferPointer { thp in356                y.withUnsafeMutableBufferPointer { yp in357                    e1.withUnsafeMutableBufferPointer { e1p in358                        u.withUnsafeMutableBufferPointer { up in359                            let A = ap.baseAddress!, TH = thp.baseAddress!, Y = yp.baseAddress!, E1 = e1p.baseAddress!, U = up.baseAddress!360                            for i in 0..<k {361                                Sampling.samplePolyCBD(seed: r, nonce: UInt8(i), eta: ps.eta1, into: Y + 256 * i)362                                Sampling.samplePolyCBD(seed: r, nonce: UInt8(k + i), eta: ps.eta2, into: E1 + 256 * i)363                            }364                            e2.withUnsafeMutableBufferPointer {365                                Sampling.samplePolyCBD(seed: r, nonce: UInt8(2 * k), eta: ps.eta2, into: $0.baseAddress!)366                            }367                            for i in 0..<k {368                                NTT.forward(Y + 256 * i)369                                NTT.reduce(Y + 256 * i)370                            }371                            // u = NTT^-1(A-hat^T o y-hat) + e1372                            for i in 0..<k {373                                let ui = U + 256 * i374                                for j in 0..<k {375                                    NTT.multiplyAccumulate(ui, A + (i * k + j) * 256, Y + 256 * j, accumulate: j > 0)376                                }377                                NTT.reduce(ui)378                                NTT.inverseToMontgomery(ui)379                                let e1i = E1 + 256 * i380                                for x in 0..<256 { ui[x] = ui[x] &+ e1i[x] }381                            }382                            // v = NTT^-1(t-hat^T o y-hat) + e2 + mu383                            v.withUnsafeMutableBufferPointer { vp in384                                let V = vp.baseAddress!385                                for j in 0..<k {386                                    NTT.multiplyAccumulate(V, TH + 256 * j, Y + 256 * j, accumulate: j > 0)387                                }388                                NTT.reduce(V)389                                NTT.inverseToMontgomery(V)390                                for x in 0..<256 { V[x] = V[x] &+ e2[x] &+ mu[x] }391                            }392                            Coding.compressEncode(U, count: 256 * k, bits: ps.du, into: &c)393                        }394                    }395                }396            }397        }398        v.withUnsafeBufferPointer { Coding.compressEncode($0.baseAddress!, count: 256, bits: ps.dv, into: &c) }399        SecureMemory.zero(&y)400        SecureMemory.zero(&e1)401        SecureMemory.zero(&e2)402        SecureMemory.zero(&mu)403        SecureMemory.zero(&v)404        SecureMemory.zero(&u)405        return c406    }407408    /// K-PKE.Decrypt (Algorithm 15). The private vector s-hat is the first 384k bytes of `dk`.409    static func pkeDecrypt(_ ps: ParameterSet, dk: Bytes, c: Bytes) -> Bytes {410        let k = ps.k411        var u = [Int16](repeating: 0, count: k * 256)412        var v = [Int16](repeating: 0, count: 256)413        var s = [Int16](repeating: 0, count: k * 256)414        var w = [Int16](repeating: 0, count: 256)415        var m = Bytes()416        m.reserveCapacity(32)417        c.withUnsafeBufferPointer { cp in418            u.withUnsafeMutableBufferPointer { Coding.decodeDecompress(cp.baseAddress!, count: 256 * k, bits: ps.du, into: $0.baseAddress!) }419            v.withUnsafeMutableBufferPointer {420                Coding.decodeDecompress(cp.baseAddress! + 32 * ps.du * k, count: 256, bits: ps.dv, into: $0.baseAddress!)421            }422        }423        dk.withUnsafeBufferPointer { dp in424            s.withUnsafeMutableBufferPointer { Coding.decode12(dp.baseAddress!, count: 256 * k, into: $0.baseAddress!) }425        }426        u.withUnsafeMutableBufferPointer { up in427            s.withUnsafeBufferPointer { sp in428                w.withUnsafeMutableBufferPointer { wp in429                    let U = up.baseAddress!, S = sp.baseAddress!, W = wp.baseAddress!430                    for i in 0..<k {431                        NTT.forward(U + 256 * i)432                        NTT.reduce(U + 256 * i)433                        NTT.multiplyAccumulate(W, S + 256 * i, U + 256 * i, accumulate: i > 0)434                    }435                    NTT.reduce(W)436                    NTT.inverseToMontgomery(W)437                    for x in 0..<256 { W[x] = v[x] &- W[x] }438                    Coding.compressEncode(W, count: 256, bits: 1, into: &m)439                }440            }441        }442        SecureMemory.zero(&s)443        SecureMemory.zero(&w)444        SecureMemory.zero(&u)445        SecureMemory.zero(&v)446        return m447    }448}449
Files main
Menu

Theme