xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Tests / XToolTests / CertificateTests.swift
CertificateTests.swift57 lines · 2.2 KiBRaw
| 1 | import Foundation |
| 2 | import Testing |
| 3 | import Crypto |
| 4 | import X509 |
| 5 | import XKit |
| 6 | |
| 7 | // serial number from https://github.com/xtool-org/xtool/issues/305 |
| 8 | private let leadingZeroSerial: [UInt8] = [ |
| 9 | 0x03, 0x37, 0x42, 0x57, 0x0D, 0x6F, 0x96, 0x84, |
| 10 | 0xA2, 0x33, 0x11, 0x71, 0x19, 0x56, 0xA0, 0x84, |
| 11 | ] |
| 12 | |
| 13 | @Test func serialNumberKeepsLeadingZeroNibble() throws { |
| 14 | let certificate = try makeCertificate(serialNumber: leadingZeroSerial) |
| 15 | #expect(certificate.serialNumber() == "033742570D6F9684A23311711956A084") |
| 16 | } |
| 17 | |
| 18 | @Test func serialNumberOmitsDERSignPadding() throws { |
| 19 | // the high bit is set, so DER encodes this serial with a leading 0x00 byte |
| 20 | var serial = leadingZeroSerial |
| 21 | serial[0] = 0x83 |
| 22 | let certificate = try makeCertificate(serialNumber: serial) |
| 23 | #expect(certificate.serialNumber() == "833742570D6F9684A23311711956A084") |
| 24 | } |
| 25 | |
| 26 | @Test func hasSerialNumberIgnoresCaseAndLeadingZeros() throws { |
| 27 | let certificate = try makeCertificate(serialNumber: leadingZeroSerial) |
| 28 | #expect(certificate.hasSerialNumber("033742570D6F9684A23311711956A084")) |
| 29 | #expect(certificate.hasSerialNumber("033742570d6f9684a23311711956a084")) |
| 30 | #expect(certificate.hasSerialNumber("33742570D6F9684A23311711956A084")) |
| 31 | #expect(certificate.hasSerialNumber("0033742570D6F9684A23311711956A084")) |
| 32 | #expect(!certificate.hasSerialNumber("133742570D6F9684A23311711956A084")) |
| 33 | #expect(!certificate.hasSerialNumber("")) |
| 34 | } |
| 35 | |
| 36 | /// Creates a self-signed certificate and round-trips it through DER, |
| 37 | /// like the certificates we get from the developer API. |
| 38 | private func makeCertificate(serialNumber: [UInt8]) throws -> XKit.Certificate { |
| 39 | let key = P256.Signing.PrivateKey() |
| 40 | let name = try DistinguishedName { |
| 41 | CommonName("xtool tests") |
| 42 | } |
| 43 | let now = Date() |
| 44 | let certificate = try X509.Certificate( |
| 45 | version: .v3, |
| 46 | serialNumber: .init(bytes: serialNumber), |
| 47 | publicKey: .init(key.publicKey), |
| 48 | notValidBefore: now, |
| 49 | notValidAfter: now + 3600, |
| 50 | issuer: name, |
| 51 | subject: name, |
| 52 | signatureAlgorithm: .ecdsaWithSHA256, |
| 53 | extensions: .init(), |
| 54 | issuerPrivateKey: .init(key) |
| 55 | ) |
| 56 | return try XKit.Certificate(data: XKit.Certificate(raw: certificate).data()) |
| 57 | } |