← Back to section · Tutorials & Labs

Encoding Formats in Practice: PEM, DER, Base64 and Hex, and How They Differ

In memory a key is an object; on disk and on the wire it must become bytes, and the same key material can wear several different outer layers — PEM, DER, Base64 and more. This tutorial walks through exporting and loading keys with the cryptography library's serialization interface and clears up the confusions that bite most often.

Published 22 November 2026 · 6 min read · PQ Frontier

Encoding Formats in Practice: PEM, DER, Base64 and Hex, and How They Differ
AI-generated site artwork
Video explainer · Python cryptography: experiments and prototypes

What this tutorial aims to do

Almost every beginner eventually stares at a block of text starting with “-----BEGIN” and wonders why the same key looks completely different in two different tools. The reason: inside a program a key is an object, but to be stored in a file, pasted into a configuration or carried in a request it must first become a byte sequence, and there are several layered conventions for what those bytes look like. This tutorial walks an Ed25519 key through export and loading with the cryptography library, explains the division of labour between DER, PEM, Base64 and hexadecimal, and points out the confusions that occur most often in practice. One sentence should stay with you throughout: encoding is only a change of clothes, not encryption — a private key dressed in PEM is still a plaintext private key.

The division of labour between four representations

Build the picture in layers. At the bottom sits structure encoding: key material contains an algorithm identifier, parameters and the key bytes themselves, and needs an unambiguous binary layout — that is DER (Distinguished Encoding Rules), a deterministic encoding of ASN.1; the binary substance of certificates and key files is DER. Above it sits the text shell: binary does not travel well through email, configuration files and terminals, so PEM exists — essentially DER run through Base64, wrapped in marker lines such as “-----BEGIN PRIVATE KEY-----” and wrapped at a fixed line width. Base64 itself is just a generic encoding that turns every 3 bytes into 4 printable characters, inflating size by about a third; hexadecimal writes each byte as two characters, doubling the size, but is human-readable and convenient for comparing fingerprints and digests in logs. The relationship compresses into one line: DER handles structure, PEM handles text packaging, and Base64 and hex are merely porters between bytes and text.

Exporting and loading keys with cryptography

The serialization interface of the cryptography library is designed very systematically: a private key object offers private_bytes(), whose three arguments are the Encoding (PEM, DER or Raw), the structure PrivateFormat (PKCS8 is the usual choice for private keys) and the password protection encryption_algorithm. Public keys mirror this with public_bytes() and PublicFormat.SubjectPublicKeyInfo. The code below generates an Ed25519 key, exports it in both PEM and DER shapes, loads it back from PEM and verifies a signature, and prints a hexadecimal fingerprint along the way:

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

private_key = Ed25519PrivateKey.generate()

# Export PEM (text form, no password protection — demo only; encrypt at rest)
pem_bytes = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption(),
)
print(pem_bytes.decode().splitlines()[0])  # -----BEGIN PRIVATE KEY-----

# Export the public key as DER (binary form)
der_bytes = private_key.public_key().public_bytes(
    serialization.Encoding.DER,
    serialization.PublicFormat.SubjectPublicKeyInfo,
)

# Public-key fingerprint: SHA-256 over the DER, shown in hexadecimal
import hashlib
fingerprint = hashlib.sha256(der_bytes).hexdigest()
print("public key fingerprint:", fingerprint)

# Load the private key back from PEM and confirm it is the same key
loaded = serialization.load_pem_private_key(pem_bytes, password=None)
message = b"encoding demo"
signature = loaded.sign(message)
loaded.public_key().verify(signature, message)
print("loaded successfully; signature verifies")

To password-protect a private-key PEM, replace NoEncryption() with serialization.BestAvailableEncryption(b"your passphrase") and pass the same passphrase as the password argument when loading. DER loading has the counterpart load_der_private_key(), mirroring the PEM interface one to one.

Reading the structure type from the PEM marker line

The PEM marker line is a free instruction label, and it pays to read it at a glance. A marker saying “PRIVATE KEY” denotes the PKCS#8 structure, which embeds its own algorithm identifier and serves as the single shell for RSA, Ed25519 and other private keys alike — it is also the cryptography library’s default export format. Markers saying “RSA PRIVATE KEY” or “EC PRIVATE KEY” denote the older PKCS#1 and SEC1 structures, with the algorithm fixed by the marker itself; they appear in legacy systems and early OpenSSL defaults. On the public-key side, the “PUBLIC KEY” marker corresponds to the SubjectPublicKeyInfo structure, likewise self-describing, and is the safest choice for exchanging public keys across systems. One more format invites confusion: SSH public keys, the single-line strings beginning with “ssh-ed25519”, are OpenSSH’s own wire format — neither PEM nor DER — and the cryptography library provides a dedicated Encoding.OpenSSH and matching loaders for them, which PEM loaders cannot read. In practice, when a key file arrives, look at three things: is there a PEM marker, which structure does the marker name, and is it a single-line OpenSSH format instead? After those three looks, the right load_* function is essentially decided. When truly unsure, letting the library try the PEM and DER loaders in turn and catching the exceptions is still far more reliable than writing your own parsing logic.

Why certificates use the same encoding system

Widen the view one notch: the certificate files you meet in browsers every day share the very same encoding system as key files. The substance of an X.509 certificate is likewise a DER-encoded ASN.1 structure, and dressed in a PEM shell it becomes text beginning with “-----BEGIN CERTIFICATE-----”; the reason a server can keep its certificate-chain file and private-key file side by side and have one toolchain read both is precisely this shared convention. Understanding this pays off immediately in practice: when a tool reports “cannot load certificate” or “key and certificate do not match”, your debugging order becomes clear at once — first confirm whether the file is PEM or DER and whether the marker names the right structure, then confirm the private key and the certificate’s public key are really a pair. Nine times out of ten such failures live in the encoding layer, not the cryptography layer: a DER file renamed to masquerade as PEM, a certificate chain assembled in the wrong order, or a password-protected private key handed to a loader that does not support passwords. Treating the encoding layer as an independent layer that can be verified on its own is the master switch for every key-and-certificate interoperability problem.

The three confusions that bite most often

Trap one: treating Base64 as structure. Someone receives a Base64 blob and assumes decoding is enough, forgetting that Base64 carries no information about whether the decoded bytes are DER or raw, private or public — that distinction must come from context or from the PEM marker lines, which is exactly why those markers exist. Trap two: parsing formats by hand. Trying to slice the middle out of a PEM block with string operations, or assembling DER bytes yourself, is wrestling with the format specification; always use the library’s load_* and *_bytes interfaces and let it handle format variants such as PKCS#1 versus PKCS#8 private-key structures. Trap three: mistaking encoding for encryption, already stressed above — a Base64-encoded private key is no different from a plaintext one, and printing it in logs, committing it to a repository or pasting it into a chat tool is a genuine key leak. One operational rule to finish: whenever a key crosses system boundaries, align on three things first — is the encoding PEM or DER, is the structure PKCS#8 or raw public-key bytes, and is it password-protected? Get those three right and most interoperability problems disappear.

Tags: PythonPEMDEREncoding