xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.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 | |
| 9 | import Foundation |
| 10 | import Crypto |
| 11 | import X509 |
| 12 | import CryptoExtras |
| 13 | |
| 14 | public 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 | |
| 23 | public struct CSR: Sendable { |
| 24 | public let pemString: String |
| 25 | |
| 26 | public init(pemString: String) { |
| 27 | self.pemString = pemString |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | public 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 | } |