apple / swift-crypto

Open-source implementation of a substantial portion of the API of Apple CryptoKit suitable for use on Linux platforms.
https://apple.github.io/swift-crypto
Apache License 2.0
1.47k stars 166 forks source link

No way to get PKCS#8 representation of private RSA key #202

Closed bjhomer closed 1 year ago

bjhomer commented 1 year ago

New Issue Checklist

Expected behavior

_CryptoExtras.RSA.Encryption.PublicKey and .PrivateKey have the following:

struct PublicKey {
  // The PKCS#8 PEM representation of the public key
  var pemRepresenation: String {}

  // The PKCS#1 PEM representation of the public key
  var pkcs1PEMRepresentation: String {}
}

extension PrivateKey {
  // The PKCS#1 PEM representation of the private key
  var pemRepresentation: String {}
}

I expected that publicKey.pemRepresentation and privateKey.pemRepresenatation would use the same standard (PKCS#8), especially since the public key specifically calls out when it's using PKCS#1. However, in practice, the similarly-named methods produce separate results, and there's no provided way to get the PKCS#8 representation of a private key.

The inconsistency in formatting between publicKey.pemRepresentation and privateKey.pemRepresentation is unfortunate. Unfortunately, for stability reasons we probably cannot change the return types of either of these. But it would be nice to have a way to get a consistent representation. Perhaps .pkcs8PEMRepresentation could be added to both, so that users can be explicit about which they want?

If possible, minimal yet complete reproducer code (or URL to code)

import _CryptoExtras

let key = try! _RSA.Encryption.PrivateKey(keySize: .bits2048)
let privatePEM = key.pemRepresenatation
let publicPEM = key.publicKey.pemRepresentation

// succeeds
assert(publicPEM.hasPrefix("-----BEGIN PUBLIC KEY-----"))

// fails
assert(privatePEM.hasPrefix("-----BEGIN PRIVATE KEY-----"))

Swift Crypto version/commit hash

3.0.0

Lukasa commented 1 year ago

Sure, we'd be willing to add support for pkcs8PEMRepresentation to the private key. Would you be open to writing a patch?

bjhomer commented 1 year ago

Yeah, I can do that.

bjhomer commented 1 year ago

@Lukasa A patch can be found here.