PEM file parsing in Python for extracting certificates, keys, and cryptographic objects.
—
Essential functions for parsing PEM files and strings into structured objects. These functions automatically detect and categorize different PEM object types using pattern matching.
Parses PEM objects from string or bytes input, extracting all recognizable PEM-encoded cryptographic objects using regex patterns.
def parse(pem_str: bytes | str) -> list[AbstractPEMObject]:
"""
Extract PEM-like objects from string or bytes.
Args:
pem_str: PEM-encoded content as bytes or string
Returns:
list[AbstractPEMObject]: List of parsed PEM objects, each typed
according to its content (Certificate, PrivateKey, etc.)
"""Usage Example:
import pem
# Parse from string
pem_string = """-----BEGIN CERTIFICATE-----
MIIBkjCB/AIBATANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA7bNnbNf7hEtC...
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAO2zZ2zX+4RL...
-----END RSA PRIVATE KEY-----"""
objects = pem.parse(pem_string)
print(f"Found {len(objects)} PEM objects")
for obj in objects:
print(f"Type: {type(obj).__name__}")
print(f"SHA-1: {obj.sha1_hexdigest}")
# Also works with bytes
pem_bytes = pem_string.encode('utf-8')
objects_from_bytes = pem.parse(pem_bytes)Reads a file and parses PEM objects from its contents using the core parse() function.
def parse_file(file_name: str | Path) -> list[AbstractPEMObject]:
"""
Read file and parse PEM objects from it.
Args:
file_name: Path to file containing PEM objects (string or pathlib.Path)
Returns:
list[AbstractPEMObject]: List of parsed PEM objects from the file
"""Usage Example:
import pem
from pathlib import Path
# Parse from file path string
objects = pem.parse_file("certificates.pem")
# Also works with pathlib.Path objects
cert_path = Path("certs") / "server.pem"
objects = pem.parse_file(cert_path)
# Process parsed objects
for obj in objects:
if isinstance(obj, pem.Certificate):
print(f"Certificate SHA-1: {obj.sha1_hexdigest}")
elif isinstance(obj, pem.PrivateKey):
print(f"Private key SHA-1: {obj.sha1_hexdigest}")-----BEGIN and -----END markersInstall with Tessl CLI
npx tessl i tessl/pypi-pem