Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / XKit / Model / Certificate.swift

Certificate.swift89 lines · 2.6 KiBRaw
1//
2// Certificate.swift
3// Supercharge
4//
5// Created by Kabir Oberai on 07/10/19.
6// Copyright © 2019 Kabir Oberai. All rights reserved.
7//
8
9import Foundation
10import X509
11import SwiftASN1
12
13/// A certificate in DER format
14public struct Certificate: Codable, Sendable {
15
16 public enum Error: Swift.Error {
17 case invalidCertificate
18 }
19
20 let raw: X509.Certificate
21
22 public init(raw: X509.Certificate) throws {
23 self.raw = raw
24 }
25
26 public init(data: Data) throws {
27 try self.init(raw: .init(derEncoded: DER.parse(Array(data))))
28 }
29
30 public init(contentsOf url: URL) throws {
31 try self.init(data: Data(contentsOf: url))
32 }
33
34 public init(from decoder: Decoder) throws {
35 let container = try decoder.singleValueContainer()
36 let data = try container.decode(Data.self)
37 try self.init(data: data)
38 }
39
40 public func encode(to encoder: Encoder) throws {
41 var container = encoder.singleValueContainer()
42 try container.encode(data())
43 }
44
45 private func subjectAttribute(_ attribute: ASN1ObjectIdentifier) throws -> String {
46 let commonName = raw.subject.lazy.flatMap { $0 }.first { $0.type == attribute }
47 guard let commonName, let parsed = String(commonName.value) else { throw Error.invalidCertificate }
48 return parsed
49 }
50
51 public func developerIdentity() throws -> String {
52 try subjectAttribute(.NameAttributes.commonName)
53 }
54
55 public func teamID() throws -> String {
56 try subjectAttribute(.NameAttributes.organizationalUnitName)
57 }
58
59 public func serialNumber() -> String {
60 // big endian, hex-encoded. Leading zero bytes are dropped, but not leading zero
61 // nibbles: Apple formats serials like "03AB…", not "3AB…" (#305).
62 raw.serialNumber.bytes
63 .drop { $0 == 0 }
64 .map { String(format: "%02hhX", $0) }
65 .joined()
66 }
67
68 /// Whether `serialNumber` (hex-encoded, e.g. by the App Store Connect API)
69 /// is this certificate's serial number.
70 ///
71 /// Compares numerically, so case and leading zeros don't matter.
72 public func hasSerialNumber(_ serialNumber: String) -> Bool {
73 func normalized(_ hex: String) -> Substring {
74 hex.uppercased().drop { $0 == "0" }
75 }
76 return normalized(serialNumber) == normalized(self.serialNumber())
77 }
78
79 public func wasIssuedBefore(_ other: Certificate) -> Bool {
80 raw.notValidBefore < other.raw.notValidBefore
81 }
82
83 public func data() throws -> Data {
84 var serializer = DER.Serializer()
85 try serializer.serialize(raw)
86 return Data(serializer.serializedBytes)
87 }
88
89}