PEM file parsing in Python for extracting certificates, keys, and cryptographic objects.
—
Complete set of PEM object classes representing different cryptographic objects. All classes inherit from AbstractPEMObject and provide specialized functionality while maintaining consistent access to raw content, payloads, and metadata.
Base class for all parsed PEM objects providing common functionality for content access and manipulation.
class AbstractPEMObject:
"""Base class for all PEM objects."""
def __init__(self, pem_bytes: bytes | str):
"""Initialize with PEM-encoded content."""
def __str__(self) -> str:
"""Return the PEM-encoded content as a native string."""
def __repr__(self) -> str:
"""Return a string representation with class name and SHA-1 digest."""
def __eq__(self, other: object) -> bool:
"""Compare objects for equality based on type and content."""
def __hash__(self) -> int:
"""Return hash of the PEM bytes for use in sets and dictionaries."""
@property
def sha1_hexdigest(self) -> str:
"""SHA-1 digest of the whole object for differentiation."""
def as_bytes(self) -> bytes:
"""Return PEM-encoded content as bytes."""
def as_text(self) -> str:
"""Return PEM-encoded content as text."""
@property
def bytes_payload(self) -> bytes:
"""Base64 payload without headers."""
@property
def text_payload(self) -> str:
"""Base64 payload as text."""
@property
def decoded_payload(self) -> bytes:
"""Base64-decoded payload."""
@property
def meta_headers(self) -> dict[str, str]:
"""Dictionary of payload headers (if any)."""Standard X.509 certificate objects.
class Certificate(AbstractPEMObject):
"""Standard certificate."""OpenSSL "trusted certificate" format with additional metadata.
class OpenSSLTrustedCertificate(Certificate):
"""OpenSSL trusted certificate with metadata."""Certificate signing request (CSR) objects.
class CertificateRequest(AbstractPEMObject):
"""Certificate signing request."""Certificate revocation list (CRL) objects.
class CertificateRevocationList(AbstractPEMObject):
"""Certificate revocation list."""Base classes for different key types.
class Key(AbstractPEMObject):
"""Base class for keys of unknown type."""
class PrivateKey(Key):
"""Private key of unknown type."""
class PublicKey(Key):
"""Public key of unknown type."""RSA-specific key types.
class RSAPrivateKey(PrivateKey):
"""RSA private key in PKCS#1 format."""
class RSAPublicKey(PublicKey):
"""RSA public key in PKCS#1 format."""Elliptic curve cryptography keys.
class ECPrivateKey(PrivateKey):
"""Elliptic curve private key."""Digital Signature Algorithm keys.
class DSAPrivateKey(PrivateKey):
"""DSA private key (including OpenSSH legacy format)."""SSH-specific key formats.
class OpenSSHPrivateKey(PrivateKey):
"""OpenSSH private key format."""
class SSHPublicKey(PublicKey):
"""SSH RFC 4716 format public key."""
class SSHCOMPrivateKey(PrivateKey):
"""SSH.COM / Tectia format private key."""OpenPGP armored key formats.
class OpenPGPPublicKey(PublicKey):
"""RFC 4880 armored OpenPGP public key."""
class OpenPGPPrivateKey(PrivateKey):
"""RFC 4880 armored OpenPGP private key."""Diffie-Hellman parameters for key exchange.
class DHParameters(AbstractPEMObject):
"""Diffie-Hellman parameters for DHE cipher suites."""import pem
# Parse mixed PEM file
objects = pem.parse_file("bundle.pem")
# Filter by type
certificates = [obj for obj in objects if isinstance(obj, pem.Certificate)]
private_keys = [obj for obj in objects if isinstance(obj, pem.PrivateKey)]
# Access certificate properties
for cert in certificates:
print(f"Certificate SHA-1: {cert.sha1_hexdigest}")
print(f"Certificate text: {cert.as_text()}")
# Access decoded certificate data for further processing
der_data = cert.decoded_payloadimport pem
objects = pem.parse_file("keys.pem")
for obj in objects:
if isinstance(obj, pem.RSAPrivateKey):
print("RSA private key found")
elif isinstance(obj, pem.ECPrivateKey):
print("EC private key found")
elif isinstance(obj, pem.OpenSSHPrivateKey):
print("OpenSSH private key found")
elif isinstance(obj, pem.PrivateKey):
print("Generic private key found")import pem
# Some PEM objects may contain headers
objects = pem.parse(pem_with_headers)
for obj in objects:
headers = obj.meta_headers
if headers:
print(f"Headers: {headers}")
# Access base64 payload
b64_payload = obj.text_payload
raw_payload = obj.decoded_payloadAll PEM objects are immutable and provide:
Install with Tessl CLI
npx tessl i tessl/pypi-pem