SPB Git

Repository Public

CryptoTests.swift 10.2 KB 210 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVaultTests/CryptoTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//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 Testing44@testable import SPVault4546@Suite("Cryptography")47struct CryptoTests {48    let key = VaultCrypto.randomKey()49    let context = Data("vault|card|meta".utf8)50    let message = Data("ALEX SPECIMEN 4242 4242 4242 4242".utf8)5152    @Test func sealAndOpenRoundTrip() throws {53        let sealed = try SealedBlob.seal(message, key: key, kind: .metadata, context: context)54        #expect(sealed.count == message.count + SealedBlob.overhead)55        #expect(sealed.range(of: Data("SPECIMEN".utf8)) == nil)56        #expect(try SealedBlob.open(sealed, key: key, kind: .metadata, context: context) == message)57    }5859    @Test func everyNonceIsFresh() throws {60        var nonces = Set<Data>()61        for _ in 0..<500 {62            let sealed = try SealedBlob.seal(message, key: key, kind: .image, context: context)63            nonces.insert(sealed.subdata(in: 6..<18))64        }65        #expect(nonces.count == 500)66    }6768    @Test func alteringAnyByteIsDetected() throws {69        let sealed = try SealedBlob.seal(message, key: key, kind: .metadata, context: context)70        for index in stride(from: 0, to: sealed.count, by: 3) {71            var tampered = sealed72            tampered[index] ^= 0x4073            #expect(throws: VaultCryptoError.self) {74                try SealedBlob.open(tampered, key: key, kind: .metadata, context: context)75            }76        }77        #expect(throws: VaultCryptoError.self) { try SealedBlob.open(sealed.dropLast(), key: key, kind: .metadata, context: context) }78    }7980    @Test func wrongKeyIsRejected() throws {81        let sealed = try SealedBlob.seal(message, key: key, kind: .metadata, context: context)82        #expect(throws: VaultCryptoError.authenticationFailed) {83            try SealedBlob.open(sealed, key: VaultCrypto.randomKey(), kind: .metadata, context: context)84        }85    }8687    @Test func contextAndKindAreBound() throws {88        let sealed = try SealedBlob.seal(message, key: key, kind: .metadata, context: context)89        #expect(throws: VaultCryptoError.authenticationFailed) {90            try SealedBlob.open(sealed, key: key, kind: .metadata, context: Data("vault|other-card|meta".utf8))91        }92        #expect(throws: VaultCryptoError.wrongKind) { try SealedBlob.open(sealed, key: key, kind: .image, context: context) }93    }9495    @Test func versionAndShapeAreChecked() throws {96        var sealed = try SealedBlob.seal(message, key: key, kind: .metadata, context: context)97        sealed[4] = 998        #expect(throws: VaultCryptoError.unsupportedVersion(9)) { try SealedBlob.open(sealed, key: key, kind: .metadata, context: context) }99        #expect(throws: VaultCryptoError.malformed) { try SealedBlob.open(Data("nope".utf8), key: key, kind: .metadata, context: context) }100        #expect(throws: VaultCryptoError.malformed) { try SealedBlob.open(Data(repeating: 0, count: 80), key: key, kind: .metadata, context: context) }101    }102103    @Test func emptyPlaintextIsSupported() throws {104        let sealed = try SealedBlob.seal(Data(), key: key, kind: .manifest, context: context)105        #expect(try SealedBlob.open(sealed, key: key, kind: .manifest, context: context).isEmpty)106    }107108    /// RFC 7914 §11, PBKDF2-HMAC-SHA256 test vector (P = "passwd", S = "salt", c = 1).109    @Test func pbkdf2MatchesPublishedVector() throws {110        let derived = try VaultCrypto.deriveKey(passphrase: "passwd", salt: Data("salt".utf8), iterations: 1)111        let hex = VaultCrypto.keyData(derived).map { String(format: "%02x", $0) }.joined()112        #expect(hex == "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc")113    }114115    /// RFC 7914 §11, second vector (P = "Password", S = "NaCl", c = 80000).116    @Test func pbkdf2MatchesSecondVector() throws {117        let derived = try VaultCrypto.deriveKey(passphrase: "Password", salt: Data("NaCl".utf8), iterations: 80_000)118        let hex = VaultCrypto.keyData(derived).map { String(format: "%02x", $0) }.joined()119        #expect(hex == "4ddcd8f60b98be21830cee5ef22701f9641a4418d04c0414aeff08876b34ab56")120    }121122    @Test func kdfParametersRejectWeakSettings() throws {123        let weak = KDFParameters(algorithm: KDFParameters.algorithmName, iterations: 10, salt: try VaultCrypto.randomBytes(32))124        #expect(throws: VaultCryptoError.keyDerivationFailed) { try weak.key(for: "anything") }125        let unknown = KDFParameters(algorithm: "md5", iterations: 600_000, salt: try VaultCrypto.randomBytes(32))126        #expect(throws: VaultCryptoError.keyDerivationFailed) { try unknown.key(for: "anything") }127        #expect(KDFParameters.defaultIterations >= 600_000)128    }129130    @Test func subkeysDifferByPurposeAndSalt() {131        let a = VaultCrypto.subkey(key, salt: Data([1]), purpose: "a"), b = VaultCrypto.subkey(key, salt: Data([1]), purpose: "b")132        let c = VaultCrypto.subkey(key, salt: Data([2]), purpose: "a")133        #expect(VaultCrypto.keyData(a) != VaultCrypto.keyData(b))134        #expect(VaultCrypto.keyData(a) != VaultCrypto.keyData(c))135        #expect(VaultCrypto.keyData(a) == VaultCrypto.keyData(VaultCrypto.subkey(key, salt: Data([1]), purpose: "a")))136    }137138    @Test func passphrasePolicy() {139        #expect(PassphrasePolicy.strength(of: "short") == .tooWeak)140        #expect(!PassphrasePolicy.isAcceptable("aaaaaaaaaaaaaaaa"))141        #expect(!PassphrasePolicy.isAcceptable("123456789012"))142        #expect(PassphrasePolicy.isAcceptable("correct horse battery staple 42"))143        #expect(PassphrasePolicy.isAcceptable("T9#vLq2!xWm8zR"))144    }145}146147@Suite("Sensitive data policy")148struct SensitiveDataPolicyTests {149    @Test func securityCodesAndPINsAreRefused() {150        for label in ["CVV", "cvc2", "Security code", "Code de sécurité", "PIN", "NIP", "Card PIN", "CID"] {151            #expect(SensitiveDataPolicy.isForbiddenLabel(label), "\(label)")152        }153        for label in ["Class", "Group number", "Shipping", "Opinion", "Pinnacle tier"] {154            #expect(!SensitiveDataPolicy.isForbiddenLabel(label), "\(label)")155        }156    }157158    @Test func validationAndSanitising() throws {159        var card = Card(name: "Test", kind: .creditCard)160        card.fields = [CardField(label: "CVV", value: "737"), CardField(label: "Tier", value: "Gold")]161        #expect(throws: SensitiveDataPolicy.Violation.forbiddenLabel("CVV")) { try SensitiveDataPolicy.validate(card) }162        let clean = SensitiveDataPolicy.sanitized(card)163        #expect(clean.fields.map(\.label) == ["Tier"])164        try SensitiveDataPolicy.validate(clean)165    }166167    @Test func magneticStripeDataIsRefused() {168        var card = Card(name: "Test", kind: .creditCard)169        card.notes = "%B4242424242424242^SPECIMEN/ALEX^28051010000000000?"170        #expect(throws: SensitiveDataPolicy.Violation.magneticStripeData) { try SensitiveDataPolicy.validate(card) }171        #expect(SensitiveDataPolicy.looksLikeMagneticStripe(";4242424242424242=28051010000?"))172        #expect(!SensitiveDataPolicy.looksLikeMagneticStripe("Call 1 800 555 0199"))173    }174175    @Test func luhnAndNetworks() {176        #expect(PaymentCard.isValidNumber("4242 4242 4242 4242"))177        #expect(PaymentCard.isValidNumber("378282246310005"))178        #expect(!PaymentCard.isValidNumber("4242 4242 4242 4243"))179        #expect(!PaymentCard.isValidNumber("1234"))180        #expect(PaymentCard.network(for: "4242424242424242") == "Visa")181        #expect(PaymentCard.network(for: "5555555555554444") == "Mastercard")182        #expect(PaymentCard.network(for: "378282246310005") == "American Express")183    }184185    @Test func numbersAreMaskedInPreviews() {186        var card = Card(name: "Test", kind: .creditCard)187        card.number = "4242424242424242"188        #expect(card.last4 == "4242")189        #expect(card.maskedNumber == "•••• •••• •••• 4242")190        #expect(!card.maskedNumber.contains("42424242"))191        #expect(card.formattedNumber == "4242 4242 4242 4242")192        card.number = "378282246310005"193        #expect(card.formattedNumber == "3782 822463 10005")194        var passport = Card(name: "Passport", kind: .passport)195        passport.number = "NW4821973"196        #expect(passport.maskedNumber.hasSuffix("1973"))197        #expect(!passport.maskedNumber.contains("NW48"))198    }199200    @Test func formatsKeepPhysicalProportions() {201        #expect(abs(CardFormat.id1.aspectRatio - 85.60 / 53.98) < 1e-9)202        #expect(abs(CardFormat.id3.aspectRatio - 125.0 / 88.0) < 1e-9)203        #expect(CardFormat.matching(aspect: 1.59) == .id1)204        #expect(CardFormat.matching(aspect: 1.42) == .id3)205        #expect(CardFormat.matching(aspect: 1.0) == .custom(aspect: 1.0))206        #expect(CardKind.passport.defaultFormat == .id3)207        for kind in CardKind.allCases { #expect(CardCategory.builtIn.contains { $0.id == kind.categoryID }) }208    }209}210
Files main
Menu

Theme