Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraSymmetric/ChaCha20Poly1305.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/// ChaCha20 stream cipher (RFC 8439, section 2.4): 256-bit key, 96-bit nonce, 32-bit block counter.44/// Only additions, rotations and XORs on 32-bit words: constant time by construction.45public enum ChaCha20 {46 public static let keySize = 3247 public static let nonceSize = 1248 public static let blockSize = 644950 @inline(__always) private static func rotl(_ x: UInt32, _ n: UInt32) -> UInt32 { (x << n) | (x >> (32 &- n)) }5152 @inline(__always) private static func quarterRound(_ s: UnsafeMutablePointer<UInt32>, _ a: Int, _ b: Int, _ c: Int, _ d: Int) {53 s[a] = s[a] &+ s[b]; s[d] = rotl(s[d] ^ s[a], 16)54 s[c] = s[c] &+ s[d]; s[b] = rotl(s[b] ^ s[c], 12)55 s[a] = s[a] &+ s[b]; s[d] = rotl(s[d] ^ s[a], 8)56 s[c] = s[c] &+ s[d]; s[b] = rotl(s[b] ^ s[c], 7)57 }5859 /// Writes the 64-byte block for `initial` (16 state words) into `out`. `work` is a 16-word scratch area.60 @inline(__always) private static func block(61 _ initial: UnsafePointer<UInt32>, into out: UnsafeMutablePointer<UInt8>, work s: UnsafeMutablePointer<UInt32>62 ) {63 for i in 0..<16 { s[i] = initial[i] }64 for _ in 0..<10 {65 quarterRound(s, 0, 4, 8, 12)66 quarterRound(s, 1, 5, 9, 13)67 quarterRound(s, 2, 6, 10, 14)68 quarterRound(s, 3, 7, 11, 15)69 quarterRound(s, 0, 5, 10, 15)70 quarterRound(s, 1, 6, 11, 12)71 quarterRound(s, 2, 7, 8, 13)72 quarterRound(s, 3, 4, 9, 14)73 }74 for i in 0..<16 {75 let v = s[i] &+ initial[i]76 out[4 * i] = UInt8(truncatingIfNeeded: v)77 out[4 * i + 1] = UInt8(truncatingIfNeeded: v >> 8)78 out[4 * i + 2] = UInt8(truncatingIfNeeded: v >> 16)79 out[4 * i + 3] = UInt8(truncatingIfNeeded: v >> 24)80 }81 }8283 private static func initialState(key: Bytes, nonce: Bytes, counter: UInt32) -> [UInt32] {84 var st = [UInt32](repeating: 0, count: 16)85 st[0] = 0x6170_7865; st[1] = 0x3320_646e; st[2] = 0x7962_2d32; st[3] = 0x6b20_657486 key.withUnsafeBufferPointer { k in87 for i in 0..<8 { st[4 + i] = Endian.loadLE32(k.baseAddress! + 4 * i) }88 }89 st[12] = counter90 nonce.withUnsafeBufferPointer { n in91 for i in 0..<3 { st[13 + i] = Endian.loadLE32(n.baseAddress! + 4 * i) }92 }93 return st94 }9596 /// The ChaCha20 block function (RFC 8439, section 2.3): 64 keystream bytes.97 public static func block(key: Bytes, nonce: Bytes, counter: UInt32) throws -> Bytes {98 guard key.count == keySize else { throw SymmetricCipherError.invalidKeyLength }99 guard nonce.count == nonceSize else { throw SymmetricCipherError.invalidNonceLength }100 var st = initialState(key: key, nonce: nonce, counter: counter)101 var out = Bytes(repeating: 0, count: 64)102 var work = [UInt32](repeating: 0, count: 16)103 st.withUnsafeBufferPointer { s in104 out.withUnsafeMutableBufferPointer { o in105 work.withUnsafeMutableBufferPointer { w in block(s.baseAddress!, into: o.baseAddress!, work: w.baseAddress!) }106 }107 }108 SecureMemory.zero(&st)109 SecureMemory.zero(&work)110 return out111 }112113 /// Encrypts or decrypts `data` (the operation is its own inverse), starting at block `counter`.114 /// Throws `messageTooLong` when the 32-bit block counter would wrap.115 public static func xor(key: Bytes, nonce: Bytes, counter: UInt32, _ data: Bytes) throws -> Bytes {116 guard key.count == keySize else { throw SymmetricCipherError.invalidKeyLength }117 guard nonce.count == nonceSize else { throw SymmetricCipherError.invalidNonceLength }118 let n = data.count119 let blocks = (UInt64(n) + 63) / 64120 guard UInt64(counter) + blocks <= UInt64(1) << 32 else { throw SymmetricCipherError.messageTooLong }121 var st = initialState(key: key, nonce: nonce, counter: counter)122 var out = Bytes(repeating: 0, count: n)123 var work = [UInt32](repeating: 0, count: 16)124 var keystream = Bytes(repeating: 0, count: 64)125 st.withUnsafeMutableBufferPointer { s in126 work.withUnsafeMutableBufferPointer { w in127 keystream.withUnsafeMutableBufferPointer { ks in128 data.withUnsafeBufferPointer { src in129 out.withUnsafeMutableBufferPointer { dst in130 var i = 0131 while i < n {132 block(UnsafePointer(s.baseAddress!), into: ks.baseAddress!, work: w.baseAddress!)133 s[12] &+= 1134 let take = min(64, n - i)135 for j in 0..<take { dst[i + j] = src[i + j] ^ ks[j] }136 i += take137 }138 }139 }140 }141 }142 }143 SecureMemory.zero(&st)144 SecureMemory.zero(&work)145 SecureMemory.zero(&keystream)146 return out147 }148}149150/// Poly1305 one-time authenticator (RFC 8439, section 2.5).151///152/// Arithmetic modulo 2^130 - 5 on five 26-bit limbs with 64-bit products; no branch or index depends on153/// the key or the message. A key must authenticate one message only.154public struct Poly1305: Sendable {155 public static let keySize = 32156 public static let tagSize = 16157158 var r0: UInt64, r1: UInt64, r2: UInt64, r3: UInt64, r4: UInt64159 var h0: UInt64 = 0, h1: UInt64 = 0, h2: UInt64 = 0, h3: UInt64 = 0, h4: UInt64 = 0160 var pad0: UInt64, pad1: UInt64, pad2: UInt64, pad3: UInt64161 var buffer = Bytes(repeating: 0, count: 16)162 var buffered = 0163164 /// `key` is the 32-byte one-time key `r || s`.165 public init(key: Bytes) throws {166 guard key.count == Self.keySize else { throw SymmetricCipherError.invalidKeyLength }167 (r0, r1, r2, r3, r4, pad0, pad1, pad2, pad3) = key.withUnsafeBufferPointer { k in168 let p = k.baseAddress!169 // clamp r (section 2.5.1) while splitting it into 26-bit limbs170 return (171 UInt64(Endian.loadLE32(p)) & 0x3ff_ffff,172 UInt64(Endian.loadLE32(p + 3) >> 2) & 0x3ff_ff03,173 UInt64(Endian.loadLE32(p + 6) >> 4) & 0x3ff_c0ff,174 UInt64(Endian.loadLE32(p + 9) >> 6) & 0x3f0_3fff,175 UInt64(Endian.loadLE32(p + 12) >> 8) & 0x00f_ffff,176 UInt64(Endian.loadLE32(p + 16)), UInt64(Endian.loadLE32(p + 20)),177 UInt64(Endian.loadLE32(p + 24)), UInt64(Endian.loadLE32(p + 28))178 )179 }180 }181182 /// h = (h + block) · r mod 2^130 - 5. `highBit` is 2^128 for full blocks, 0 for the padded final block.183 @inline(__always) private mutating func absorb(_ m: UnsafePointer<UInt8>, highBit: UInt64) {184 let mask: UInt64 = 0x3ff_ffff185 let s1 = r1 &* 5, s2 = r2 &* 5, s3 = r3 &* 5, s4 = r4 &* 5186 let a0 = h0 &+ (UInt64(Endian.loadLE32(m)) & mask)187 let a1 = h1 &+ (UInt64(Endian.loadLE32(m + 3) >> 2) & mask)188 let a2 = h2 &+ (UInt64(Endian.loadLE32(m + 6) >> 4) & mask)189 let a3 = h3 &+ (UInt64(Endian.loadLE32(m + 9) >> 6) & mask)190 let a4 = h4 &+ (UInt64(Endian.loadLE32(m + 12) >> 8) | highBit)191192 var d0 = a0 &* r0 &+ a1 &* s4 &+ a2 &* s3 &+ a3 &* s2 &+ a4 &* s1193 var d1 = a0 &* r1 &+ a1 &* r0 &+ a2 &* s4 &+ a3 &* s3 &+ a4 &* s2194 var d2 = a0 &* r2 &+ a1 &* r1 &+ a2 &* r0 &+ a3 &* s4 &+ a4 &* s3195 var d3 = a0 &* r3 &+ a1 &* r2 &+ a2 &* r1 &+ a3 &* r0 &+ a4 &* s4196 var d4 = a0 &* r4 &+ a1 &* r3 &+ a2 &* r2 &+ a3 &* r1 &+ a4 &* r0197198 var c = d0 >> 26; d0 &= mask199 d1 &+= c; c = d1 >> 26; d1 &= mask200 d2 &+= c; c = d2 >> 26; d2 &= mask201 d3 &+= c; c = d3 >> 26; d3 &= mask202 d4 &+= c; c = d4 >> 26; d4 &= mask203 d0 &+= c &* 5; c = d0 >> 26; d0 &= mask204 d1 &+= c205 h0 = d0; h1 = d1; h2 = d2; h3 = d3; h4 = d4206 }207208 public mutating func update(_ data: Bytes) {209 let n = data.count210 var offset = 0211 if buffered > 0 {212 let take = min(16 - buffered, n)213 for i in 0..<take { buffer[buffered + i] = data[i] }214 buffered += take215 offset = take216 if buffered < 16 { return }217 buffer.withUnsafeBufferPointer { b in absorb(b.baseAddress!, highBit: 1 << 24) }218 buffered = 0219 }220 data.withUnsafeBufferPointer { d in221 while n - offset >= 16 {222 absorb(d.baseAddress! + offset, highBit: 1 << 24)223 offset += 16224 }225 }226 for i in offset..<n { buffer[i - offset] = data[i] }227 buffered = n - offset228 }229230 /// Returns the 16-byte tag and erases the key material. The instance must not be used afterwards.231 public mutating func finalize() -> Bytes {232 let mask: UInt64 = 0x3ff_ffff233 if buffered > 0 {234 buffer[buffered] = 1235 for i in (buffered + 1)..<16 { buffer[i] = 0 }236 buffer.withUnsafeBufferPointer { b in absorb(b.baseAddress!, highBit: 0) }237 }238 // full carry propagation239 var c = h1 >> 26; h1 &= mask240 h2 &+= c; c = h2 >> 26; h2 &= mask241 h3 &+= c; c = h3 >> 26; h3 &= mask242 h4 &+= c; c = h4 >> 26; h4 &= mask243 h0 &+= c &* 5; c = h0 >> 26; h0 &= mask244 h1 &+= c245246 // g = h + 5 - 2^130; keep g when it did not borrow (h >= p), without branching247 var g0 = h0 &+ 5; c = g0 >> 26; g0 &= mask248 var g1 = h1 &+ c; c = g1 >> 26; g1 &= mask249 var g2 = h2 &+ c; c = g2 >> 26; g2 &= mask250 var g3 = h3 &+ c; c = g3 >> 26; g3 &= mask251 var g4 = h4 &+ c &- (1 << 26)252 let keepG = (g4 >> 63) &- 1 // all ones when g4 is non-negative253 g0 &= keepG; g1 &= keepG; g2 &= keepG; g3 &= keepG; g4 &= keepG254 let keepH = ~keepG255 h0 = (h0 & keepH) | g0256 h1 = (h1 & keepH) | g1257 h2 = (h2 & keepH) | g2258 h3 = (h3 & keepH) | g3259 h4 = (h4 & keepH) | g4260261 // h mod 2^128 as four 32-bit words, then add s262 let w0 = (h0 | (h1 << 26)) & 0xffff_ffff263 let w1 = ((h1 >> 6) | (h2 << 20)) & 0xffff_ffff264 let w2 = ((h2 >> 12) | (h3 << 14)) & 0xffff_ffff265 let w3 = ((h3 >> 18) | (h4 << 8)) & 0xffff_ffff266 var f = w0 &+ pad0267 let t0 = UInt32(truncatingIfNeeded: f)268 f = w1 &+ pad1 &+ (f >> 32)269 let t1 = UInt32(truncatingIfNeeded: f)270 f = w2 &+ pad2 &+ (f >> 32)271 let t2 = UInt32(truncatingIfNeeded: f)272 f = w3 &+ pad3 &+ (f >> 32)273 let t3 = UInt32(truncatingIfNeeded: f)274275 r0 = 0; r1 = 0; r2 = 0; r3 = 0; r4 = 0276 h0 = 0; h1 = 0; h2 = 0; h3 = 0; h4 = 0277 pad0 = 0; pad1 = 0; pad2 = 0; pad3 = 0278 SecureMemory.zero(&buffer)279 buffered = 0280 return Endian.le32(t0) + Endian.le32(t1) + Endian.le32(t2) + Endian.le32(t3)281 }282283 /// One-shot tag of `message` under the one-time `key`.284 public static func authenticate(key: Bytes, message: Bytes) throws -> Bytes {285 let dit = DataIndependentTiming.enable()286 defer { DataIndependentTiming.restore(dit) }287 var p = try Poly1305(key: key)288 p.update(message)289 return p.finalize()290 }291}292293/// AEAD_CHACHA20_POLY1305 (RFC 8439, section 2.8): 32-byte key, 12-byte nonce, 16-byte tag.294///295/// A nonce must never be used twice with the same key. Decryption verifies the tag in constant time296/// before any plaintext is produced.297public enum ChaCha20Poly1305 {298 public static let keySize = 32299 public static let nonceSize = 12300 public static let tagSize = 16301 /// Largest plaintext in bytes: 2^32 - 1 blocks of 64 bytes (RFC 8439, section 2.8).302 public static let maxPlaintextSize: UInt64 = ((1 << 32) - 1) * 64303304 private static func tag(key: Bytes, nonce: Bytes, ciphertext: Bytes, associatedData: Bytes) throws -> Bytes {305 var block0 = try ChaCha20.block(key: key, nonce: nonce, counter: 0)306 var oneTimeKey = Bytes(block0[0..<32])307 defer {308 SecureMemory.zero(&block0)309 SecureMemory.zero(&oneTimeKey)310 }311 var mac = try Poly1305(key: oneTimeKey)312 mac.update(associatedData)313 mac.update(Bytes(repeating: 0, count: (16 - associatedData.count % 16) % 16))314 mac.update(ciphertext)315 mac.update(Bytes(repeating: 0, count: (16 - ciphertext.count % 16) % 16))316 mac.update(Endian.le64(UInt64(associatedData.count)) + Endian.le64(UInt64(ciphertext.count)))317 return mac.finalize()318 }319320 /// Encrypts and authenticates. Returns the ciphertext (same length as the plaintext) and the 16-byte tag.321 public static func seal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> (ciphertext: Bytes, tag: Bytes) {322 let dit = DataIndependentTiming.enable()323 defer { DataIndependentTiming.restore(dit) }324 guard key.count == keySize else { throw SymmetricCipherError.invalidKeyLength }325 guard nonce.count == nonceSize else { throw SymmetricCipherError.invalidNonceLength }326 guard UInt64(plaintext.count) <= maxPlaintextSize else { throw SymmetricCipherError.messageTooLong }327 let ciphertext = try ChaCha20.xor(key: key, nonce: nonce, counter: 1, plaintext)328 return (ciphertext, try tag(key: key, nonce: nonce, ciphertext: ciphertext, associatedData: associatedData))329 }330331 /// Verifies the tag, then decrypts. Throws `authenticationFailed` without releasing any plaintext otherwise.332 public static func open(key: Bytes, nonce: Bytes, ciphertext: Bytes, tag: Bytes, associatedData: Bytes = []) throws -> Bytes {333 let dit = DataIndependentTiming.enable()334 defer { DataIndependentTiming.restore(dit) }335 guard key.count == keySize else { throw SymmetricCipherError.invalidKeyLength }336 guard nonce.count == nonceSize else { throw SymmetricCipherError.invalidNonceLength }337 guard tag.count == tagSize else { throw SymmetricCipherError.invalidTagLength }338 guard UInt64(ciphertext.count) <= maxPlaintextSize else { throw SymmetricCipherError.messageTooLong }339 var expected = try self.tag(key: key, nonce: nonce, ciphertext: ciphertext, associatedData: associatedData)340 defer { SecureMemory.zero(&expected) }341 guard ConstantTime.equal(expected, tag) else { throw SymmetricCipherError.authenticationFailed }342 return try ChaCha20.xor(key: key, nonce: nonce, counter: 1, ciphertext)343 }344345 /// Deterministic sealing with an explicit nonce; output is `nonce || ciphertext || tag`.346 /// The caller guarantees that the nonce is never reused with this key.347 public static func sealInternal(key: Bytes, nonce: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> Bytes {348 let r = try seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: associatedData)349 return nonce + r.ciphertext + r.tag350 }351352 /// Sealing with a fresh random 96-bit nonce from `SystemRandom`; output is `nonce || ciphertext || tag`.353 public static func seal(key: Bytes, plaintext: Bytes, associatedData: Bytes = []) throws -> Bytes {354 try sealInternal(key: key, nonce: SystemRandom.bytes(nonceSize), plaintext: plaintext, associatedData: associatedData)355 }356357 /// Opens `nonce || ciphertext || tag`.358 public static func open(key: Bytes, sealed: Bytes, associatedData: Bytes = []) throws -> Bytes {359 guard key.count == keySize else { throw SymmetricCipherError.invalidKeyLength }360 guard sealed.count >= nonceSize + tagSize else { throw SymmetricCipherError.truncatedInput }361 let end = sealed.count - tagSize362 return try open(363 key: key, nonce: Bytes(sealed[0..<nonceSize]), ciphertext: Bytes(sealed[nonceSize..<end]),364 tag: Bytes(sealed[end...]), associatedData: associatedData)365 }366}367