-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support for importing/exporting PKCS8 key pairs
- Loading branch information
Showing
4 changed files
with
167 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// | ||
// File.swift | ||
// | ||
// | ||
// Created by Kevin Wooten on 1/26/24. | ||
// | ||
|
||
import Foundation | ||
import Regex | ||
|
||
public enum PEM { | ||
|
||
public struct Kind: RawRepresentable { | ||
|
||
public var rawValue: String | ||
|
||
public init(rawValue: String) { | ||
self.rawValue = rawValue | ||
} | ||
|
||
public static let certificate = Self(rawValue: "CERTIFICATE") | ||
public static let pkcs8PrivateKey = Self(rawValue: "PRIVATE KEY") | ||
|
||
} | ||
|
||
private static let pemRegex = | ||
Regex(#"-----BEGIN ([\w\s]+)-----\s*([a-zA-Z0-9\s/+]+=*)\s*-----END \1-----"#) | ||
private static let pemWhitespaceRegex = Regex(#"[\n\t\s]+"#) | ||
|
||
public static func read(pem: String) -> [(Kind, Data)] { | ||
|
||
pemRegex.allMatches(in: pem) | ||
.compactMap { match in | ||
|
||
guard | ||
let kindCapture = match.captures.first, | ||
let kind = kindCapture, | ||
let dataCapture = match.captures.last, | ||
let base64Data = dataCapture?.replacingAll(matching: pemWhitespaceRegex, with: ""), | ||
let data = Data(base64Encoded: base64Data) | ||
else { | ||
return nil | ||
} | ||
|
||
return (.init(rawValue: kind), data) | ||
} | ||
|
||
} | ||
|
||
public static func write(kind: Kind, data: Data) -> String { | ||
let pem = data.base64EncodedString().chunks(ofCount: 64).joined(separator: "\n") | ||
return "-----BEGIN \(kind.rawValue)-----\n\(pem)\n-----END \(kind.rawValue)-----" | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters