Skip to content

Commit

Permalink
Merge pull request #75 from outfoxx/feature/pem-cert
Browse files Browse the repository at this point in the history
Add `pemEncoded` to SecCertificate to match `derEncoded`
  • Loading branch information
kdubb authored Jun 26, 2023
2 parents e98d70d + b8985c9 commit 8ee2c71
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Sources/ShieldSecurity/SecCertificate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,11 @@ public extension SecCertificate {
)
}

var pemEncoded: String {
let pem = derEncoded.base64EncodedString().chunks(ofCount: 64).joined(separator: "\n")
return "-----BEGIN CERTIFICATE-----\n\(pem)\n-----END CERTIFICATE-----"
}

var derEncoded: Data {
return SecCertificateCopyData(self) as Data
}
Expand Down
52 changes: 52 additions & 0 deletions Tests/SecCertificateTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,58 @@ class SecCertificateTests: XCTestCase {
XCTAssertEqual(try cert.publicKey?.encode(), try Self.keyPair.publicKey.encode())
}

func testPEM() throws {

let subjectName = try NameBuilder()
.add("Unit Testing", forTypeName: "CN")
.add("123456", forTypeName: "UID")
.name

let issuerName = try NameBuilder()
.add("Test Issuer", forTypeName: "CN")
.name

let certData =
try Certificate.Builder()
.subject(name: subjectName)
.issuer(name: issuerName)
.publicKey(keyPair: Self.keyPair, usage: [.keyCertSign, .cRLSign])
.valid(for: 86400 * 5)
.build(signingKey: Self.keyPair.privateKey, digestAlgorithm: .sha256)
.encoded()

let certSec = try SecCertificate.from(data: certData)
let certPem = certSec.pemEncoded

XCTAssertEqual(certSec.derEncoded, try SecCertificate.load(pem: certPem).first?.derEncoded)
}

func testDER() throws {

let subjectName = try NameBuilder()
.add("Unit Testing", forTypeName: "CN")
.add("123456", forTypeName: "UID")
.name

let issuerName = try NameBuilder()
.add("Test Issuer", forTypeName: "CN")
.name

let certData =
try Certificate.Builder()
.subject(name: subjectName)
.issuer(name: issuerName)
.publicKey(keyPair: Self.keyPair, usage: [.keyCertSign, .cRLSign])
.valid(for: 86400 * 5)
.build(signingKey: Self.keyPair.privateKey, digestAlgorithm: .sha256)
.encoded()

let certSec = try SecCertificate.from(data: certData)
let certDer = certSec.derEncoded

XCTAssertEqual(certSec.derEncoded, try SecCertificate.load(der: certDer).derEncoded)
}

func testValidatedPublicKey() throws {

let rootName = try NameBuilder().add("Unit Testing Root", forTypeName: "CN").name
Expand Down

0 comments on commit 8ee2c71

Please sign in to comment.