SPB Git

Repository Public

AESGCMTests.swift 17.1 KB 329 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraSymmetricTests/AESGCMTests.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 CommonCrypto42import CryptoKit43import Foundation44import Testing45import QyvoraMath46@testable import QyvoraSymmetric4748private func randomBytes(_ n: Int) -> Bytes {49    var rng = SystemRandomNumberGenerator()50    return (0..<n).map { _ in UInt8.random(in: 0...255, using: &rng) }51}5253private func cipherError(_ body: () throws -> Void) -> SymmetricCipherError? {54    do {55        try body()56        return nil57    } catch {58        return error as? SymmetricCipherError59    }60}6162/// CommonCrypto AES-ECB on one block as an independent oracle.63private func ccAESBlock(key: Bytes, block: Bytes, decrypt: Bool) -> Bytes {64    var out = Bytes(repeating: 0, count: 16)65    var moved = 066    let status = CCCrypt(67        CCOperation(decrypt ? kCCDecrypt : kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionECBMode),68        key, key.count, nil, block, 16, &out, 16, &moved)69    precondition(status == kCCSuccess && moved == 16)70    return out71}7273@Suite struct AESBlockTests {74    /// FIPS 197, Appendix C (example vectors) and Appendix B (cipher example).75    @Test func fips197Vectors() throws {76        let plaintext = Bytes(hex: "00112233445566778899aabbccddeeff")!77        let cases: [(String, String)] = [78            ("000102030405060708090a0b0c0d0e0f", "69c4e0d86a7b0430d8cdb78070b4c55a"),79            ("000102030405060708090a0b0c0d0e0f1011121314151617", "dda97ca4864cdfe06eaf70a0ec0d7191"),80            ("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "8ea2b7ca516745bfeafc49904b496089"),81        ]82        for (key, ciphertext) in cases {83            let aes = try QyvoraSymmetric.AES(key: Bytes(hex: key)!)84            #expect(try aes.encryptBlock(plaintext).hex == ciphertext)85            #expect(try aes.decryptBlock(Bytes(hex: ciphertext)!) == plaintext)86        }87        let b = try QyvoraSymmetric.AES(key: Bytes(hex: "2b7e151628aed2a6abf7158809cf4f3c")!)88        #expect(try b.encryptBlock(Bytes(hex: "3243f6a8885a308d313198a2e0370734")!).hex == "3925841d02dc09fbdc118597196a0b32")89    }9091    /// The algebraic S-box equals the FIPS 197 definition for all 256 inputs, in every byte position.92    @Test func sboxMatchesDefinition() {93        func gmul(_ a: UInt8, _ b: UInt8) -> UInt8 {94            var a = a, b = b, r: UInt8 = 095            while b != 0 {96                if b & 1 != 0 { r ^= a }97                a = (a << 1) ^ (a & 0x80 != 0 ? 0x1b : 0)98                b >>= 199            }100            return r101        }102        var table = [UInt8](repeating: 0, count: 256)103        for x in 0..<256 {104            var inv: UInt8 = 0105            if x != 0 {106                for y in 1..<256 where gmul(UInt8(x), UInt8(y)) == 1 { inv = UInt8(y) }107            }108            var s = inv109            for k in 1...4 { s ^= (inv << UInt8(k)) | (inv >> UInt8(8 - k)) }110            table[x] = s ^ 0x63111        }112        // spot values of FIPS 197, figure 7113        #expect(table[0x00] == 0x63 && table[0x01] == 0x7c && table[0x53] == 0xed && table[0xff] == 0x16)114        for x in 0..<256 {115            for position in 0..<8 {116                let other = UInt64(0xa5a5_a5a5_a5a5_a5a5) & ~(UInt64(0xff) << UInt64(8 * position))117                let word = other | UInt64(x) << UInt64(8 * position)118                let out = QyvoraSymmetric.AES.subBytes(word)119                #expect(UInt8(truncatingIfNeeded: out >> UInt64(8 * position)) == table[x])120                #expect(QyvoraSymmetric.AES.invSubBytes(out) == word)121            }122        }123    }124125    @Test func differentialAgainstCommonCrypto() throws {126        for size in [16, 24, 32] {127            for _ in 0..<40 {128                let key = randomBytes(size), block = randomBytes(16)129                let aes = try QyvoraSymmetric.AES(key: key)130                let c = try aes.encryptBlock(block)131                #expect(c == ccAESBlock(key: key, block: block, decrypt: false))132                #expect(try aes.decryptBlock(block) == ccAESBlock(key: key, block: block, decrypt: true))133                #expect(try aes.decryptBlock(c) == block)134            }135        }136    }137138    @Test func rejectsBadSizes() throws {139        for size in [0, 1, 15, 17, 31, 33, 64] {140            #expect(cipherError { _ = try QyvoraSymmetric.AES(key: Bytes(repeating: 0, count: size)) } == .invalidKeyLength)141        }142        let aes = try QyvoraSymmetric.AES(key: Bytes(repeating: 0, count: 32))143        #expect(cipherError { _ = try aes.encryptBlock(Bytes(repeating: 0, count: 15)) } == .invalidBlockLength)144        #expect(cipherError { _ = try aes.decryptBlock(Bytes(repeating: 0, count: 17)) } == .invalidBlockLength)145    }146}147148@Suite struct AESGCMTests {149    /// McGrew & Viega, GCM specification, Appendix B: test cases 1 to 18 (three key sizes, IV of 96, 64 and 480 bits).150    @Test func gcmSpecificationTestCases() throws {151        let tests = try VectorFile.load("gcm-spec-vectors.json.gz").list("tests")152        #expect(tests.count == 18)153        for t in tests {154            let gcm = try AESGCM(key: t.bytes("K"))155            let sealed = try gcm.sealAnyNonce(nonce: t.bytes("IV"), plaintext: t.bytes("P"), associatedData: t.bytes("A"))156            #expect(sealed.ciphertext == t.bytes("C"), "test case \(t.int("tc"))")157            #expect(sealed.tag == t.bytes("T"), "test case \(t.int("tc"))")158            let opened = try gcm.openAnyNonce(nonce: t.bytes("IV"), ciphertext: t.bytes("C"), tag: t.bytes("T"), associatedData: t.bytes("A"))159            #expect(opened == t.bytes("P"))160            if t.bytes("IV").count == 12 {161                #expect(try gcm.seal(nonce: t.bytes("IV"), plaintext: t.bytes("P"), associatedData: t.bytes("A")).tag == t.bytes("T"))162            }163        }164    }165166    /// NIST CAVP gcmEncryptExtIV256.rsp, tests with 128-bit tags (IV of 8, 96 and 1024 bits).167    @Test func cavpEncrypt256() throws {168        let tests = try VectorFile.load("cavp-gcm256-encrypt.json.gz").list("tests")169        var standardNonce = 0170        for t in tests {171            let gcm = try AESGCM(key: t.bytes("key"))172            let r = try gcm.sealAnyNonce(nonce: t.bytes("iv"), plaintext: t.bytes("pt"), associatedData: t.bytes("aad"))173            #expect(r.ciphertext == t.bytes("ct") && r.tag == t.bytes("tag"), "ivLen \(t.int("ivLen")) ptLen \(t.int("ptLen")) aadLen \(t.int("aadLen")) count \(t.int("count"))")174            if t.int("ivLen") == 96 {175                let viaPublic = try AES256GCM.seal(key: t.bytes("key"), nonce: t.bytes("iv"), plaintext: t.bytes("pt"), associatedData: t.bytes("aad"))176                #expect(viaPublic.ciphertext == t.bytes("ct") && viaPublic.tag == t.bytes("tag"))177                standardNonce += 1178            }179        }180        #expect(tests.count == 1125)181        #expect(standardNonce == 375)182    }183184    /// NIST CAVP gcmDecrypt256.rsp, tests with 128-bit tags: valid ones decrypt, the ones marked FAIL are rejected.185    @Test func cavpDecrypt256() throws {186        let tests = try VectorFile.load("cavp-gcm256-decrypt.json.gz").list("tests")187        var accepted = 0, rejected = 0188        for t in tests {189            let gcm = try AESGCM(key: t.bytes("key"))190            let shouldPass = t["pass"] as? Bool ?? false191            do {192                let pt = try gcm.openAnyNonce(nonce: t.bytes("iv"), ciphertext: t.bytes("ct"), tag: t.bytes("tag"), associatedData: t.bytes("aad"))193                #expect(shouldPass, "accepted a vector NIST marks FAIL")194                if shouldPass { #expect(pt == t.bytes("pt")) }195                accepted += 1196            } catch {197                #expect(!shouldPass, "rejected a valid vector")198                #expect(error as? SymmetricCipherError == .authenticationFailed)199                rejected += 1200            }201        }202        #expect(tests.count == 1125)203        #expect(accepted == 559 && rejected == 566)204    }205206    @Test func differentialAgainstCryptoKit() throws {207        let lengths = Array(0...130) + [255, 256, 257, 1000, 4096, 5003]208        for n in lengths {209            let key = randomBytes(32), nonce = randomBytes(12)210            let plaintext = randomBytes(n), aad = randomBytes(n % 3 == 0 ? 0 : (n * 7) % 97)211            let ours = try AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: aad)212            let reference = try CryptoKit.AES.GCM.seal(Data(plaintext), using: SymmetricKey(data: Data(key)), nonce: CryptoKit.AES.GCM.Nonce(data: Data(nonce)), authenticating: Data(aad))213            #expect(ours.ciphertext == Array(reference.ciphertext))214            #expect(ours.tag == Array(reference.tag))215            // each side opens what the other sealed216            let box = try CryptoKit.AES.GCM.SealedBox(nonce: CryptoKit.AES.GCM.Nonce(data: Data(nonce)), ciphertext: Data(ours.ciphertext), tag: Data(ours.tag))217            #expect(try Array(CryptoKit.AES.GCM.open(box, using: SymmetricKey(data: Data(key)), authenticating: Data(aad))) == plaintext)218            #expect(try AES256GCM.open(key: key, nonce: nonce, ciphertext: Array(reference.ciphertext), tag: Array(reference.tag), associatedData: aad) == plaintext)219        }220        // AES-128 and AES-192 keys, and longer nonces through the internal entry point221        for size in [16, 24, 32] {222            for nonceLength in [12, 13, 16, 32, 60] {223                let key = randomBytes(size), nonce = randomBytes(nonceLength), plaintext = randomBytes(77), aad = randomBytes(19)224                let ours = try AESGCM(key: key).sealAnyNonce(nonce: nonce, plaintext: plaintext, associatedData: aad)225                let reference = try CryptoKit.AES.GCM.seal(Data(plaintext), using: SymmetricKey(data: Data(key)), nonce: CryptoKit.AES.GCM.Nonce(data: Data(nonce)), authenticating: Data(aad))226                #expect(ours.ciphertext == Array(reference.ciphertext) && ours.tag == Array(reference.tag))227            }228        }229    }230231    @Test func tamperingIsRejected() throws {232        let key = randomBytes(32), nonce = randomBytes(12)233        let plaintext = randomBytes(75), aad = randomBytes(21)234        let sealed = try AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: aad)235        #expect(try AES256GCM.open(key: key, nonce: nonce, ciphertext: sealed.ciphertext, tag: sealed.tag, associatedData: aad) == plaintext)236237        func rejected(key k: Bytes? = nil, nonce n: Bytes? = nil, ciphertext c: Bytes? = nil, tag t: Bytes? = nil, aad a: Bytes? = nil) -> Bool {238            cipherError {239                _ = try AES256GCM.open(key: k ?? key, nonce: n ?? nonce, ciphertext: c ?? sealed.ciphertext, tag: t ?? sealed.tag, associatedData: a ?? aad)240            } == .authenticationFailed241        }242        // every single-bit flip of the tag, and one bit in every byte of the other inputs243        for bit in 0..<128 {244            var t = sealed.tag245            t[bit / 8] ^= 1 << UInt8(bit % 8)246            #expect(rejected(tag: t))247        }248        for i in 0..<sealed.ciphertext.count {249            var c = sealed.ciphertext250            c[i] ^= 1 << UInt8(i % 8)251            #expect(rejected(ciphertext: c))252        }253        for i in 0..<aad.count {254            var a = aad255            a[i] ^= 0x80256            #expect(rejected(aad: a))257        }258        for i in 0..<12 {259            var n = nonce260            n[i] ^= 0x01261            #expect(rejected(nonce: n))262        }263        for i in 0..<32 {264            var k = key265            k[i] ^= 0x10266            #expect(rejected(key: k))267        }268        // truncation and extension269        #expect(rejected(ciphertext: Array(sealed.ciphertext.dropLast())))270        #expect(rejected(ciphertext: sealed.ciphertext + [0]))271        #expect(rejected(ciphertext: []))272        #expect(rejected(aad: Array(aad.dropLast())))273        #expect(rejected(aad: aad + [0]))274        #expect(rejected(aad: []))275        // ciphertext and associated data are not interchangeable276        #expect(rejected(ciphertext: aad, aad: sealed.ciphertext))277        // an all-zero tag is not accepted278        #expect(rejected(tag: Bytes(repeating: 0, count: 16)))279    }280281    @Test func malformedInputsThrowTypedErrors() throws {282        let key = randomBytes(32), nonce = randomBytes(12)283        let sealed = try AES256GCM.seal(key: key, nonce: nonce, plaintext: [1, 2, 3])284        #expect(cipherError { _ = try AES256GCM.seal(key: randomBytes(16), nonce: nonce, plaintext: []) } == .invalidKeyLength)285        #expect(cipherError { _ = try AES256GCM.seal(key: randomBytes(31), nonce: nonce, plaintext: []) } == .invalidKeyLength)286        for n in [0, 1, 8, 11, 13, 16] {287            #expect(cipherError { _ = try AES256GCM.seal(key: key, nonce: randomBytes(n), plaintext: []) } == .invalidNonceLength)288            #expect(cipherError { _ = try AES256GCM.open(key: key, nonce: randomBytes(n), ciphertext: sealed.ciphertext, tag: sealed.tag) } == .invalidNonceLength)289        }290        for n in [0, 4, 12, 15, 17] {291            #expect(cipherError { _ = try AES256GCM.open(key: key, nonce: nonce, ciphertext: sealed.ciphertext, tag: Bytes(sealed.tag.prefix(n)) + Bytes(repeating: 0, count: max(0, n - 16))) } == .invalidTagLength)292        }293        #expect(cipherError { _ = try AESGCM(key: key).sealAnyNonce(nonce: [], plaintext: [], associatedData: []) } == .invalidNonceLength)294        #expect(cipherError { _ = try AES256GCM.open(key: key, sealed: Bytes(repeating: 0, count: 27)) } == .truncatedInput)295        #expect(cipherError { _ = try AES256GCM.open(key: key, sealed: Bytes(repeating: 0, count: 28)) } == .authenticationFailed)296        #expect(cipherError { _ = try AES256GCM.open(key: randomBytes(5), sealed: Bytes(repeating: 0, count: 40)) } == .invalidKeyLength)297        #expect(cipherError { _ = try AESGCM(key: key).openCombined(nonce: nonce, combined: Bytes(repeating: 0, count: 15)) } == .truncatedInput)298    }299300    @Test func combinedAndRandomNonceForms() throws {301        let key = randomBytes(32)302        let gcm = try AESGCM(key: key)303        for n in [0, 1, 16, 33, 200] {304            let plaintext = randomBytes(n), aad = randomBytes(n / 2), nonce = randomBytes(12)305            let parts = try gcm.seal(nonce: nonce, plaintext: plaintext, associatedData: aad)306            let combined = try gcm.sealCombined(nonce: nonce, plaintext: plaintext, associatedData: aad)307            #expect(combined == parts.ciphertext + parts.tag)308            #expect(try gcm.openCombined(nonce: nonce, combined: combined, associatedData: aad) == plaintext)309            #expect(try AES256GCM.sealInternal(key: key, nonce: nonce, plaintext: plaintext, associatedData: aad) == nonce + combined)310311            let a = try AES256GCM.seal(key: key, plaintext: plaintext, associatedData: aad)312            let b = try AES256GCM.seal(key: key, plaintext: plaintext, associatedData: aad)313            #expect(a.count == 12 + n + 16)314            #expect(Bytes(a.prefix(12)) != Bytes(b.prefix(12)), "two random nonces collided")315            #expect(try AES256GCM.open(key: key, sealed: a, associatedData: aad) == plaintext)316            #expect(try AES256GCM.open(key: key, sealed: b, associatedData: aad) == plaintext)317            var bad = a318            bad[bad.count / 2] ^= 0x04319            #expect(cipherError { _ = try AES256GCM.open(key: key, sealed: bad, associatedData: aad) } == .authenticationFailed)320            // one byte short: below nonce + tag it is a framing error, otherwise an authentication failure321            #expect(cipherError { _ = try AES256GCM.open(key: key, sealed: Array(a.dropLast()), associatedData: aad) }322                == (n == 0 ? .truncatedInput : .authenticationFailed))323            // CryptoKit opens the nonce || ciphertext || tag layout as well324            let box = try CryptoKit.AES.GCM.SealedBox(combined: Data(a))325            #expect(try Array(CryptoKit.AES.GCM.open(box, using: SymmetricKey(data: Data(key)), authenticating: Data(aad))) == plaintext)326        }327    }328}329
Files main
Menu

Theme