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.43k stars 151 forks source link

pkcs8PEMRepresenation for RSA private keys #203

Closed bjhomer closed 9 months ago

bjhomer commented 9 months ago

This PR adds a pkcs8PEMRepresentation property to RSA public keys.

Checklist

If you've made changes to gyb files

Motivation:

There are two widely-used formats for public and private keys. PKCS#1 defines the format for RSA keys, which begin with BEGIN RSA {PUBLIC/PRIVATE KEY}

Later, as additional key types were implemented, more general containers were introduced. X.509 introduces SubjectPublicKeyInfo (SPKI), which defines a general structure for containing any type of public key (RSA or otherwise). PKCS#8 does the same for private keys. privateKey.pemRepresentation gives the PKCS#1 representation, but there's no equivalent for getting the PCKS8 representation.

Our implementation of RSA keys included a way to get both the new and old format of public keys (via publicKey.pemRepresentation and publicKey.pkcs1PEMRepresentation), but we didn't have a way to get both the new and old formats of private keys.

This PR introduces _RSA.PrivateKey.pkcs8PEMRepresentation to fill that gap.

Modifications:

Note that the BoringSSL implementation of pkcs8PEMRepresentation includes a trailing newline. The naive implementation using Security.framework would not have that trailing newline, but for consistency between the two implementations, I have added it to both.

I'm open to instead stripping off the trailing new line on the BoringSSL implementation, but I was less sure of how to implement that.

Result:

RSA private keys now have pkcs8PEMRepresentation.

Lukasa commented 9 months ago

@swift-server-bot test this please