or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-parsing.mdindex.mdpem-objects.mdtwisted-integration.md
tile.json

tessl/pypi-pem

PEM file parsing in Python for extracting certificates, keys, and cryptographic objects.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pem@23.1.x

To install, run

npx @tessl/cli install tessl/pypi-pem@23.1.0

index.mddocs/

PEM

A Python library for parsing and splitting PEM files (Privacy-Enhanced Mail format). It extracts Base64-encoded DER keys and certificates with no dependencies, supporting various certificate deployment scenarios where different servers expect certificates, keys, and trust chains in different file configurations.

Package Information

  • Package Name: pem
  • Language: Python
  • Installation: pip install pem

Core Imports

import pem

For individual components:

from pem import parse, parse_file, Certificate, PrivateKey

Basic Usage

import pem

# Parse PEM objects from a file
pem_objects = pem.parse_file("certificate_chain.pem")
print(f"Found {len(pem_objects)} PEM objects")

# Parse from string/bytes
pem_string = """-----BEGIN CERTIFICATE-----
MIIBkjCB...
-----END CERTIFICATE-----"""

objects = pem.parse(pem_string)
for obj in objects:
    print(f"Object type: {type(obj).__name__}")
    print(f"SHA-1 digest: {obj.sha1_hexdigest}")

# Work with individual objects
if objects:
    cert = objects[0]
    print(f"PEM content: {cert.as_text()}")
    print(f"Base64 payload: {cert.text_payload}")
    
    # Access decoded payload for further processing
    decoded_data = cert.decoded_payload

Architecture

The PEM package uses a pattern-based parsing system:

  • Parser Functions: parse() and parse_file() use regex patterns to identify and extract PEM objects
  • Abstract Base Class: AbstractPEMObject provides common methods for all PEM object types
  • Concrete Classes: 16 specific PEM object types (Certificate, PrivateKey, PublicKey, etc.) each with unique pattern matching
  • Twisted Integration: Optional helpers for creating Twisted TLS contexts from PEM objects

All PEM objects are immutable and provide consistent access to raw content, payloads, and metadata.

Capabilities

Core Parsing Functions

Essential functions for parsing PEM files and strings into structured objects. These functions automatically detect and categorize different PEM object types.

def parse(pem_str: bytes | str) -> list[AbstractPEMObject]:
    """Extract PEM-like objects from string or bytes."""

def parse_file(file_name: str | Path) -> list[AbstractPEMObject]:
    """Read file and parse PEM objects from it."""

Core Parsing

PEM Object Types

Complete set of PEM object classes representing different cryptographic objects including certificates, keys, and parameters. Each type provides specialized functionality while inheriting common methods.

class Certificate(AbstractPEMObject): ...
class PrivateKey(AbstractPEMObject): ...
class PublicKey(AbstractPEMObject): ...
class RSAPrivateKey(PrivateKey): ...
class ECPrivateKey(PrivateKey): ...
class DHParameters(AbstractPEMObject): ...

PEM Object Types

Twisted Integration

Specialized helpers for the Twisted framework that convert PEM objects into Twisted TLS contexts, handling certificate chains and key matching automatically.

def certificateOptionsFromPEMs(
    pemObjects: list[AbstractPEMObject], 
    **kw: object
) -> ssl.CertificateOptions: ...

def certificateOptionsFromFiles(
    *pemFiles: str, 
    **kw: object
) -> ssl.CertificateOptions: ...

Twisted Integration

Common Types

class AbstractPEMObject:
    """Base class for all PEM objects."""
    
    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."""

Module Metadata

The module provides access to package metadata through special attributes:

def __getattr__(name: str) -> str:
    """
    Access package metadata attributes dynamically.
    
    Supported attributes:
    - __version__: Package version
    - __description__: Package summary (deprecated)
    - __uri__: Project URL (deprecated)
    - __url__: Project URL (deprecated) 
    - __email__: Author email (deprecated)
    
    Returns:
        str: The requested metadata value
        
    Raises:
        AttributeError: If attribute name is not supported
    """

Usage Example:

import pem

# Get package version
version = pem.__version__
print(f"PEM package version: {version}")

# Deprecated attributes (will show warnings)
# Use importlib.metadata directly instead
description = pem.__description__  # Deprecated
url = pem.__url__                  # Deprecated