From 4ce1b9b001461593b462dce4620fdcf2a70d2fbd Mon Sep 17 00:00:00 2001 From: Raphael Date: Wed, 2 Jul 2025 02:06:02 +0100 Subject: [PATCH] Add a PKCS#8 DER property to private keys (#372) ### Motivation PKCS#8 is pretty widely used. Currently getting a key in PKCS#8 DER representations requires going through a PKCS8 PEM document and then get its DER bytes. ### Modifications Add a computed property to RSA private keys that calls into BoringSSL or Security.framework to get the PKCS8 DER representation of the key. ECDH keys use the existing `derRepresentation` property to provide a property of the same name. A small ASN1 encoder adds the functionality to ed25519/x25519 keys. ### Result The representation can be accessed directly. *The identifiers for MLKEM are [still a draft](https://datatracker.ietf.org/doc/draft-ietf-lamps-kyber-certificates/). As such MLKEM is not included in the PR.* --------- Co-authored-by: Cory Benfield --- Sources/_CryptoExtras/CMakeLists.txt | 4 + .../_CryptoExtras/EC/ObjectIdentifier.swift | 37 ++++ .../EC/PKCS8DERRepresentation.swift | 76 +++++++ .../_CryptoExtras/EC/PKCS8PrivateKey.swift | 93 ++++++++ .../EC/RFC8410AlgorithmIdentifier.swift | 74 +++++++ Sources/_CryptoExtras/RSA/RSA.swift | 5 + Sources/_CryptoExtras/RSA/RSA_boring.swift | 13 ++ Sources/_CryptoExtras/RSA/RSA_security.swift | 6 + .../PKCS8DERRepresentationTests.swift | 201 ++++++++++++++++++ 9 files changed, 509 insertions(+) create mode 100644 Sources/_CryptoExtras/EC/ObjectIdentifier.swift create mode 100644 Sources/_CryptoExtras/EC/PKCS8DERRepresentation.swift create mode 100644 Sources/_CryptoExtras/EC/PKCS8PrivateKey.swift create mode 100644 Sources/_CryptoExtras/EC/RFC8410AlgorithmIdentifier.swift create mode 100644 Tests/_CryptoExtrasTests/PKCS8DERRepresentationTests.swift diff --git a/Sources/_CryptoExtras/CMakeLists.txt b/Sources/_CryptoExtras/CMakeLists.txt index 6582d439..32445c1f 100644 --- a/Sources/_CryptoExtras/CMakeLists.txt +++ b/Sources/_CryptoExtras/CMakeLists.txt @@ -32,6 +32,10 @@ add_library(_CryptoExtras "ARC/ARCServer.swift" "ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift" "ChaCha20CTR/ChaCha20CTR.swift" + "EC/ObjectIdentifier.swift" + "EC/PKCS8DERRepresentation.swift" + "EC/PKCS8PrivateKey.swift" + "EC/RFC8410AlgorithmIdentifier.swift" "ECToolbox/BoringSSL/ECToolbox_boring.swift" "ECToolbox/ECToolbox.swift" "H2G/HashToField.swift" diff --git a/Sources/_CryptoExtras/EC/ObjectIdentifier.swift b/Sources/_CryptoExtras/EC/ObjectIdentifier.swift new file mode 100644 index 00000000..87c79f53 --- /dev/null +++ b/Sources/_CryptoExtras/EC/ObjectIdentifier.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +extension ASN1ObjectIdentifier.AlgorithmIdentifier { + // Identifies the key agreement algorithm X25519. + // + // This identifier is defined in RFC 8410 + static let idX25519: ASN1ObjectIdentifier = [1, 3, 101, 110] + + // Identifies the key agreement algorithm X448. + // + // This identifier is defined in RFC 8410 + static let idX448: ASN1ObjectIdentifier = [1, 3, 101, 111] + + // Identifies the signature algorithm Ed25519. + // + // This identifier is defined in RFC 8410 + static let idEd25519: ASN1ObjectIdentifier = [1, 3, 101, 112] + + // Identifies the signature algorithm Ed448. + // + // This identifier is defined in RFC 8410 + static let idEd448: ASN1ObjectIdentifier = [1, 3, 101, 113] +} diff --git a/Sources/_CryptoExtras/EC/PKCS8DERRepresentation.swift b/Sources/_CryptoExtras/EC/PKCS8DERRepresentation.swift new file mode 100644 index 00000000..a3449ca6 --- /dev/null +++ b/Sources/_CryptoExtras/EC/PKCS8DERRepresentation.swift @@ -0,0 +1,76 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Crypto +import Foundation +import SwiftASN1 + +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) +extension Curve25519.Signing.PrivateKey { + /// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format. + public var pkcs8DERRepresentation: Data { + let pkey = ASN1.PKCS8PrivateKey(algorithm: .ed25519, privateKey: Array(self.rawRepresentation)) + var serializer = DER.Serializer() + + // Serializing this key can't throw + try! serializer.serialize(pkey) + return Data(serializer.serializedBytes) + } +} + +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) +extension Curve25519.KeyAgreement.PrivateKey { + /// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format. + public var pkcs8DERRepresentation: Data { + let pkey = ASN1.PKCS8PrivateKey(algorithm: .x25519, privateKey: Array(self.rawRepresentation)) + var serializer = DER.Serializer() + + // Serializing this key can't throw + try! serializer.serialize(pkey) + return Data(serializer.serializedBytes) + } +} + +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) +extension P256.Signing.PrivateKey { + /// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format. + /// + /// This property provides the same output as the existing `derRepresentation` property, + /// which already conforms to the PKCS#8 standard. + public var pkcs8DERRepresentation: Data { + self.derRepresentation + } +} + +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) +extension P384.Signing.PrivateKey { + /// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format. + /// + /// This property provides the same output as the existing `derRepresentation` property, + /// which already conforms to the PKCS#8 standard. + public var pkcs8DERRepresentation: Data { + self.derRepresentation + } +} + +@available(iOS 14.0, macOS 11.0, watchOS 7.0, tvOS 14.0, *) +extension P521.Signing.PrivateKey { + /// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format. + /// + /// This property provides the same output as the existing `derRepresentation` property, + /// which already conforms to the PKCS#8 standard. + public var pkcs8DERRepresentation: Data { + self.derRepresentation + } +} diff --git a/Sources/_CryptoExtras/EC/PKCS8PrivateKey.swift b/Sources/_CryptoExtras/EC/PKCS8PrivateKey.swift new file mode 100644 index 00000000..5de7a11e --- /dev/null +++ b/Sources/_CryptoExtras/EC/PKCS8PrivateKey.swift @@ -0,0 +1,93 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Crypto +import SwiftASN1 + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension ASN1 { + // A PKCS#8 private key is one of two formats, depending on the version: + // + // 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. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + struct PKCS8PrivateKey: DERImplicitlyTaggable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var algorithm: RFC8410AlgorithmIdentifier + + var privateKey: ASN1OctetString + + 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 || version == 1 else { + throw ASN1Error.invalidASN1Object(reason: "Version number mismatch") + } + + let algorithm = try ASN1.RFC8410AlgorithmIdentifier(derEncoded: &nodes) + let privateKeyBytes = try ASN1OctetString(derEncoded: &nodes) + + // We ignore the attributes + _ = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in } + + let privateKeyNode = try DER.parse(privateKeyBytes.bytes) + let privateKey = try ASN1OctetString(derEncoded: privateKeyNode) + + return try .init(algorithm: algorithm, privateKey: privateKey) + } + } + + private init(algorithm: ASN1.RFC8410AlgorithmIdentifier, privateKey: ASN1OctetString) throws { + self.privateKey = privateKey + self.algorithm = algorithm + } + + init(algorithm: ASN1.RFC8410AlgorithmIdentifier, privateKey: [UInt8]) { + self.algorithm = algorithm + self.privateKey = ASN1OctetString(contentBytes: privateKey[...]) + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(0) + 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/_CryptoExtras/EC/RFC8410AlgorithmIdentifier.swift b/Sources/_CryptoExtras/EC/RFC8410AlgorithmIdentifier.swift new file mode 100644 index 00000000..b73b4373 --- /dev/null +++ b/Sources/_CryptoExtras/EC/RFC8410AlgorithmIdentifier.swift @@ -0,0 +1,74 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension ASN1 { + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) + struct RFC8410AlgorithmIdentifier: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var algorithm: ASN1ObjectIdentifier + + // RFC 8410: For all of these OIDs, the parameters MUST be absent. + // They are still part of the identifer block. + var parameters: ASN1Any? + + init(algorithm: ASN1ObjectIdentifier, parameters: ASN1Any?) { + self.algorithm = algorithm + self.parameters = parameters + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + // The AlgorithmIdentifier block looks like this. + // + // AlgorithmIdentifier ::= SEQUENCE { + // algorithm OBJECT IDENTIFIER, + // parameters ANY DEFINED BY algorithm OPTIONAL + // } + // + // We don't bother with helpers: we just try to decode it directly. + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let algorithmOID = try ASN1ObjectIdentifier(berEncoded: &nodes) + + let parameters = nodes.next().map { ASN1Any(berEncoded: $0) } + + return .init(algorithm: algorithmOID, parameters: parameters) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.algorithm) + if let parameters = self.parameters { + try coder.serialize(parameters) + } + } + } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension ASN1.RFC8410AlgorithmIdentifier { + static let x25519 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idX25519, parameters: nil) + + static let x448 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idX448, parameters: nil) + + static let ed25519 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEd25519, parameters: nil) + + static let ed448 = ASN1.RFC8410AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEd448, parameters: nil) +} diff --git a/Sources/_CryptoExtras/RSA/RSA.swift b/Sources/_CryptoExtras/RSA/RSA.swift index c0acdbb4..a805097f 100644 --- a/Sources/_CryptoExtras/RSA/RSA.swift +++ b/Sources/_CryptoExtras/RSA/RSA.swift @@ -259,6 +259,11 @@ extension _RSA.Signing { self.backing.pemRepresentation } + /// A Distinguished Encoding Rules (DER) encoded representation of the private key in PKCS#8 format. + public var pkcs8DERRepresentation: Data { + self.backing.pkcs8DERRepresentation + } + public var pkcs8PEMRepresentation: String { self.backing.pkcs8PEMRepresentation } diff --git a/Sources/_CryptoExtras/RSA/RSA_boring.swift b/Sources/_CryptoExtras/RSA/RSA_boring.swift index cd560d75..3c6eebbb 100644 --- a/Sources/_CryptoExtras/RSA/RSA_boring.swift +++ b/Sources/_CryptoExtras/RSA/RSA_boring.swift @@ -106,6 +106,10 @@ internal struct BoringSSLRSAPrivateKey: Sendable { self.backing.pemRepresentation } + var pkcs8DERRepresentation: Data { + self.backing.pkcs8DERRepresentation + } + var pkcs8PEMRepresentation: String { self.backing.pkcs8PEMRepresentation } @@ -737,6 +741,15 @@ extension BoringSSLRSAPrivateKey { } } + fileprivate var pkcs8DERRepresentation: Data { + BIOHelper.withWritableMemoryBIO { bio in + let rc = CCryptoBoringSSL_i2d_PKCS8PrivateKeyInfo_bio(bio, self.pointer) + precondition(rc == 1, "Exporting PKCS8 DER key failed") + + return try! Data(copyingMemoryBIO: bio) + } + } + fileprivate var pkcs8PEMRepresentation: String { BIOHelper.withWritableMemoryBIO { bio in let evp = CCryptoBoringSSL_EVP_PKEY_new() diff --git a/Sources/_CryptoExtras/RSA/RSA_security.swift b/Sources/_CryptoExtras/RSA/RSA_security.swift index 0a88fcc6..31708a38 100644 --- a/Sources/_CryptoExtras/RSA/RSA_security.swift +++ b/Sources/_CryptoExtras/RSA/RSA_security.swift @@ -169,6 +169,12 @@ internal struct SecurityRSAPrivateKey: @unchecked Sendable { return pemString.appending("\n") } + var pkcs8DERRepresentation: Data { + let pkcs1Bytes = self.derRepresentation + let pkcs8Bytes = Data(privateKeyPKCS8BytesForPKCS1Bytes: pkcs1Bytes) + return pkcs8Bytes + } + var keySizeInBits: Int { SecKeyGetBlockSize(self.backing) * 8 } diff --git a/Tests/_CryptoExtrasTests/PKCS8DERRepresentationTests.swift b/Tests/_CryptoExtrasTests/PKCS8DERRepresentationTests.swift new file mode 100644 index 00000000..1cc754c2 --- /dev/null +++ b/Tests/_CryptoExtrasTests/PKCS8DERRepresentationTests.swift @@ -0,0 +1,201 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Crypto +import Foundation +import XCTest + +@testable import _CryptoExtras + +final class PKCS8DERRepresentationTests: XCTestCase { + func test_RSA() { + let rsaPrivateKeyPEM = """ + -----BEGIN RSA PRIVATE KEY----- + MIIEpQIBAAKCAQEAxeBrlW1i+gXmqC/4XlTppLCXPpksZbxsc0AufsWzpcIxBAQL + jr4LxXyOenZcyhrdXxksEsCJE/8stJuUZgiFyDMesWjoL5bYyOpWrwPyvCMNaC8F + 15cKe5n7OSVNU312X0ZSxTZAOrCEH0kGrsXoQn5JgHygVXejSPlHw8F1Pwps3pnc + cRYE9vsHZegspUI3DaqWgmewFWz6jSMY0v1DcZv2Xw+pMLeXEpKKMf+eo90mHShh + n8FijsI1tFuYD++LmM/e1TV1z+W2sPL2CaosBO890WeCyL/bFl4j1lmdnXdBNX+l + ub/5HTqI7hxAm/qonzDs3iV5KK1ZWZTVsPyqtwIDAQABAoIBAQCGLBQG8HMKgXHT + XSOWIxGCIFONm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/EsGdaWpnpogZismAq74kuXIZUFkHIbvTJd6Xwhm32XgJhy2VLgPyJgC11H4IKfxcatzwkgufAFtgM0CgYEAyH22ILyHIhz/AFX9ZyC2ljq0+Ss3i7DpZEQf5SRWm80zaQwwKCfVgsdtirW9Io3espkv0Snj7y6ZEyDnJOCr2JREyg2Or6pTw0MXSdGWObIlG+ADkTPaJASubfLl1jEr7zAFG8KQN46KK7Uyd31yGC7S1CGl+juj5Pdd5cHmiZMCgYEAqXciqVWcrGeWzo0RULRO3Sr3dlHptQa/4br5fd/irF7szlLeImdeswxVtCNz6JiQmvhhDTB1fkMZWKbGC/1iajr+8arVkoXr1jsAMt3jv0NPolsjZLv0ll2uvSeQF8o+DMHA5jQZjNaTQO2XwI6c0TkseRLL8dbytKvfadM3VD0CgYA52XwZygw73Z3+nNE3VosYoeviEYQ/fFZ7peSGG4wZ/IWfA/NJQuUqjRygb3wZYlIlumm/spSgSRPGHzJSw7kSDwYiPvMy4LS2nL81f5IXJ73pYyPkW8/PoMIr23BR83I32+U9c1Bll21q2yeqrrmjHK+cofDgWSEbSfz/9IjunQKBgQD0KgDr/etEhUooQ6B4JAcNUogkhq5NSyTB2sEctVTtIf5x9DpU3LrOn8zngylQ/mO+JIvrUeZGgSqpwxYsAskfJnXJABldKm2HIzDRqGpNRnvWPW6Qg7RRSMrd2skl3aMZDQt+GUMJftWZREionqRpDRYE0AksWFNbgBLwcZhFmQ==" + let rsaPrivateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER)! + + // Create private keys from both representations of the same key + let keyFromPEM = try! _RSA.Signing.PrivateKey(pemRepresentation: rsaPrivateKeyPEM) + let keyFromDER = try! _RSA.Signing.PrivateKey(derRepresentation: rsaPrivateKeyPKCS8DER) + + XCTAssertEqual(keyFromDER.keySizeInBits, 2048) + XCTAssertEqual(keyFromPEM.keySizeInBits, 2048) + + // The keys match + XCTAssertEqual(keyFromPEM.derRepresentation, keyFromDER.derRepresentation) + + // Our property creates the expected representation + XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, rsaPrivateKeyPKCS8DER) + } + + func test_ed25519() { + let privateKeyPEM = """ + -----BEGIN PRIVATE KEY----- + MC4CAQAwBQYDK2VwBCIEIFSrpkDrDWBMoz/YWjFaW9t4TQaKWyalZ6TRDUS/4+LE + -----END PRIVATE KEY----- + """ + + // Same key in PKCS8 DER representation. + let privateKeyPKCS8DER = Data( + base64Encoded: + "MC4CAQAwBQYDK2VwBCIEIFSrpkDrDWBMoz/YWjFaW9t4TQaKWyalZ6TRDUS/4+LE" + )! + + // We only need the 32 bytes of the key. + let document = try! ASN1.PEMDocument(pemString: privateKeyPEM) + var bytes = document.derBytes + bytes.removeFirst(bytes.count - 32) + + let keyFromDER = try! Curve25519.Signing.PrivateKey(rawRepresentation: bytes) + + let pkcs8 = keyFromDER.pkcs8DERRepresentation + + XCTAssertEqual(pkcs8, privateKeyPKCS8DER) + } + + func test_ed25519_rfc_example() { + // Example key from RFC 8410, Section 10.3. + // Create private key from bytes. + let keyBytes = Data( + base64Encoded: + "1O5y2/kTWErVttjx92n4rTr+fCjL8dT74Jeoj0R1WEI=" + )! + // Same key in PKCS8 DER representation. + let exampleKeyPKCS8DER = Data( + base64Encoded: + "MC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC" + )! + + // Create key from the private key bytes and compare our exported representation. + let exampleKey = try! Curve25519.Signing.PrivateKey(rawRepresentation: keyBytes) + + XCTAssertEqual(exampleKey.pkcs8DERRepresentation, exampleKeyPKCS8DER) + } + + func test_x25519() { + let privateKeyPEM = """ + -----BEGIN PRIVATE KEY----- + MC4CAQAwBQYDK2VuBCIEIKBtrFwBvmRtGZjMyj0rXewOQclz/8cdEY981glA/w5a + -----END PRIVATE KEY----- + """ + + // Same key in PKCS8 DER representation. + let privateKeyPKCS8DER = Data( + base64Encoded: + "MC4CAQAwBQYDK2VuBCIEIKBtrFwBvmRtGZjMyj0rXewOQclz/8cdEY981glA/w5a" + )! + + // We only need the 32 bytes of the key. + let document = try! ASN1.PEMDocument(pemString: privateKeyPEM) + var bytes = document.derBytes + bytes.removeFirst(bytes.count - 32) + + // Create key from the private key bytes and compare our exported representation. + let keyFromDER = try! Curve25519.KeyAgreement.PrivateKey(rawRepresentation: bytes) + + XCTAssertEqual(keyFromDER.pkcs8DERRepresentation, privateKeyPKCS8DER) + } + + func test_P256() { + let privateKeyPEM = """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgO6fz+J/sZqbCki3h + chsrVb69KW8q24pLDwotAtwz/gahRANCAASkBqszxMCGrd8l+xZitPto300blCWk + wRCdoar3UeEEfuH5LsJ3kNjN+oMZmHAmnhHE6cqLHFem/ujsGgrqJ3E8 + -----END PRIVATE KEY----- + """ + let encodedPKCS8DER = + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgO6fz+J/sZqbCki3hchsrVb69KW8q24pLDwotAtwz/gahRANCAASkBqszxMCGrd8l+xZitPto300blCWkwRCdoar3UeEEfuH5LsJ3kNjN+oMZmHAmnhHE6cqLHFem/ujsGgrqJ3E8" + let privateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER)! + + // Create key from PEM and compare our exported representation. + let keyFromPEM = try! P256.Signing.PrivateKey(pemRepresentation: privateKeyPEM) + + XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, privateKeyPKCS8DER) + } + + func test_P384() { + let privateKeyPEM = """ + -----BEGIN PRIVATE KEY----- + MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDD2qUnvEDviY5Hon7fx + rsJmgWCGQcNlU+nXEWOoFPC49kioBm1hsveCH0q3vk9GjZKhZANiAAQFzxvdG2gI + uWZfkAeMW2BzsKGdUWwybx8MHs8fv48MCPmfvL4kIvkU9T7F7diut41ciSzILv5/ + gb45xx6+dZjlWxIopstQuBu5v/J4oa3fgN1uYQJTSsKksDi3L52TcnY= + -----END PRIVATE KEY----- + """ + + // Same key in PKCS8 DER representation. + let encodedPKCS8DER = + "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDD2qUnvEDviY5Hon7fxrsJmgWCGQcNlU+nXEWOoFPC49kioBm1hsveCH0q3vk9GjZKhZANiAAQFzxvdG2gIuWZfkAeMW2BzsKGdUWwybx8MHs8fv48MCPmfvL4kIvkU9T7F7diut41ciSzILv5/gb45xx6+dZjlWxIopstQuBu5v/J4oa3fgN1uYQJTSsKksDi3L52TcnY=" + let privateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER)! + + // Create key from PEM and compare our exported representation. + let keyFromPEM = try! P384.Signing.PrivateKey(pemRepresentation: privateKeyPEM) + + XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, privateKeyPKCS8DER) + } + + func test_P521() { + let privateKeyPEM = """ + -----BEGIN PRIVATE KEY----- + MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBcQv0MVt8xb5teBQJ + Mqn7wnQ2GVzgL+jkMERcMaABU7+UL7uC0ff+15RKEI2RwKLVUVvp3WJigCHBDpwY + qI9OFnyhgYkDgYYABAD7PeX+GFUa99yyhYJ4WReKq2nLUOjo+ZZ+pdepc0EaESj+ + 8o2Sv4mRjIU0s3WFTNx0mh9BKiszBNRu2nq148ZfCwAcAiJu4xcwR2o+L7BqNadJ + 1hCoVItbL61BWxAMITZPegQLMV1K7SMS6NNkYBBIh10Q870tBO26VJ5wMm5K46MA + Cg== + -----END PRIVATE KEY----- + """ + + // Same key in PKCS8 DER representation. + let encodedPKCS8DER = + "MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBcQv0MVt8xb5teBQJMqn7wnQ2GVzgL+jkMERcMaABU7+UL7uC0ff+15RKEI2RwKLVUVvp3WJigCHBDpwYqI9OFnyhgYkDgYYABAD7PeX+GFUa99yyhYJ4WReKq2nLUOjo+ZZ+pdepc0EaESj+8o2Sv4mRjIU0s3WFTNx0mh9BKiszBNRu2nq148ZfCwAcAiJu4xcwR2o+L7BqNadJ1hCoVItbL61BWxAMITZPegQLMV1K7SMS6NNkYBBIh10Q870tBO26VJ5wMm5K46MACg==" + let privateKeyPKCS8DER = Data(base64Encoded: encodedPKCS8DER) + + // Create key from PEM and compare our exported representation. + let keyFromPEM = try! P521.Signing.PrivateKey(pemRepresentation: privateKeyPEM) + + XCTAssertEqual(keyFromPEM.pkcs8DERRepresentation, privateKeyPKCS8DER) + } +}