PEM file parsing for Python
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
- gotcha PEM files are frequently used for sensitive cryptographic material like private keys. These should generally NOT be committed to version control systems like Git.
- gotcha When working with `requests` or `ssl` modules, ensure your PEM file contains the complete certificate chain (server certificate, intermediate CAs, and root CA) if you are providing it for verification. An incomplete chain can lead to `SSLCertVerificationError`.
- gotcha The `pem` library strictly parses PEM-encoded data. If you are attempting to parse a file that is in DER (Distinguished Encoding Rules) format without PEM wrappers, `pem` will not be able to process it.
Install
-
pip install pem
Imports
- pem
import pem
Quickstart
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