From ac767dc44200cf11b1cb025cb8a65c772a2770fa Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Mon, 24 Apr 2023 14:20:19 +0200 Subject: [PATCH] Support PEM serialisation and parsing of `Certificate`, `Certificate.PublicKey` and `Certificate.PrivateKey` (#71) * Support PEM serialisation and parsing for `Certificate`, `Certificate.PublicKey` and `Certificate.PrivateKey` * Fix Linux build * Fix tests on Linux and required watchOS version * run ./scripts/update_cmakelists.sh * add proper support for private RSA keys * Fix review comments * replace `as Any` with `String(describing:)` --- NOTICE.txt | 9 ++ Package.swift | 3 +- Sources/X509/CMakeLists.txt | 2 + Sources/X509/Certificate.swift | 5 + Sources/X509/CertificatePrivateKey.swift | 80 ++++++++++- Sources/X509/CertificatePublicKey.swift | 29 +++- Sources/X509/Error.swift | 18 +++ Sources/X509/PKCS8PrivateKey.swift | 100 ++++++++++++++ Sources/X509/SEC1PrivateKey.swift | 130 ++++++++++++++++++ .../X509BaseTypes/AlgorithmIdentifier.swift | 20 ++- Tests/X509Tests/PEMTestRSACertificate.pem | 28 ++++ Tests/X509Tests/PEMTests.swift | 115 ++++++++++++++++ rsakey.pem | 28 ++++ 13 files changed, 562 insertions(+), 5 deletions(-) create mode 100644 Sources/X509/PKCS8PrivateKey.swift create mode 100644 Sources/X509/SEC1PrivateKey.swift create mode 100644 Tests/X509Tests/PEMTestRSACertificate.pem create mode 100644 Tests/X509Tests/PEMTests.swift create mode 100644 rsakey.pem diff --git a/NOTICE.txt b/NOTICE.txt index 81ce3d6..3824b10 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -41,4 +41,13 @@ This product contains test data derived from Webpki. * https://github.com/briansmith/webpki/blob/main/LICENSE * HOMEPAGE: * https://github.com/briansmith/webpki/ + +--- + +This product contains derivations of various ASN1 types from SwiftASN1. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/apple/swift-asn1 diff --git a/Package.swift b/Package.swift index ab5a9a8..249887e 100644 --- a/Package.swift +++ b/Package.swift @@ -52,6 +52,7 @@ let package = Package( .copy("OCSP Test Resources/www.apple.com.der"), .copy("OCSP Test Resources/www.apple.com.ocsp-response.der"), .copy("OCSP Test Resources/www.apple.com.intermediate.ocsp-response.der"), + .copy("PEMTestRSACertificate.pem"), ]), ] ) @@ -62,7 +63,7 @@ let package = Package( if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { package.dependencies += [ .package(url: "https://github.com/apple/swift-crypto.git", from: "2.5.0"), - .package(url: "https://github.com/apple/swift-asn1.git", .upToNextMinor(from: "0.7.0")), + .package(url: "https://github.com/apple/swift-asn1.git", .upToNextMinor(from: "0.8.0")), .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"), ] } else { diff --git a/Sources/X509/CMakeLists.txt b/Sources/X509/CMakeLists.txt index 6ecba21..97d53af 100644 --- a/Sources/X509/CMakeLists.txt +++ b/Sources/X509/CMakeLists.txt @@ -68,9 +68,11 @@ add_library(X509 "OCSP/OCSPSingleResponse.swift" "OCSP/OCSPTBSRequest.swift" "OCSP/OCSPVersion.swift" + "PKCS8PrivateKey.swift" "RDNAttribute.swift" "RandomNumberGenerator+bytes.swift" "RelativeDistinguishedName.swift" + "SEC1PrivateKey.swift" "Signature.swift" "SignatureAlgorithm.swift" "Verifier/CertificateStore.swift" diff --git a/Sources/X509/Certificate.swift b/Sources/X509/Certificate.swift index 574c6e1..4415a30 100644 --- a/Sources/X509/Certificate.swift +++ b/Sources/X509/Certificate.swift @@ -324,3 +324,8 @@ extension DER.Serializer { } } + +extension Certificate: PEMRepresentable { + @inlinable + public static var defaultPEMDiscriminator: String { "CERTIFICATE" } +} diff --git a/Sources/X509/CertificatePrivateKey.swift b/Sources/X509/CertificatePrivateKey.swift index 3a9503c..64ba3eb 100644 --- a/Sources/X509/CertificatePrivateKey.swift +++ b/Sources/X509/CertificatePrivateKey.swift @@ -12,10 +12,10 @@ // //===----------------------------------------------------------------------===// +import SwiftASN1 import Foundation @preconcurrency import Crypto @preconcurrency import _CryptoExtras -import Foundation extension Certificate { /// A private key that can be used with a certificate. @@ -202,3 +202,81 @@ extension Certificate.PrivateKey { } } } + +@available(macOS 11.0, iOS 14, tvOS 14, watchOS 7, *) +extension Certificate.PrivateKey { + @inlinable + static var pemDiscriminatorForRSAPrivateKey: String { "RSA PRIVATE KEY" } + + @inlinable + static var pemDiscriminatorForSEC1PrivateKey: String { "EC PRIVATE KEY" } + + @inlinable + static var pemDiscriminatorForPKCS8PrivateKey: String { "PRIVATE KEY" } + + @inlinable + public init(pemEncoded: String) throws { + try self.init(pemDocument: PEMDocument(pemString: pemEncoded)) + } + + @inlinable + public init(pemDocument: PEMDocument) throws { + switch pemDocument.discriminator { + case Self.pemDiscriminatorForRSAPrivateKey: + self = try .init(_CryptoExtras._RSA.Signing.PrivateKey.init(derRepresentation: pemDocument.derBytes)) + + case Self.pemDiscriminatorForSEC1PrivateKey: + let sec1 = try SEC1PrivateKey(derEncoded: pemDocument.derBytes) + self = try .init(ecdsaAlgorithm: sec1.algorithm, rawEncodedPrivateKey: sec1.privateKey.bytes) + + case Self.pemDiscriminatorForPKCS8PrivateKey: + let pkcs8 = try PKCS8PrivateKey(derEncoded: pemDocument.derBytes) + switch pkcs8.algorithm { + case .ecdsaP256, .ecdsaP384, .ecdsaP521: + let sec1 = try SEC1PrivateKey(derEncoded: pkcs8.privateKey.bytes) + if let innerAlgorithm = sec1.algorithm, innerAlgorithm != pkcs8.algorithm { + throw ASN1Error.invalidASN1Object(reason: "algorithm missmatch. PKCS#8 is \(pkcs8.algorithm) but inner SEC1 is \(innerAlgorithm)") + } + self = try .init(ecdsaAlgorithm: pkcs8.algorithm, rawEncodedPrivateKey: sec1.privateKey.bytes) + + case .rsaKey: + self = try .init(_CryptoExtras._RSA.Signing.PrivateKey(derRepresentation: pkcs8.privateKey.bytes)) + default: + throw CertificateError.unsupportedPrivateKey(reason: "unknown algorithm \(pkcs8.algorithm)") + } + + default: + throw ASN1Error.invalidPEMDocument( + reason: "PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.pemDiscriminatorForPKCS8PrivateKey), \(Self.pemDiscriminatorForSEC1PrivateKey) or \(Self.pemDiscriminatorForRSAPrivateKey) instead" + ) + } + } + + @inlinable + init(ecdsaAlgorithm: AlgorithmIdentifier?, rawEncodedPrivateKey: ArraySlice) throws { + switch ecdsaAlgorithm { + case .some(.ecdsaP256): + self = try .init(P256.Signing.PrivateKey(rawRepresentation: rawEncodedPrivateKey)) + case .some(.ecdsaP384): + self = try .init(P384.Signing.PrivateKey(rawRepresentation: rawEncodedPrivateKey)) + case .some(.ecdsaP521): + self = try .init(P521.Signing.PrivateKey(rawRepresentation: rawEncodedPrivateKey)) + default: + throw CertificateError.unsupportedPrivateKey(reason: "unknown algorithm \(String(describing: ecdsaAlgorithm))") + } + } + + @inlinable + public func serializeAsPEM() throws -> PEMDocument { + switch backing { + case .p256(let key): return try PEMDocument(pemString: key.pemRepresentation) + case .p384(let key): return try PEMDocument(pemString: key.pemRepresentation) + case .p521(let key): return try PEMDocument(pemString: key.pemRepresentation) + case .rsa(let key): return try PEMDocument(pemString: key.pemRepresentation) + #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) + case .secureEnclaveP256: + throw CertificateError.unsupportedPrivateKey(reason: "secure enclave private keys can not be serialised as PEM") + #endif + } + } +} diff --git a/Sources/X509/CertificatePublicKey.swift b/Sources/X509/CertificatePublicKey.swift index 9ed08e0..4ca9803 100644 --- a/Sources/X509/CertificatePublicKey.swift +++ b/Sources/X509/CertificatePublicKey.swift @@ -39,7 +39,7 @@ extension Certificate { case .p521PublicKey: let key = try P521.Signing.PublicKey(x963Representation: spki.key.bytes) self.backing = .p521(key) - case .rsaPublicKey: + case .rsaKey: // To confirm that only the PKCS#1 format is allowed here, we actually attempt to decode the inner key // format. Sadly, Swift Crypto doesn't have a way to accept the raw numbers directly, so we then ask it // to decode as well. @@ -202,7 +202,7 @@ extension SubjectPublicKeyInfo { algorithmIdentifier = .p521PublicKey key = .init(bytes: ArraySlice(p521.x963Representation)) case .rsa(let rsa): - algorithmIdentifier = .rsaPublicKey + algorithmIdentifier = .rsaKey key = .init(bytes: ArraySlice(rsa.pkcs1DERRepresentation)) } @@ -287,3 +287,28 @@ extension _RSA.Signing.PublicKey { } } } + +extension Certificate.PublicKey { + @inlinable + static var pemDiscriminatorForPublicKey: String { "PUBLIC KEY" } + + @inlinable + public init(pemEncoded: String) throws { + try self.init(pemDocument: PEMDocument(pemString: pemEncoded)) + } + + @inlinable + public init(pemDocument: PEMDocument) throws { + guard pemDocument.discriminator == Self.pemDiscriminatorForPublicKey else { + throw ASN1Error.invalidPEMDocument(reason: "PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.pemDiscriminatorForPublicKey) instead") + } + + try self.init(spki: try SubjectPublicKeyInfo(derEncoded: pemDocument.derBytes)) + } + + func serializeAsPEM() throws -> PEMDocument { + let spki = SubjectPublicKeyInfo(self) + let derBytes = try DER.Serializer.serialized(element: spki) + return PEMDocument(type: "PUBLIC KEY", derBytes: derBytes) + } +} diff --git a/Sources/X509/Error.swift b/Sources/X509/Error.swift index c4a7404..d135795 100644 --- a/Sources/X509/Error.swift +++ b/Sources/X509/Error.swift @@ -127,6 +127,20 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible { ) ) } + + /// A digest private key isn't supported + /// - Parameter reason: A detailed reason indicating the unsupported private key. + /// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/unsupportedPrivateKey``. + @inline(never) + public static func unsupportedPrivateKey( + reason: String, file: String = #fileID, line: UInt = #line + ) -> CertificateError { + return CertificateError( + backing: .init( + code: .unsupportedPrivateKey, reason: reason, file: file, line: line + ) + ) + } } extension CertificateError { @@ -142,6 +156,7 @@ extension CertificateError { case invalidSignatureForCertificate case incorrectOIDForExtension case unsupportedDigestAlgorithm + case unsupportedPrivateKey } fileprivate var backingCode: BackingCode @@ -164,6 +179,9 @@ extension CertificateError { /// The digest algorithm isn't supported. public static let unsupportedDigestAlgorithm = ErrorCode(.unsupportedDigestAlgorithm) + + /// The private key isn't supported. + public static let unsupportedPrivateKey = ErrorCode(.unsupportedPrivateKey) public var description: String { return String(describing: self.backingCode) diff --git a/Sources/X509/PKCS8PrivateKey.swift b/Sources/X509/PKCS8PrivateKey.swift new file mode 100644 index 0000000..adc2796 --- /dev/null +++ b/Sources/X509/PKCS8PrivateKey.swift @@ -0,0 +1,100 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftASN1 open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftASN1 project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftASN1 project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +// For PKCS#8 we need the following for the private key: +// +// PrivateKeyInfo ::= SEQUENCE { +// version Version, +// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, +// privateKey PrivateKey, +// attributes [0] IMPLICIT Attributes OPTIONAL } +// +// Version ::= INTEGER +// +// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier +// +// PrivateKey ::= OCTET STRING +// +// Attributes ::= SET OF Attribute +// +// We disregard the attributes because we don't support them anyway. +// +@usableFromInline +struct PKCS8PrivateKey: DERImplicitlyTaggable { + @inlinable + static var defaultIdentifier: ASN1Identifier { + return .sequence + } + + @usableFromInline + var algorithm: AlgorithmIdentifier + + @usableFromInline + var privateKey: ASN1OctetString + + @inlinable + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let version = try Int(derEncoded: &nodes) + guard version == 0 else { + throw ASN1Error.invalidASN1Object(reason: "Invalid version") + } + + let algorithm = try AlgorithmIdentifier(derEncoded: &nodes) + let privateKeyBytes = try ASN1OctetString(derEncoded: &nodes) + + // We ignore the attributes + _ = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in } + + return try .init(algorithm: algorithm, privateKey: privateKeyBytes) + } + } + + @inlinable + init(algorithm: AlgorithmIdentifier, privateKey: ASN1OctetString) throws { + self.privateKey = privateKey + self.algorithm = algorithm + } + + @inlinable + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(0) // version + try coder.serialize(self.algorithm) + + // Here's a weird one: we recursively serialize the private key, and then turn the bytes into an octet string. + var subCoder = DER.Serializer() + try subCoder.serialize(self.privateKey) + let serializedKey = ASN1OctetString(contentBytes: subCoder.serializedBytes[...]) + + try coder.serialize(serializedKey) + } + } +} diff --git a/Sources/X509/SEC1PrivateKey.swift b/Sources/X509/SEC1PrivateKey.swift new file mode 100644 index 0000000..cd59ec3 --- /dev/null +++ b/Sources/X509/SEC1PrivateKey.swift @@ -0,0 +1,130 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftASN1 open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftASN1 project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftASN1 project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +// For private keys, SEC 1 uses: +// +// ECPrivateKey ::= SEQUENCE { +// version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), +// privateKey OCTET STRING, +// parameters [0] EXPLICIT ECDomainParameters OPTIONAL, +// publicKey [1] EXPLICIT BIT STRING OPTIONAL +// } +@usableFromInline +struct SEC1PrivateKey: DERImplicitlyTaggable, PEMRepresentable { + @usableFromInline + static let defaultPEMDiscriminator: String = "EC PRIVATE KEY" + + @inlinable + static var defaultIdentifier: ASN1Identifier { + return .sequence + } + + @usableFromInline + var algorithm: AlgorithmIdentifier? + + @usableFromInline + var privateKey: ASN1OctetString + + @usableFromInline + var publicKey: ASN1BitString? + + @inlinable + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let version = try Int(derEncoded: &nodes) + guard 1 == version else { + throw ASN1Error.invalidASN1Object(reason: "Invalid version \(version)") + } + + let privateKey = try ASN1OctetString(derEncoded: &nodes) + let parameters = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + return try ASN1ObjectIdentifier(derEncoded: node) + } + let publicKey = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in + return try ASN1BitString(derEncoded: node) + } + + return try .init(privateKey: privateKey, algorithm: parameters, publicKey: publicKey) + } + } + + @inlinable + internal init(privateKey: ASN1OctetString, algorithm: ASN1ObjectIdentifier?, publicKey: ASN1BitString?) throws { + self.privateKey = privateKey + self.publicKey = publicKey + self.algorithm = try algorithm.map { algorithmOID in + switch algorithmOID { + case ASN1ObjectIdentifier.NamedCurves.secp256r1: + return .ecdsaP256 + case ASN1ObjectIdentifier.NamedCurves.secp384r1: + return .ecdsaP384 + case ASN1ObjectIdentifier.NamedCurves.secp521r1: + return .ecdsaP521 + default: + throw ASN1Error.invalidASN1Object(reason: "Invalid algorithm ID") + } + } + } + + @inlinable + init(privateKey: [UInt8], algorithm: AlgorithmIdentifier?, publicKey: [UInt8]) { + self.privateKey = ASN1OctetString(contentBytes: privateKey[...]) + self.algorithm = algorithm + self.publicKey = ASN1BitString(bytes: publicKey[...]) + } + + @inlinable + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(1) // version + try coder.serialize(self.privateKey) + + if let algorithm = self.algorithm { + let oid: ASN1ObjectIdentifier + switch algorithm { + case .ecdsaP256: + oid = ASN1ObjectIdentifier.NamedCurves.secp256r1 + case .ecdsaP384: + oid = ASN1ObjectIdentifier.NamedCurves.secp384r1 + case .ecdsaP521: + oid = ASN1ObjectIdentifier.NamedCurves.secp521r1 + default: + throw ASN1Error.invalidASN1Object(reason: "Unsupported algorithm") + } + + try coder.serialize(oid, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + } + + if let publicKey = self.publicKey { + try coder.serialize(publicKey, explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific) + } + } + } +} diff --git a/Sources/X509/X509BaseTypes/AlgorithmIdentifier.swift b/Sources/X509/X509BaseTypes/AlgorithmIdentifier.swift index 8ce126c..a156301 100644 --- a/Sources/X509/X509BaseTypes/AlgorithmIdentifier.swift +++ b/Sources/X509/X509BaseTypes/AlgorithmIdentifier.swift @@ -130,7 +130,7 @@ extension AlgorithmIdentifier { ) @usableFromInline - static let rsaPublicKey = AlgorithmIdentifier( + static let rsaKey = AlgorithmIdentifier( algorithm: .AlgorithmIdentifier.rsaEncryption, parameters: try! ASN1Any(erasing: ASN1Null()) ) @@ -232,3 +232,21 @@ extension ASN1ObjectIdentifier.AlgorithmIdentifier { static let sha512: ASN1ObjectIdentifier = [2, 16, 840, 1, 101, 3, 4, 2, 3] } + +extension AlgorithmIdentifier { + @usableFromInline + static let ecdsaP256 = AlgorithmIdentifier( + algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp256r1) + ) + @usableFromInline + static let ecdsaP384 = AlgorithmIdentifier( + algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp384r1) + ) + @usableFromInline + static let ecdsaP521 = AlgorithmIdentifier( + algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp521r1) + ) +} diff --git a/Tests/X509Tests/PEMTestRSACertificate.pem b/Tests/X509Tests/PEMTestRSACertificate.pem new file mode 100644 index 0000000..e3c9cae --- /dev/null +++ b/Tests/X509Tests/PEMTestRSACertificate.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDNFiodnfVB0HDP +snhnoqqXIx3Ua039vt++LGO3lZR6inzM1kSKNZDCHwyv0UJ2HfFj6Z1fxSngXI0w ++3peudxLglyLvKSGOnRipAPcNP8atpcVKwIkTb5gH0Hm8DHULbM+p7d17WvCh+Px +HArJ+zlcXp5g5aGMytnzCZC1YsYv1YnBJYpLqQnK3PkBHeGDIQPjltJgFzQ2Vl5i +mCSPVRqRsVvSFtCOjcKzmBBxMbO+cDG6q7W99jHamR49wNZpeKg9khL5/5My+/ET +Y88ML6OGpm916RpcdTWNKKdHdIalrF+Zrn9CxxTUkFeC4kuaP1EArAYd4zG2svH8 +VB9Sl5/TAgMBAAECggEAIwUw5ePOOJHWYbERHGlLhglqE5bLN5Q7cqbz1CqHszEo +xHWmOI+TC4Lv0KoEFlVgnfYLeIobb4N+XKnkqH5GXuKA2R+6XG1o6FsniZfHJBGf +1O6GLBrWcmWEBGJpr9ip7f4Htux25T39L3PhZ8Itdld15gfwQTF2bCjq+/5E52/Z +rWYOpyX1tGTGuqOLkzd6GWctD1b5xDFe8xb6nvMBrq0WNPLyWmKS255rg56kDz+a +NQRsttUUmvljBWfnT4oWzZGqBSeQNPEp+2906G1mpdDvsUeSVB6QN3c7ssVzQm6w +w4BMSrzs2C+XQ+4d3uaiN+81QzfIOP61VETpcGyCQQKBgQD+BYLkYMG1AmnOJ9wB +LRfgQcknlUgiRLnACVCm8yBt3gBU91+YvDPypeV1HY4hJ7GWdluJLImWQKi3sr5i +xZZ1W+6yJuoAmwLwjNWURF6DDGO+6CNiXcaF4t/1a6HWdnRcVCerVLk4s+s2IR17 +I5DREOVD82WaihkrkqLW+1gS4QKBgQDOrxUvR8mBPrSQ0XkvN2GdT0j6gGq2dfGN +V3lGQMfjFZTHNr2MM7AX+EHIF9yV9D6bhvVAAaImP6ZIsffjxA9wT1yE7SBLASsx +VAlQoRq9FBXF+7TBCapDdpkNf3iajADJaj2P8Wlwrbs3w9+JmEY1HuPlukj9V2cB +wKMJrVR9MwKBgQD5pzz/a0C1v4txO6dz2HewxbcHGiZs15KfdAg6LJTgpeE5oG3p +1H5Rqk4bjlKTr0lQET7hUE5gx2eKMzf+Jyc6bIHpwWkV80MuW5vFPnSM425cwBWW +pYdpKpLlx0SlXIH8BBGAx6HKYrl215D75vZ7ItnQsLRY8ATQ2CsGkrv6wQKBgCH1 +gnWSRfmGZASnZlHrt44xSLxf/SidmGKwzKxOWIlnMlrJE7vFgllt4OEPip7Y0rCb +LBCoNAw0yQ2IsEIsJJ0/bOQqUfQA7SfdtuoYjlwiwLEW+kv9WoxbICqnlxlNh5OQ +cS0FbV2mLeyrsj7ZVi/EM427XeLCSZpwHFmqsQchAoGAGtcPrETsozK16LzrKj9v +dgOk1GBiX0o1b1DF+7mm745//Xpuuh+xKAfLLFDJYbiArtxSVow7xBVP0RB0WlTI +0dh5+W5fOl3spkTV5fomkxVMsR2APcPQCPl5TRH6CWeQCFBJltRmIPB9woOG8iT9 +MC1b84idBnqZvzLXA3QVRaM= +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/Tests/X509Tests/PEMTests.swift b/Tests/X509Tests/PEMTests.swift new file mode 100644 index 0000000..318bda5 --- /dev/null +++ b/Tests/X509Tests/PEMTests.swift @@ -0,0 +1,115 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import XCTest + +import SwiftASN1 +import Crypto +import _CryptoExtras +@testable import X509 + +fileprivate protocol Key { + associatedtype Wrapped: WrappedKey + init(derRepresentation: some DataProtocol) throws + init(pemRepresentation: String) throws + var pemRepresentation: String { get } + var wrapped: Wrapped { get } +} + +extension Key { + var pemDiscriminator: String { + get throws { + try PEMDocument(pemString: pemRepresentation).discriminator + } + } +} + +// MARK: Private Keys + +extension Crypto.P256.Signing.PrivateKey: Key { + var wrapped: Certificate.PrivateKey { .init(self) } +} +extension Crypto.P384.Signing.PrivateKey: Key { + var wrapped: Certificate.PrivateKey { .init(self) } +} +extension Crypto.P521.Signing.PrivateKey: Key { + var wrapped: Certificate.PrivateKey { .init(self) } +} +extension _CryptoExtras._RSA.Signing.PrivateKey: Key { + var wrapped: Certificate.PrivateKey { .init(self) } +} + +// MARK: Public Keys + +extension Crypto.P256.Signing.PublicKey: Key { + var wrapped: Certificate.PublicKey { .init(self) } +} +extension Crypto.P384.Signing.PublicKey: Key { + var wrapped: Certificate.PublicKey { .init(self) } +} +extension Crypto.P521.Signing.PublicKey: Key { + var wrapped: Certificate.PublicKey { .init(self) } +} +extension _CryptoExtras._RSA.Signing.PublicKey: Key { + var wrapped: Certificate.PublicKey { .init(self) } +} + + + +fileprivate protocol WrappedKey: Equatable { + init(pemEncoded: String) throws + func serializeAsPEM() throws -> PEMDocument +} + +extension Certificate.PublicKey: WrappedKey {} +extension Certificate.PrivateKey: WrappedKey {} + + +final class PEMTests: XCTestCase { + fileprivate func assertPEMRoundtrip(key: some Key, file: StaticString = #filePath, line: UInt = #line) throws { + let initialPEMString = key.pemRepresentation + let wrapped = try type(of: key).Wrapped(pemEncoded: initialPEMString) + XCTAssertEqual(key.wrapped, wrapped, "Wrapper mismatch after one roundtrip for \(key)", file: file, line: line) + let pemDocument = try key.wrapped.serializeAsPEM() + let initialPEMDocument = try PEMDocument(pemString: initialPEMString) + XCTAssertEqual(pemDocument.discriminator, initialPEMDocument.discriminator, "PEM discriminator mismatch after one roundtrip for \(key)", file: file, line: line) + XCTAssertEqual(pemDocument.pemString, initialPEMDocument.pemString, "PEM string mismatch after one roundtrip for \(key)", file: file, line: line) + } + + func testPublicKeys() throws { + try assertPEMRoundtrip(key: P256.Signing.PrivateKey().publicKey) + try assertPEMRoundtrip(key: P384.Signing.PrivateKey().publicKey) + try assertPEMRoundtrip(key: P521.Signing.PrivateKey().publicKey) + try assertPEMRoundtrip(key: _RSA.Signing.PrivateKey(keySize: .bits2048).publicKey) + } + + func testPrivateKeys() throws { + try assertPEMRoundtrip(key: P256.Signing.PrivateKey()) + try assertPEMRoundtrip(key: P384.Signing.PrivateKey()) + try assertPEMRoundtrip(key: P521.Signing.PrivateKey()) + try assertPEMRoundtrip(key: _RSA.Signing.PrivateKey(keySize: .bits2048)) + } + + func testRSAPrivateKey() throws { + // generated with "openssl genpkey -algorithm rsa" + let rsaKey = try String(contentsOf: XCTUnwrap(Bundle.module.url(forResource: "PEMTestRSACertificate", withExtension: "pem"))) + let privateKey = try Certificate.PrivateKey(pemEncoded: rsaKey) + guard case .rsa = privateKey.backing else { + XCTFail("parsed as wrong key type \(privateKey)") + return + } + let privateKeyAfterRoundtrip = try Certificate.PrivateKey(pemDocument: privateKey.serializeAsPEM()) + XCTAssertEqual(privateKey, privateKeyAfterRoundtrip) + } +} diff --git a/rsakey.pem b/rsakey.pem new file mode 100644 index 0000000..f305b09 --- /dev/null +++ b/rsakey.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASC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