PEM file parsing for Python

23.1.0 · active · verified Sat Apr 11

The `pem` library is a Python module designed for parsing and splitting PEM (Privacy Enhanced Mail) files, which contain Base64-encoded DER keys and certificates. It is a lightweight tool with no external dependencies, focusing solely on file parsing without interpreting the certificate data itself. The current version is 23.1.0, and it maintains a steady, though not rapid, release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a PEM file. It first creates a dummy `example.pem` file with a sample certificate, then uses `pem.parse_file()` to read and extract the PEM objects. The type and a truncated string representation of each found object are printed.

import pem

# Create a dummy PEM file for demonstration
with open("example.pem", "w") as f:
    f.write("-----BEGIN CERTIFICATE-----\n")
    f.write("MIIDTDCCArSgAwIBAgIUJgMhCgS1P2Q3R5fL6Z9y/B0X6UowDQYJKoZIhvcNAQEL\n")
    f.write("BQAwMjELMAkGA1UEBhMCSVQxEDAOBgNVBAgMB0xhdGlvczEQMA4GA1UEAwwHVGVz\n")
    f.write("dENlcnQwHhcNMjMwMTAxMDAwMDAwWhcNMzMwMTAxMDAwMDAwWjAyMQswCQYDVQQG\n")
    f.write("EwJJVDERMA8GA1UECAwIQ2l0dGFkZTEPMA0GA1UEAwwGbG9jYWxoZDAwggEiMA0G\n")
    f.write("CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDEcE5pZz3lF9mJ8p+qG7xR7qK6YmQp\n")
    f.write("qM2oY0t/J2n7c5y2X6Q5F7pW1Z7rC9Q9X0P0P0P0P0P0P0P0P0P0P0P0P0P0P0P\n")
    f.write("AgMBAAGjUzBRMB0GA1UdDgQWBBTx3B4e3b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b\n")
    f.write("MCgGA1UdEQQfMB2CDXNvbWVkb21haW4uY29tggdFWEFNUExFMzANBgkqhkiG9w0B\n")
    f.write("AQsFAAOCAQEAy/qJ/w+7p+2v+6v+7v+8v/9v/g+v/x+y/0+1/2/3/4/5/6/7/8/\n")
    f.write("-----END CERTIFICATE-----\n")

certs = pem.parse_file("example.pem")
for cert in certs:
    print(f"Found PEM object: {type(cert).__name__}")
    print(str(cert)[:100] + "...") # Print first 100 chars of the PEM string

view raw JSON →