Modern Apps git

xtool.git

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

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

Keypair.swift63 lines · 1.4 KiBRaw
1//
2// Keypair.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 Crypto
11import X509
12import CryptoExtras
13
14public struct PrivateKey: Codable, Sendable {
15 // pem encoded
16 public let data: Data
17
18 public init(data: Data) {
19 self.data = data
20 }
21}
22
23public struct CSR: Sendable {
24 public let pemString: String
25
26 public init(pemString: String) {
27 self.pemString = pemString
28 }
29}
30
31public struct Keypair {
32
33 public enum Error: Swift.Error {
34 case couldNotCreate
35 case invalidKeypair
36 }
37
38 // Apple developer certs seem to require RSA2048
39 let raw: _RSA.Signing.PrivateKey
40
41 public init() throws {
42 self.raw = try _RSA.Signing.PrivateKey(keySize: .bits2048)
43 }
44
45 public func privateKey() throws -> PrivateKey {
46 PrivateKey(data: Data(raw.pemRepresentation.utf8))
47 }
48
49 public func generateCSR() throws -> CSR {
50 let request = try CertificateSigningRequest(
51 version: .v1,
52 subject: DistinguishedName {
53 CountryName("US")
54 CommonName("xtool")
55 },
56 privateKey: X509.Certificate.PrivateKey(raw),
57 attributes: CertificateSigningRequest.Attributes(),
58 signatureAlgorithm: .sha1WithRSAEncryption
59 )
60 return CSR(pemString: try request.serializeAsPEM().pemString)
61 }
62
63}