RSA Key Formats

Page content

In a previous post, I discussed some of what I’d learned about key formats used by various ciphers. This post will go into more detail for RSA, covering the RSA key formats available, including formats that password protect private keys.

Two formats

The old

Traditionally, RSA keys have been generated with OpenSSL’s genrsa command. The simplest way to do this is to do something like:

$ openssl genrsa 2048 > key1-plain.pem

RSA Private Key

This generates a private key in “PEM” format that will begin with the line:

-----BEGIN RSA PRIVATE KEY-----

The ASN1 for this is defined in RFC3447 and is essential a sequence containing the raw parameters. The key will need to either by contained in some other structure, or written in PEM format so that the type can be distinguished.

This tool also allows the key to be password protected:

$ openssl genrsa -aes128 > key1-aes.pem

This will generate a private key in PEM format with this header:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,696B662369F3E6DF990E11D087A0967D

Since this format is considered deprecated, I won’t go into further detail about it at this time. I assume the hex value is an IV for AES-128-CBC, but I’m not sure what the KDF is from the user-typed password.

The new

The new way of generating RSA private keys (as well as other formats) is to use the genpkey command:

$ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 \
    > key2-plain.pem

This generates a PEM block starting with BEGIN PRIVATE KEY, which is encoded in PKCS#8 format.

Lastly, we can add the -aes-128-cbc argument to the above OpenSSL command, which will give us a PEM file with BEGIN ENCRYPTED PRIVATE KEY. This is the variant we are most interested in.

Encrypted private keys.

PKCS#8 defines an encoding for private keys that includes a way of encrypting the key with a password. The wrapping is defined in PKCS#5. The algorithm given with -aes-128-cbc uses “PBES2”, which uses PBKDF2 with a given salt, hash function, and iteration count to derive the encryption key for the aes 128 CBC encryption itself.