PEM Format for RSA Keys Explained

Understand the PEM format for RSA keys: Base64-encoded DER with header/footer lines. Learn about PKCS#1, PKCS#8, and how to convert between PEM and DER formats.

Key Formats

Detailed Explanation

PEM Format for RSA Keys

PEM (Privacy-Enhanced Mail) is the most common encoding format for cryptographic keys and certificates. It stores binary DER-encoded data as Base64 text wrapped in distinctive header and footer lines.

PEM Structure

A PEM file has three parts:

-----BEGIN [TYPE]-----
[Base64-encoded DER data, 64 characters per line]
-----END [TYPE]-----

Common PEM Types for RSA

Header Format Contains
BEGIN RSA PRIVATE KEY PKCS#1 RSA private key only
BEGIN PRIVATE KEY PKCS#8 Algorithm identifier + private key
BEGIN RSA PUBLIC KEY PKCS#1 RSA public key only
BEGIN PUBLIC KEY SPKI/X.509 Algorithm identifier + public key
BEGIN ENCRYPTED PRIVATE KEY PKCS#8 encrypted Passphrase-protected private key

PKCS#1 vs PKCS#8

PKCS#1 is RSA-specific:

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA...
-----END RSA PRIVATE KEY-----

PKCS#8 is algorithm-agnostic (recommended for new applications):

-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASC...
-----END PRIVATE KEY-----

The PKCS#8 format includes an AlgorithmIdentifier OID that specifies the key type, making it usable with any asymmetric algorithm.

PEM vs DER

  • PEM: Text format, can be concatenated, easily copied into config files
  • DER: Binary format, smaller file size, used in Java keystores and some TLS implementations

Converting Between Formats

# PEM to DER
openssl pkey -in key.pem -outform DER -out key.der

# DER to PEM
openssl pkey -in key.der -inform DER -out key.pem

# PKCS#1 to PKCS#8
openssl pkcs8 -topk8 -in rsa_key.pem -out pkcs8_key.pem -nocrypt

# Extract public key from private
openssl pkey -in private.pem -pubout -out public.pem

Multi-Object PEM Files

PEM files can contain multiple objects (certificate chain + private key). Each object is delimited by its own BEGIN/END markers. Parsers read them sequentially.

Use Case

Developers encounter PEM format when configuring TLS/SSL certificates on web servers, setting up SSH keys, implementing JWT signing, or working with any PKI infrastructure. Understanding the differences between PKCS#1 and PKCS#8 is crucial when integrating with different libraries and platforms that may expect specific formats.

Try It — RSA Key Pair Generator

Open full tool