SPB Git

Repository Public

CryptoKitDiffTests.swift 28.5 KB 468 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/DifferentialAuditTests/CryptoKitDiffTests.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 AuditSupport42import CommonCrypto43import CryptoKit44import Foundation45import QyvoraKeccak46import QyvoraMLDSA47import QyvoraMLKEM48import QyvoraMath49import QyvoraSymmetric50import Testing5152// Differential tests against Apple's implementations (CryptoKit: corecrypto; CommonCrypto), used as53// independent oracles in the test environment only. Random inputs come from a seeded generator and54// the seed of every campaign is recorded.5556private let cryptoKit = "Apple CryptoKit (corecrypto), macOS \(ProcessInfo.processInfo.operatingSystemVersionString)"57private let commonCrypto = "Apple CommonCrypto, macOS \(ProcessInfo.processInfo.operatingSystemVersionString)"5859private func raw(_ key: SymmetricKey) -> Bytes { key.withUnsafeBytes { Bytes($0) } }60private func raw(_ secret: SharedSecret) -> Bytes { secret.withUnsafeBytes { Bytes($0) } }6162@Suite struct CryptoKitDifferential {63    // MARK: Hash functions6465    private func hashCampaign(_ algorithm: String, block: Int, ours: (Bytes) -> Bytes, theirs: (Data) -> Bytes) {66        let seed = DiffSeed.make("ck-hash-" + algorithm)67        var rng = AuditRNG(seed: seed)68        var tally = DiffTally("cryptokit-" + algorithm.lowercased(), algorithm: algorithm, oracle: cryptoKit, seed: seed)69        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {70            let m = rng.bytes(rng.edgeLength(block: block))71            tally.check(ours(m) == theirs(Data(m)), "message=\(Hex.encode(m))")72        }73        #expect(tally.finish() == 0)74    }7576    @Test func sha256() {77        hashCampaign("SHA-256", block: 64, ours: { QyvoraSymmetric.SHA256.hash($0) }, theirs: { Bytes(CryptoKit.SHA256.hash(data: $0)) })78    }7980    @Test func sha384() {81        hashCampaign("SHA-384", block: 128, ours: { QyvoraSymmetric.SHA384.hash($0) }, theirs: { Bytes(CryptoKit.SHA384.hash(data: $0)) })82    }8384    @Test func sha512() {85        hashCampaign("SHA-512", block: 128, ours: { QyvoraSymmetric.SHA512.hash($0) }, theirs: { Bytes(CryptoKit.SHA512.hash(data: $0)) })86    }8788    @Test func sha3_256() {89        hashCampaign("SHA3-256", block: 136, ours: { SHA3.sha3_256($0) }, theirs: { Bytes(CryptoKit.SHA3_256.hash(data: $0)) })90    }9192    @Test func sha3_384() {93        hashCampaign("SHA3-384", block: 104, ours: { SHA3.sha3_384($0) }, theirs: { Bytes(CryptoKit.SHA3_384.hash(data: $0)) })94    }9596    @Test func sha3_512() {97        hashCampaign("SHA3-512", block: 72, ours: { SHA3.sha3_512($0) }, theirs: { Bytes(CryptoKit.SHA3_512.hash(data: $0)) })98    }99100    /// The incremental interface must give the same digest whatever the chunking.101    @Test func incrementalHashing() {102        let seed = DiffSeed.make("ck-hash-incremental")103        var rng = AuditRNG(seed: seed)104        var tally = DiffTally("cryptokit-sha2-incremental", algorithm: "SHA-256 / SHA-512 (incremental update)", oracle: cryptoKit, seed: seed)105        for _ in 0..<AuditMode.cases(quick: 1000, full: 10000) {106            let m = rng.bytes(rng.int(0...700))107            var a = QyvoraSymmetric.SHA256(), b = QyvoraSymmetric.SHA512()108            var i = 0109            while i < m.count {110                let n = min(m.count - i, rng.pick([0, 1, 3, 63, 64, 65, 127, 128, 129, 200]))111                a.update(Bytes(m[i..<(i + n)]))112                b.update(Bytes(m[i..<(i + n)]))113                i += n114            }115            let ok = a.finalize() == Bytes(CryptoKit.SHA256.hash(data: Data(m))) && b.finalize() == Bytes(CryptoKit.SHA512.hash(data: Data(m)))116            tally.check(ok, "message=\(Hex.encode(m))")117        }118        #expect(tally.finish() == 0)119    }120121    // MARK: HMAC and HKDF122123    @Test func hmacSHA256() {124        let seed = DiffSeed.make("ck-hmac256")125        var rng = AuditRNG(seed: seed)126        var tally = DiffTally("cryptokit-hmac-sha256", algorithm: "HMAC-SHA-256", oracle: cryptoKit, seed: seed)127        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {128            let key = rng.bytes(rng.edgeLength(block: 64, max: 200)), m = rng.bytes(rng.edgeLength(block: 64))129            let theirs = Bytes(CryptoKit.HMAC<CryptoKit.SHA256>.authenticationCode(for: Data(m), using: SymmetricKey(data: Data(key))))130            tally.check(QyvoraSymmetric.HMAC<QyvoraSymmetric.SHA256>.authenticate(key: key, message: m) == theirs,131                "key=\(Hex.encode(key)) message=\(Hex.encode(m))")132        }133        #expect(tally.finish() == 0)134    }135136    @Test func hmacSHA512() {137        let seed = DiffSeed.make("ck-hmac512")138        var rng = AuditRNG(seed: seed)139        var tally = DiffTally("cryptokit-hmac-sha512", algorithm: "HMAC-SHA-512", oracle: cryptoKit, seed: seed)140        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {141            let key = rng.bytes(rng.edgeLength(block: 128, max: 300)), m = rng.bytes(rng.edgeLength(block: 128))142            let theirs = Bytes(CryptoKit.HMAC<CryptoKit.SHA512>.authenticationCode(for: Data(m), using: SymmetricKey(data: Data(key))))143            tally.check(QyvoraSymmetric.HMAC<QyvoraSymmetric.SHA512>.authenticate(key: key, message: m) == theirs,144                "key=\(Hex.encode(key)) message=\(Hex.encode(m))")145        }146        #expect(tally.finish() == 0)147    }148149    @Test func hkdfSHA256() {150        let seed = DiffSeed.make("ck-hkdf256")151        var rng = AuditRNG(seed: seed)152        var tally = DiffTally("cryptokit-hkdf-sha256", algorithm: "HKDF-SHA-256", oracle: cryptoKit, seed: seed)153        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {154            let ikm = rng.bytes(rng.int(0...100)), salt = rng.bytes(rng.pick([0, 1, 16, 32, 64, 65, 100])), info = rng.bytes(rng.int(0...80))155            let length = rng.pick([1, 16, 31, 32, 33, 64, 100, 255, 32 * 255])156            let theirs = raw(CryptoKit.HKDF<CryptoKit.SHA256>.deriveKey(157                inputKeyMaterial: SymmetricKey(data: Data(ikm)), salt: Data(salt), info: Data(info), outputByteCount: length))158            let ours = QyvoraSymmetric.HKDF<QyvoraSymmetric.SHA256>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: length)159            let prk = Bytes(CryptoKit.HKDF<CryptoKit.SHA256>.extract(inputKeyMaterial: SymmetricKey(data: Data(ikm)), salt: Data(salt)))160            let ok = ours == theirs && QyvoraSymmetric.HKDF<QyvoraSymmetric.SHA256>.extract(salt: salt, inputKeyMaterial: ikm) == prk161            tally.check(ok, "ikm=\(Hex.encode(ikm)) salt=\(Hex.encode(salt)) info=\(Hex.encode(info)) length=\(length)")162        }163        #expect(tally.finish() == 0)164    }165166    @Test func hkdfSHA512() {167        let seed = DiffSeed.make("ck-hkdf512")168        var rng = AuditRNG(seed: seed)169        var tally = DiffTally("cryptokit-hkdf-sha512", algorithm: "HKDF-SHA-512", oracle: cryptoKit, seed: seed)170        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {171            let ikm = rng.bytes(rng.int(0...150)), salt = rng.bytes(rng.pick([0, 1, 32, 64, 128, 129, 200])), info = rng.bytes(rng.int(0...80))172            let length = rng.pick([1, 32, 63, 64, 65, 128, 200, 64 * 255])173            let theirs = raw(CryptoKit.HKDF<CryptoKit.SHA512>.deriveKey(174                inputKeyMaterial: SymmetricKey(data: Data(ikm)), salt: Data(salt), info: Data(info), outputByteCount: length))175            let ours = QyvoraSymmetric.HKDF<QyvoraSymmetric.SHA512>.deriveKey(inputKeyMaterial: ikm, salt: salt, info: info, length: length)176            tally.check(ours == theirs, "ikm=\(Hex.encode(ikm)) salt=\(Hex.encode(salt)) info=\(Hex.encode(info)) length=\(length)")177        }178        #expect(tally.finish() == 0)179    }180181    // MARK: AEAD182183    /// Both directions, with associated data, then a tampered message that both sides must refuse.184    @Test func aesGCM() throws {185        for keySize in [16, 24, 32] {186            let seed = DiffSeed.make("ck-aesgcm-\(keySize)")187            var rng = AuditRNG(seed: seed)188            var tally = DiffTally("cryptokit-aes-gcm-\(keySize * 8)", algorithm: "AES-GCM", parameterSet: "AES-\(keySize * 8), 96-bit nonce", oracle: cryptoKit, seed: seed)189            for _ in 0..<AuditMode.cases(quick: 1500, full: 15000) {190                let key = rng.bytes(keySize), nonce = rng.bytes(12)191                let pt = rng.bytes(rng.edgeLength(block: 16, max: 300)), aad = rng.bytes(rng.edgeLength(block: 16, max: 80))192                let detail = "key=\(Hex.encode(key)) nonce=\(Hex.encode(nonce)) plaintext=\(Hex.encode(pt)) aad=\(Hex.encode(aad))"193                var ok = true194                // ours → CryptoKit195                let gcm = try AESGCM(key: key)196                let sealed = try gcm.seal(nonce: nonce, plaintext: pt, associatedData: aad)197                let theirs = try CryptoKit.AES.GCM.seal(Data(pt), using: SymmetricKey(data: Data(key)), nonce: CryptoKit.AES.GCM.Nonce(data: Data(nonce)), authenticating: Data(aad))198                ok = ok && Bytes(theirs.ciphertext) == sealed.ciphertext && Bytes(theirs.tag) == sealed.tag199                let box = try CryptoKit.AES.GCM.SealedBox(nonce: CryptoKit.AES.GCM.Nonce(data: Data(nonce)), ciphertext: Data(sealed.ciphertext), tag: Data(sealed.tag))200                ok = ok && (try? CryptoKit.AES.GCM.open(box, using: SymmetricKey(data: Data(key)), authenticating: Data(aad))).map { Bytes($0) } == pt201                // CryptoKit → ours202                ok = ok && (try? gcm.open(nonce: nonce, ciphertext: Bytes(theirs.ciphertext), tag: Bytes(theirs.tag), associatedData: aad)) == pt203                // tampering: one bit of the ciphertext, the tag, the associated data or the nonce204                var ct = sealed.ciphertext, tag = sealed.tag, ad = aad, n = nonce205                switch rng.int(0...3) {206                case 0 where !ct.isEmpty: ct[rng.int(0...(ct.count - 1))] ^= 1 << UInt8(rng.int(0...7))207                case 1 where !ad.isEmpty: ad[rng.int(0...(ad.count - 1))] ^= 1 << UInt8(rng.int(0...7))208                case 2: n[rng.int(0...11)] ^= 1 << UInt8(rng.int(0...7))209                default: tag[rng.int(0...15)] ^= 1 << UInt8(rng.int(0...7))210                }211                let oursRefuses = (try? gcm.open(nonce: n, ciphertext: ct, tag: tag, associatedData: ad)) == nil212                let badBox = try CryptoKit.AES.GCM.SealedBox(nonce: CryptoKit.AES.GCM.Nonce(data: Data(n)), ciphertext: Data(ct), tag: Data(tag))213                let theirsRefuses = (try? CryptoKit.AES.GCM.open(badBox, using: SymmetricKey(data: Data(key)), authenticating: Data(ad))) == nil214                ok = ok && oursRefuses && theirsRefuses215                tally.check(ok, detail)216            }217            #expect(tally.finish() == 0)218        }219    }220221    @Test func chaCha20Poly1305() throws {222        let seed = DiffSeed.make("ck-chachapoly")223        var rng = AuditRNG(seed: seed)224        var tally = DiffTally("cryptokit-chacha20-poly1305", algorithm: "ChaCha20-Poly1305", parameterSet: "RFC 8439, 96-bit nonce", oracle: cryptoKit, seed: seed)225        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {226            let key = rng.bytes(32), nonce = rng.bytes(12)227            let pt = rng.bytes(rng.edgeLength(block: 64, max: 300)), aad = rng.bytes(rng.edgeLength(block: 16, max: 80))228            let detail = "key=\(Hex.encode(key)) nonce=\(Hex.encode(nonce)) plaintext=\(Hex.encode(pt)) aad=\(Hex.encode(aad))"229            var ok = true230            let sealed = try ChaCha20Poly1305.seal(key: key, nonce: nonce, plaintext: pt, associatedData: aad)231            let theirs = try ChaChaPoly.seal(Data(pt), using: SymmetricKey(data: Data(key)), nonce: ChaChaPoly.Nonce(data: Data(nonce)), authenticating: Data(aad))232            ok = ok && Bytes(theirs.ciphertext) == sealed.ciphertext && Bytes(theirs.tag) == sealed.tag233            ok = ok && (try? ChaCha20Poly1305.open(key: key, nonce: nonce, ciphertext: Bytes(theirs.ciphertext), tag: Bytes(theirs.tag), associatedData: aad)) == pt234            var ct = sealed.ciphertext, tag = sealed.tag, ad = aad235            switch rng.int(0...2) {236            case 0 where !ct.isEmpty: ct[rng.int(0...(ct.count - 1))] ^= 1 << UInt8(rng.int(0...7))237            case 1 where !ad.isEmpty: ad[rng.int(0...(ad.count - 1))] ^= 1 << UInt8(rng.int(0...7))238            default: tag[rng.int(0...15)] ^= 1 << UInt8(rng.int(0...7))239            }240            let oursRefuses = (try? ChaCha20Poly1305.open(key: key, nonce: nonce, ciphertext: ct, tag: tag, associatedData: ad)) == nil241            let badBox = try ChaChaPoly.SealedBox(nonce: ChaChaPoly.Nonce(data: Data(nonce)), ciphertext: Data(ct), tag: Data(tag))242            let theirsRefuses = (try? ChaChaPoly.open(badBox, using: SymmetricKey(data: Data(key)), authenticating: Data(ad))) == nil243            tally.check(ok && oursRefuses && theirsRefuses, detail)244        }245        #expect(tally.finish() == 0)246    }247248    // MARK: ML-KEM (FIPS 203) — CryptoKit offers 768 and 1024249250    @Test func mlkem768() throws {251        let seed = DiffSeed.make("ck-mlkem768")252        var rng = AuditRNG(seed: seed)253        var tally = DiffTally("cryptokit-ml-kem-768", algorithm: "ML-KEM", parameterSet: "ML-KEM-768", oracle: cryptoKit, seed: seed)254        for _ in 0..<AuditMode.cases(quick: 1000, full: 10000) {255            let dz = rng.bytes(64), m = rng.bytes(32)256            var ok = true257            // key generation from the seed d ‖ z258            let ours = try MLKEM.keyPair(.mlkem768, seed: dz)259            let theirs = try MLKEM768.PrivateKey(seedRepresentation: Data(dz), publicKey: nil)260            ok = ok && Bytes(theirs.publicKey.rawRepresentation) == ours.encapsulationKey261            // our encapsulation (fixed m), CryptoKit decapsulation262            let enc = try MLKEM.encapsInternal(.mlkem768, encapsulationKey: ours.encapsulationKey, m: m)263            ok = try ok && raw(theirs.decapsulate(Data(enc.ciphertext))) == enc.sharedSecret264            // CryptoKit encapsulation, our decapsulation265            let r = try theirs.publicKey.encapsulate()266            ok = try ok && MLKEM.decapsulate(.mlkem768, decapsulationKey: ours.decapsulationKey, ciphertext: Bytes(r.encapsulated)) == raw(r.sharedSecret)267            // implicit rejection: a mutated ciphertext gives the same pseudorandom secret on both sides268            var bad = enc.ciphertext269            bad[rng.int(0...(bad.count - 1))] ^= 1 << UInt8(rng.int(0...7))270            let k1 = try MLKEM.decapsulate(.mlkem768, decapsulationKey: ours.decapsulationKey, ciphertext: bad)271            ok = try ok && k1 == raw(theirs.decapsulate(Data(bad))) && k1 != enc.sharedSecret272            tally.check(ok, "seed(d‖z)=\(Hex.encode(dz)) m=\(Hex.encode(m))")273        }274        #expect(tally.finish() == 0)275    }276277    @Test func mlkem1024() throws {278        let seed = DiffSeed.make("ck-mlkem1024")279        var rng = AuditRNG(seed: seed)280        var tally = DiffTally("cryptokit-ml-kem-1024", algorithm: "ML-KEM", parameterSet: "ML-KEM-1024", oracle: cryptoKit, seed: seed)281        for _ in 0..<AuditMode.cases(quick: 1000, full: 10000) {282            let dz = rng.bytes(64), m = rng.bytes(32)283            var ok = true284            let ours = try MLKEM.keyPair(.mlkem1024, seed: dz)285            let theirs = try MLKEM1024.PrivateKey(seedRepresentation: Data(dz), publicKey: nil)286            ok = ok && Bytes(theirs.publicKey.rawRepresentation) == ours.encapsulationKey287            let enc = try MLKEM.encapsInternal(.mlkem1024, encapsulationKey: ours.encapsulationKey, m: m)288            ok = try ok && raw(theirs.decapsulate(Data(enc.ciphertext))) == enc.sharedSecret289            let r = try theirs.publicKey.encapsulate()290            ok = try ok && MLKEM.decapsulate(.mlkem1024, decapsulationKey: ours.decapsulationKey, ciphertext: Bytes(r.encapsulated)) == raw(r.sharedSecret)291            var bad = enc.ciphertext292            bad[rng.int(0...(bad.count - 1))] ^= 1 << UInt8(rng.int(0...7))293            let k1 = try MLKEM.decapsulate(.mlkem1024, decapsulationKey: ours.decapsulationKey, ciphertext: bad)294            ok = try ok && k1 == raw(theirs.decapsulate(Data(bad))) && k1 != enc.sharedSecret295            tally.check(ok, "seed(d‖z)=\(Hex.encode(dz)) m=\(Hex.encode(m))")296        }297        #expect(tally.finish() == 0)298    }299300    /// Encapsulation keys with a coefficient ≥ q, or of the wrong length, must be refused by both sides.301    @Test func mlkemKeyValidationAgreement() throws {302        let seed = DiffSeed.make("ck-mlkem-validate")303        var rng = AuditRNG(seed: seed)304        var tally = DiffTally("cryptokit-ml-kem-key-check", algorithm: "ML-KEM", parameterSet: "ML-KEM-768 / 1024 encapsulation-key check", oracle: cryptoKit, seed: seed)305        for _ in 0..<AuditMode.cases(quick: 400, full: 4000) {306            let big = rng.bool()307            var ek = try MLKEM.keyPair(big ? .mlkem1024 : .mlkem768, seed: rng.bytes(64)).encapsulationKey308            switch rng.int(0...3) {309            case 0:  // force one 12-bit coefficient to a value in [q, 4095]310                let c = rng.int(0...(((ek.count - 32) * 8 / 12) - 1)), v = rng.int(3329...4095)311                let bit = c * 12, byte = bit / 8312                if bit % 8 == 0 {313                    ek[byte] = UInt8(v & 0xff)314                    ek[byte + 1] = (ek[byte + 1] & 0xf0) | UInt8(v >> 8)315                } else {316                    ek[byte] = (ek[byte] & 0x0f) | UInt8((v & 0x0f) << 4)317                    ek[byte + 1] = UInt8(v >> 4)318                }319            case 1: ek.removeLast(rng.int(1...40))320            case 2: ek.append(contentsOf: rng.bytes(rng.int(1...40)))321            default: ek[rng.int(0...(ek.count - 1))] ^= 1 << UInt8(rng.int(0...7))  // usually still valid322            }323            let oursValid = MLKEM.isValidEncapsulationKey(big ? .mlkem1024 : .mlkem768, ek)324            tally.verdict(oursValid)325            let theirsValid: Bool326            if big {327                theirsValid = (try? MLKEM1024.PublicKey(rawRepresentation: Data(ek)).encapsulate()) != nil328            } else {329                theirsValid = (try? MLKEM768.PublicKey(rawRepresentation: Data(ek)).encapsulate()) != nil330            }331            tally.check(oursValid == theirsValid, "parameterSet=\(big ? 1024 : 768) ours=\(oursValid) cryptokit=\(theirsValid) ek=\(Hex.encode(ek))")332        }333        #expect(tally.finish() == 0)334    }335336    // MARK: ML-DSA (FIPS 204) — CryptoKit offers 65 and 87337338    @Test func mldsa65() throws {339        let seed = DiffSeed.make("ck-mldsa65")340        var rng = AuditRNG(seed: seed)341        var tally = DiffTally("cryptokit-ml-dsa-65", algorithm: "ML-DSA", parameterSet: "ML-DSA-65", oracle: cryptoKit, seed: seed)342        for _ in 0..<AuditMode.cases(quick: 400, full: 4000) {343            let xi = rng.bytes(32), message = rng.bytes(rng.int(0...400)), context = rng.bytes(rng.pick([0, 0, 1, 17, 255]))344            var ok = true345            let ours = try MLDSA.keyGenInternal(.mldsa65, seed: xi)346            let theirs = try CryptoKit.MLDSA65.PrivateKey(seedRepresentation: Data(xi), publicKey: nil)347            ok = ok && Bytes(theirs.publicKey.rawRepresentation) == ours.publicKey348            // our signature (deterministic and hedged with a fixed rnd), CryptoKit verification349            let s1 = try MLDSA.sign(.mldsa65, privateKey: ours.privateKey, message: message, context: context, randomness: .deterministic)350            let s2 = try MLDSA.sign(.mldsa65, privateKey: ours.privateKey, message: message, context: context, randomness: .explicit(rng.bytes(32)))351            ok = ok && theirs.publicKey.isValidSignature(Data(s1), for: Data(message), context: Data(context))352            ok = ok && theirs.publicKey.isValidSignature(Data(s2), for: Data(message), context: Data(context))353            // CryptoKit signature, our verification354            let s3 = Bytes(try theirs.signature(for: Data(message), context: Data(context)))355            ok = ok && MLDSA.verify(.mldsa65, publicKey: ours.publicKey, message: message, signature: s3, context: context)356            // tampering must be refused by both357            var bad = s3358            bad[rng.int(0...(bad.count - 1))] ^= 1 << UInt8(rng.int(0...7))359            ok = ok && !MLDSA.verify(.mldsa65, publicKey: ours.publicKey, message: message, signature: bad, context: context)360            ok = ok && !theirs.publicKey.isValidSignature(Data(bad), for: Data(message), context: Data(context))361            ok = ok && !MLDSA.verify(.mldsa65, publicKey: ours.publicKey, message: message + [0], signature: s3, context: context)362            if context.count < 255 {  // a different context must not verify363                ok = ok && !MLDSA.verify(.mldsa65, publicKey: ours.publicKey, message: message, signature: s3, context: context + [1])364            }365            tally.check(ok, "xi=\(Hex.encode(xi)) message=\(Hex.encode(message)) context=\(Hex.encode(context))")366        }367        #expect(tally.finish() == 0)368    }369370    @Test func mldsa87() throws {371        let seed = DiffSeed.make("ck-mldsa87")372        var rng = AuditRNG(seed: seed)373        var tally = DiffTally("cryptokit-ml-dsa-87", algorithm: "ML-DSA", parameterSet: "ML-DSA-87", oracle: cryptoKit, seed: seed)374        for _ in 0..<AuditMode.cases(quick: 400, full: 4000) {375            let xi = rng.bytes(32), message = rng.bytes(rng.int(0...400)), context = rng.bytes(rng.pick([0, 0, 1, 17, 255]))376            var ok = true377            let ours = try MLDSA.keyGenInternal(.mldsa87, seed: xi)378            let theirs = try CryptoKit.MLDSA87.PrivateKey(seedRepresentation: Data(xi), publicKey: nil)379            ok = ok && Bytes(theirs.publicKey.rawRepresentation) == ours.publicKey380            let s1 = try MLDSA.sign(.mldsa87, privateKey: ours.privateKey, message: message, context: context, randomness: .deterministic)381            let s2 = try MLDSA.sign(.mldsa87, privateKey: ours.privateKey, message: message, context: context, randomness: .explicit(rng.bytes(32)))382            ok = ok && theirs.publicKey.isValidSignature(Data(s1), for: Data(message), context: Data(context))383            ok = ok && theirs.publicKey.isValidSignature(Data(s2), for: Data(message), context: Data(context))384            let s3 = Bytes(try theirs.signature(for: Data(message), context: Data(context)))385            ok = ok && MLDSA.verify(.mldsa87, publicKey: ours.publicKey, message: message, signature: s3, context: context)386            var bad = s3387            bad[rng.int(0...(bad.count - 1))] ^= 1 << UInt8(rng.int(0...7))388            ok = ok && !MLDSA.verify(.mldsa87, publicKey: ours.publicKey, message: message, signature: bad, context: context)389            ok = ok && !theirs.publicKey.isValidSignature(Data(bad), for: Data(message), context: Data(context))390            ok = ok && !MLDSA.verify(.mldsa87, publicKey: ours.publicKey, message: message + [0], signature: s3, context: context)391            tally.check(ok, "xi=\(Hex.encode(xi)) message=\(Hex.encode(message)) context=\(Hex.encode(context))")392        }393        #expect(tally.finish() == 0)394    }395}396397@Suite struct CommonCryptoDifferential {398    private func ccPBKDF2(_ prf: CCPseudoRandomAlgorithm, _ password: Bytes, _ salt: Bytes, _ iterations: Int, _ length: Int) -> Bytes {399        var out = Bytes(repeating: 0, count: length)400        let status = password.withUnsafeBufferPointer { pw in401            pw.withMemoryRebound(to: CChar.self) { pwc in402                CCKeyDerivationPBKDF(403                    CCPBKDFAlgorithm(kCCPBKDF2), pwc.baseAddress, password.count, salt, salt.count, prf, UInt32(iterations), &out, length)404            }405        }406        return status == kCCSuccess ? out : []407    }408409    /// The BIP-39 seed derivation: PBKDF2-HMAC-SHA512, 2048 iterations, 64 bytes.410    @Test func pbkdf2SHA512BIP39Shape() {411        let seed = DiffSeed.make("cc-pbkdf2-bip39")412        var rng = AuditRNG(seed: seed)413        var tally = DiffTally("commoncrypto-pbkdf2-sha512-2048", algorithm: "PBKDF2-HMAC-SHA-512", parameterSet: "2048 iterations, 64 bytes (BIP-39)", oracle: commonCrypto, seed: seed)414        for _ in 0..<AuditMode.cases(quick: 150, full: 1500) {415            // CommonCrypto refuses an empty password pointer: at least one byte416            let password = rng.bytes(rng.pick([1, 8, 80, 127, 128, 129, 200, 300])), salt = rng.bytes(rng.int(8...60))417            let ours = PBKDF2<QyvoraSymmetric.SHA512>.deriveKey(password: password, salt: salt, iterations: 2048, length: 64)418            tally.check(ours == ccPBKDF2(CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512), password, salt, 2048, 64),419                "password=\(Hex.encode(password)) salt=\(Hex.encode(salt))")420        }421        #expect(tally.finish() == 0)422    }423424    @Test func pbkdf2Varied() {425        let seed = DiffSeed.make("cc-pbkdf2-varied")426        var rng = AuditRNG(seed: seed)427        var tally = DiffTally("commoncrypto-pbkdf2-varied", algorithm: "PBKDF2-HMAC-SHA-256 / SHA-512", parameterSet: "1–50 iterations, 1–200 bytes", oracle: commonCrypto, seed: seed)428        for _ in 0..<AuditMode.cases(quick: 1500, full: 15000) {429            let password = rng.bytes(rng.pick([1, 5, 63, 64, 65, 127, 128, 129, 250])), salt = rng.bytes(rng.int(1...100))430            let iterations = rng.int(1...50), length = rng.pick([1, 20, 31, 32, 33, 63, 64, 65, 100, 200])431            let ok: Bool432            if rng.bool() {433                ok = PBKDF2<QyvoraSymmetric.SHA256>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)434                    == ccPBKDF2(CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), password, salt, iterations, length)435            } else {436                ok = PBKDF2<QyvoraSymmetric.SHA512>.deriveKey(password: password, salt: salt, iterations: iterations, length: length)437                    == ccPBKDF2(CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512), password, salt, iterations, length)438            }439            tally.check(ok, "password=\(Hex.encode(password)) salt=\(Hex.encode(salt)) iterations=\(iterations) length=\(length)")440        }441        #expect(tally.finish() == 0)442    }443444    @Test func sha2AndHMAC() {445        let seed = DiffSeed.make("cc-sha2-hmac")446        var rng = AuditRNG(seed: seed)447        var tally = DiffTally("commoncrypto-sha2-hmac", algorithm: "SHA-224 / SHA-256 / SHA-384 / SHA-512, HMAC-SHA-256 / 512", oracle: commonCrypto, seed: seed)448        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {449            let m = rng.bytes(rng.edgeLength(block: 64)), key = rng.bytes(rng.edgeLength(block: 64, max: 200))450            var d224 = Bytes(repeating: 0, count: 28), d256 = Bytes(repeating: 0, count: 32)451            var d384 = Bytes(repeating: 0, count: 48), d512 = Bytes(repeating: 0, count: 64)452            var h256 = Bytes(repeating: 0, count: 32), h512 = Bytes(repeating: 0, count: 64)453            CC_SHA224(m, CC_LONG(m.count), &d224)454            CC_SHA256(m, CC_LONG(m.count), &d256)455            CC_SHA384(m, CC_LONG(m.count), &d384)456            CC_SHA512(m, CC_LONG(m.count), &d512)457            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key, key.count, m, m.count, &h256)458            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA512), key, key.count, m, m.count, &h512)459            let ok = QyvoraSymmetric.SHA224.hash(m) == d224 && QyvoraSymmetric.SHA256.hash(m) == d256460                && QyvoraSymmetric.SHA384.hash(m) == d384 && QyvoraSymmetric.SHA512.hash(m) == d512461                && QyvoraSymmetric.HMAC<QyvoraSymmetric.SHA256>.authenticate(key: key, message: m) == h256462                && QyvoraSymmetric.HMAC<QyvoraSymmetric.SHA512>.authenticate(key: key, message: m) == h512463            tally.check(ok, "key=\(Hex.encode(key)) message=\(Hex.encode(m))")464        }465        #expect(tally.finish() == 0)466    }467}468
Files main
Menu

Theme