SPB Git

Repository Public

ChaCha20Poly1305Tests.swift 16.8 KB 325 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraSymmetricTests/ChaCha20Poly1305Tests.swift8// Module           : Tests9// 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 CryptoKit42import Foundation43import Testing44import QyvoraMath45@testable import QyvoraSymmetric4647private typealias QChaChaPoly = QyvoraSymmetric.ChaCha20Poly13054849private func randomBytes(_ n: Int) -> Bytes {50    var rng = SystemRandomNumberGenerator()51    return (0..<n).map { _ in UInt8.random(in: 0...255, using: &rng) }52}5354private func cipherError(_ body: () throws -> Void) -> SymmetricCipherError? {55    do {56        try body()57        return nil58    } catch {59        return error as? SymmetricCipherError60    }61}6263private func h(_ s: String) -> Bytes { Bytes(hex: s.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: ":", with: ""))! }6465/// RFC 8439 vectors. The hex dumps come from `Vectors/rfc8439-vectors.json.gz` (extracted from the RFC text);66/// the short inline values (keys and nonces given in running text, tags) are copied from the same sections.67@Suite struct RFC8439Tests {68    static func records(_ section: String) throws -> [[String: Any]] {69        try VectorFile.load("rfc8439-vectors.json.gz").list("records").filter { $0.str("section") == section }70    }7172    static func fields(_ record: [String: Any]) -> [String: Any] { record["fields"] as! [String: Any] }7374    static let sequentialKey: Bytes = (0..<32).map { UInt8($0) }7576    @Test func section232BlockFunction() throws {77        let f = Self.fields(try Self.records("2.3.2")[0])78        let block = try ChaCha20.block(key: Self.sequentialKey, nonce: h("000000090000004a00000000"), counter: 1)79        #expect(block == f.bytes("Serialized Block"))80    }8182    @Test func section242Encryption() throws {83        let f = Self.fields(try Self.records("2.4.2")[0])84        let nonce = h("000000000000004a00000000")85        let plaintext = f.bytes("Plaintext Sunscreen")86        #expect(String(decoding: plaintext, as: UTF8.self).hasPrefix("Ladies and Gentlemen of the class of '99"))87        let ciphertext = try ChaCha20.xor(key: Self.sequentialKey, nonce: nonce, counter: 1, plaintext)88        #expect(ciphertext == f.bytes("Ciphertext Sunscreen"))89        #expect(try ChaCha20.xor(key: Self.sequentialKey, nonce: nonce, counter: 1, ciphertext) == plaintext)90    }9192    @Test func section252Poly1305() throws {93        let f = Self.fields(try Self.records("2.5.2")[0])94        let key = h("85:d6:be:78:57:55:6d:33:7f:44:52:fe:42:d5:06:a8:01:03:80:8a:fb:0d:b2:fd:4a:bf:f6:af:41:49:f5:1b")95        let message = f.bytes("Message to be Authenticated")96        #expect(message == Array("Cryptographic Forum Research Group".utf8))97        #expect(try Poly1305.authenticate(key: key, message: message) == h("a8:06:1d:c1:30:51:36:c6:c2:2b:8b:af:0c:01:27:a9"))98    }99100    @Test func section262KeyGeneration() throws {101        let f = Self.fields(try Self.records("2.6.2")[0])102        let block = try ChaCha20.block(key: f.bytes("Key"), nonce: f.bytes("Nonce"), counter: 0)103        #expect(Bytes(block.prefix(32)) == f.bytes("Output bytes"))104    }105106    @Test func section282AEAD() throws {107        let f = Self.fields(try Self.records("2.8.2")[0])108        let nonce = f.bytes("32-bit fixed-common part") + f.bytes("IV")109        let tag = h("1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91")110        #expect(Bytes(try ChaCha20.block(key: f.bytes("Key"), nonce: nonce, counter: 0).prefix(32)) == f.bytes("Poly1305 Key"))111        let sealed = try QChaChaPoly.seal(key: f.bytes("Key"), nonce: nonce, plaintext: f.bytes("Plaintext"), associatedData: f.bytes("AAD"))112        #expect(sealed.ciphertext == f.bytes("Ciphertext"))113        #expect(sealed.tag == tag)114        #expect(try QChaChaPoly.open(key: f.bytes("Key"), nonce: nonce, ciphertext: f.bytes("Ciphertext"), tag: tag, associatedData: f.bytes("AAD")) == f.bytes("Plaintext"))115    }116117    @Test func appendixA1BlockFunction() throws {118        let records = try Self.records("A.1")119        #expect(records.count == 5)120        for r in records {121            let f = Self.fields(r)122            #expect(try ChaCha20.block(key: f.bytes("Key"), nonce: f.bytes("Nonce"), counter: UInt32(r.int("counter"))) == f.bytes("Keystream"), "A.1 #\(r.int("vector"))")123        }124    }125126    @Test func appendixA2Encryption() throws {127        let records = try Self.records("A.2")128        #expect(records.count == 3)129        for r in records {130            let f = Self.fields(r)131            let out = try ChaCha20.xor(key: f.bytes("Key"), nonce: f.bytes("Nonce"), counter: UInt32(r.int("counter")), f.bytes("Plaintext"))132            #expect(out == f.bytes("Ciphertext"), "A.2 #\(r.int("vector"))")133        }134    }135136    @Test func appendixA3Poly1305() throws {137        let records = try Self.records("A.3")138        #expect(records.count == 4)139        for r in records {140            let f = Self.fields(r)141            #expect(try Poly1305.authenticate(key: f.bytes("One-time Poly1305 Key"), message: f.bytes("Text to MAC")) == f.bytes("Tag"), "A.3 #\(r.int("vector"))")142        }143        // A.3 test vectors 5 to 11: edge cases of the arithmetic modulo 2^130 - 5 (key = R || S)144        let zero = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"145        let edge: [(Int, String, String, String, String)] = [146            (5, "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", zero,147             "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF",148             "03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"),149            (6, "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF",150             "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",151             "03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"),152            (7, "01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", zero,153             "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF" + "F0 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF"154                + "11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",155             "05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"),156            (8, "01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", zero,157             "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF" + "FB FE FE FE FE FE FE FE FE FE FE FE FE FE FE FE"158                + "01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01",159             "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"),160            (9, "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", zero,161             "FD FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF",162             "FA FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF"),163            (10, "01 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00", zero,164             "E3 35 94 D7 50 5E 43 B9 00 00 00 00 00 00 00 00" + "33 94 D7 50 5E 43 79 CD 01 00 00 00 00 00 00 00"165                + "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" + "01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",166             "14 00 00 00 00 00 00 00 55 00 00 00 00 00 00 00"),167            (11, "01 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00", zero,168             "E3 35 94 D7 50 5E 43 B9 00 00 00 00 00 00 00 00" + "33 94 D7 50 5E 43 79 CD 01 00 00 00 00 00 00 00"169                + "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",170             "13 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"),171        ]172        for (number, r, s, data, tag) in edge {173            #expect(try Poly1305.authenticate(key: h(r) + h(s), message: h(data)) == h(tag), "A.3 #\(number)")174        }175    }176177    @Test func appendixA4KeyGeneration() throws {178        let records = try Self.records("A.4")179        #expect(records.count == 3)180        for r in records {181            let f = Self.fields(r)182            let block = try ChaCha20.block(key: f.bytes("The ChaCha20 Key"), nonce: f.bytes("The nonce"), counter: 0)183            #expect(Bytes(block.prefix(32)) == f.bytes("Poly1305 one-time key"), "A.4 #\(r.int("vector"))")184        }185    }186187    @Test func appendixA5Decryption() throws {188        let f = Self.fields(try Self.records("A.5")[0])189        let plaintext = try QChaChaPoly.open(190            key: f.bytes("The ChaCha20 Key"), nonce: f.bytes("The nonce"), ciphertext: f.bytes("Ciphertext"),191            tag: f.bytes("Received Tag"), associatedData: f.bytes("The AAD"))192        #expect(plaintext == f.bytes("Plaintext"))193        #expect(f.bytes("Received Tag") == f.bytes("Calculated Tag"))194        #expect(String(decoding: plaintext, as: UTF8.self).hasPrefix("Internet-Drafts are draft documents"))195    }196}197198@Suite struct ChaCha20Poly1305Tests {199    @Test func differentialAgainstCryptoKit() throws {200        let lengths = Array(0...140) + [255, 256, 257, 1000, 4096, 5003]201        for n in lengths {202            let key = randomBytes(32), nonce = randomBytes(12)203            let plaintext = randomBytes(n), aad = randomBytes(n % 3 == 0 ? 0 : (n * 5) % 83)204            let ours = try QChaChaPoly.seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: aad)205            let reference = try ChaChaPoly.seal(Data(plaintext), using: SymmetricKey(data: Data(key)), nonce: ChaChaPoly.Nonce(data: Data(nonce)), authenticating: Data(aad))206            #expect(ours.ciphertext == Array(reference.ciphertext))207            #expect(ours.tag == Array(reference.tag))208            let box = try ChaChaPoly.SealedBox(nonce: ChaChaPoly.Nonce(data: Data(nonce)), ciphertext: Data(ours.ciphertext), tag: Data(ours.tag))209            #expect(try Array(ChaChaPoly.open(box, using: SymmetricKey(data: Data(key)), authenticating: Data(aad))) == plaintext)210            #expect(try QChaChaPoly.open(key: key, nonce: nonce, ciphertext: Array(reference.ciphertext), tag: Array(reference.tag), associatedData: aad) == plaintext)211        }212    }213214    @Test func poly1305IncrementalEqualsOneShot() throws {215        var rng = SystemRandomNumberGenerator()216        for n in [0, 1, 15, 16, 17, 31, 32, 33, 100, 1000] {217            let key = randomBytes(32), m = randomBytes(n)218            let want = try Poly1305.authenticate(key: key, message: m)219            for _ in 0..<5 {220                var p = try Poly1305(key: key)221                var i = 0222                while i < n {223                    let step = min(n - i, Int.random(in: 0...40, using: &rng))224                    p.update(Array(m[i..<(i + step)]))225                    i += step226                }227                #expect(p.finalize() == want)228            }229        }230        // extreme inputs: all-ones key and message exercise the carries231        let ones = Bytes(repeating: 0xff, count: 32)232        let tag = try Poly1305.authenticate(key: ones, message: Bytes(repeating: 0xff, count: 163))233        var p = try Poly1305(key: ones)234        for _ in 0..<163 { p.update([0xff]) }235        #expect(p.finalize() == tag)236    }237238    @Test func tamperingIsRejected() throws {239        let key = randomBytes(32), nonce = randomBytes(12)240        let plaintext = randomBytes(90), aad = randomBytes(17)241        let sealed = try QChaChaPoly.seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: aad)242243        func rejected(key k: Bytes? = nil, nonce n: Bytes? = nil, ciphertext c: Bytes? = nil, tag t: Bytes? = nil, aad a: Bytes? = nil) -> Bool {244            cipherError {245                _ = try QChaChaPoly.open(key: k ?? key, nonce: n ?? nonce, ciphertext: c ?? sealed.ciphertext, tag: t ?? sealed.tag, associatedData: a ?? aad)246            } == .authenticationFailed247        }248        for bit in 0..<128 {249            var t = sealed.tag250            t[bit / 8] ^= 1 << UInt8(bit % 8)251            #expect(rejected(tag: t))252        }253        for i in 0..<sealed.ciphertext.count {254            var c = sealed.ciphertext255            c[i] ^= 1 << UInt8(i % 8)256            #expect(rejected(ciphertext: c))257        }258        for i in 0..<aad.count {259            var a = aad260            a[i] ^= 0x01261            #expect(rejected(aad: a))262        }263        for i in 0..<12 {264            var n = nonce265            n[i] ^= 0x80266            #expect(rejected(nonce: n))267        }268        for i in 0..<32 {269            var k = key270            k[i] ^= 0x02271            #expect(rejected(key: k))272        }273        #expect(rejected(ciphertext: Array(sealed.ciphertext.dropLast())))274        #expect(rejected(ciphertext: sealed.ciphertext + [0]))275        #expect(rejected(ciphertext: []))276        #expect(rejected(aad: Array(aad.dropLast())))277        #expect(rejected(aad: aad + [0]))278        #expect(rejected(ciphertext: aad, aad: sealed.ciphertext))279        #expect(rejected(tag: Bytes(repeating: 0, count: 16)))280    }281282    @Test func malformedInputsThrowTypedErrors() throws {283        let key = randomBytes(32), nonce = randomBytes(12)284        let sealed = try QChaChaPoly.seal(key: key, nonce: nonce, plaintext: [1, 2, 3])285        for n in [0, 16, 31, 33] {286            #expect(cipherError { _ = try QChaChaPoly.seal(key: randomBytes(n), nonce: nonce, plaintext: []) } == .invalidKeyLength)287            #expect(cipherError { _ = try ChaCha20.block(key: randomBytes(n), nonce: nonce, counter: 0) } == .invalidKeyLength)288            #expect(cipherError { _ = try Poly1305(key: randomBytes(n)) } == .invalidKeyLength)289        }290        for n in [0, 8, 11, 13, 24] {291            #expect(cipherError { _ = try QChaChaPoly.seal(key: key, nonce: randomBytes(n), plaintext: []) } == .invalidNonceLength)292            #expect(cipherError { _ = try QChaChaPoly.open(key: key, nonce: randomBytes(n), ciphertext: sealed.ciphertext, tag: sealed.tag) } == .invalidNonceLength)293            #expect(cipherError { _ = try ChaCha20.xor(key: key, nonce: randomBytes(n), counter: 0, [1]) } == .invalidNonceLength)294        }295        for n in [0, 15, 17] {296            #expect(cipherError { _ = try QChaChaPoly.open(key: key, nonce: nonce, ciphertext: sealed.ciphertext, tag: Bytes(repeating: 0, count: n)) } == .invalidTagLength)297        }298        #expect(cipherError { _ = try QChaChaPoly.open(key: key, sealed: Bytes(repeating: 0, count: 27)) } == .truncatedInput)299        #expect(cipherError { _ = try QChaChaPoly.open(key: key, sealed: Bytes(repeating: 0, count: 28)) } == .authenticationFailed)300        // the 32-bit block counter must not wrap301        #expect(cipherError { _ = try ChaCha20.xor(key: key, nonce: nonce, counter: UInt32.max, Bytes(repeating: 0, count: 65)) } == .messageTooLong)302        #expect(try ChaCha20.xor(key: key, nonce: nonce, counter: UInt32.max, Bytes(repeating: 0, count: 64)).count == 64)303    }304305    @Test func randomNonceForm() throws {306        let key = randomBytes(32)307        for n in [0, 1, 64, 65, 300] {308            let plaintext = randomBytes(n), aad = randomBytes(n / 3)309            let a = try QChaChaPoly.seal(key: key, plaintext: plaintext, associatedData: aad)310            let b = try QChaChaPoly.seal(key: key, plaintext: plaintext, associatedData: aad)311            #expect(a.count == 12 + n + 16)312            #expect(Bytes(a.prefix(12)) != Bytes(b.prefix(12)), "two random nonces collided")313            #expect(try QChaChaPoly.open(key: key, sealed: a, associatedData: aad) == plaintext)314            let nonce = Bytes(a.prefix(12))315            #expect(try QChaChaPoly.sealInternal(key: key, nonce: nonce, plaintext: plaintext, associatedData: aad) == a)316            var bad = a317            bad[bad.count - 1] ^= 0x01318            #expect(cipherError { _ = try QChaChaPoly.open(key: key, sealed: bad, associatedData: aad) } == .authenticationFailed)319            // CryptoKit opens the nonce || ciphertext || tag layout as well320            let box = try ChaChaPoly.SealedBox(combined: Data(a))321            #expect(try Array(ChaChaPoly.open(box, using: SymmetricKey(data: Data(key)), authenticating: Data(aad))) == plaintext)322        }323    }324}325
Files main
Menu

Theme