We now have the RSA public key. The next step is to produce the appropriate output format.

PKCS#1 Public Key Format

Our target format is a PEM-encoded PKCS#1 public key.

PKCS#1 is “the first of a family of standards called Public-Key Cryptography Standards (PKCS), published by RSA Laboratories.” (Wikipedia). You can identify a PKCS#1 PEM-encoded public key by the markers used to delimit the base64 encoded data:

-----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----

This is different from an x.509 public key, which looks like this:

-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----

The x.509 format may be used to store keys generated using algorithms other than RSA.

The data in a PKCS#1 key is encoded using DER, which is a set of rules for serializing ASN.1 data. For more information see:

Appendix: OpenSSH private key format

Whereas the OpenSSH public key format is effectively “proprietary” (that is, the format is used only by OpenSSH), the private key is already stored as a PKCS#1 private key. This means that the private key can be manipulated using the OpenSSL command line tools.

The clever folks among you may be wondering if, assuming we have the private key available, we could have skipped this whole exercise and simply extracted the public key in the correct format using the openssl command. We can come very close…the following demonstrates how to extract the public key from the private key using openssl: