0
# PEM
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: pem
7
- **Language**: Python
8
- **Installation**: `pip install pem`
9
10
## Core Imports
11
12
```python
13
import pem
14
```
15
16
For individual components:
17
18
```python
19
from pem import parse, parse_file, Certificate, PrivateKey
20
```
21
22
## Basic Usage
23
24
```python
25
import pem
26
27
# Parse PEM objects from a file
28
pem_objects = pem.parse_file("certificate_chain.pem")
29
print(f"Found {len(pem_objects)} PEM objects")
30
31
# Parse from string/bytes
32
pem_string = """-----BEGIN CERTIFICATE-----
33
MIIBkjCB...
34
-----END CERTIFICATE-----"""
35
36
objects = pem.parse(pem_string)
37
for obj in objects:
38
print(f"Object type: {type(obj).__name__}")
39
print(f"SHA-1 digest: {obj.sha1_hexdigest}")
40
41
# Work with individual objects
42
if objects:
43
cert = objects[0]
44
print(f"PEM content: {cert.as_text()}")
45
print(f"Base64 payload: {cert.text_payload}")
46
47
# Access decoded payload for further processing
48
decoded_data = cert.decoded_payload
49
```
50
51
## Architecture
52
53
The PEM package uses a pattern-based parsing system:
54
55
- **Parser Functions**: `parse()` and `parse_file()` use regex patterns to identify and extract PEM objects
56
- **Abstract Base Class**: `AbstractPEMObject` provides common methods for all PEM object types
57
- **Concrete Classes**: 16 specific PEM object types (Certificate, PrivateKey, PublicKey, etc.) each with unique pattern matching
58
- **Twisted Integration**: Optional helpers for creating Twisted TLS contexts from PEM objects
59
60
All PEM objects are immutable and provide consistent access to raw content, payloads, and metadata.
61
62
## Capabilities
63
64
### Core Parsing Functions
65
66
Essential functions for parsing PEM files and strings into structured objects. These functions automatically detect and categorize different PEM object types.
67
68
```python { .api }
69
def parse(pem_str: bytes | str) -> list[AbstractPEMObject]:
70
"""Extract PEM-like objects from string or bytes."""
71
72
def parse_file(file_name: str | Path) -> list[AbstractPEMObject]:
73
"""Read file and parse PEM objects from it."""
74
```
75
76
[Core Parsing](./core-parsing.md)
77
78
### PEM Object Types
79
80
Complete set of PEM object classes representing different cryptographic objects including certificates, keys, and parameters. Each type provides specialized functionality while inheriting common methods.
81
82
```python { .api }
83
class Certificate(AbstractPEMObject): ...
84
class PrivateKey(AbstractPEMObject): ...
85
class PublicKey(AbstractPEMObject): ...
86
class RSAPrivateKey(PrivateKey): ...
87
class ECPrivateKey(PrivateKey): ...
88
class DHParameters(AbstractPEMObject): ...
89
```
90
91
[PEM Object Types](./pem-objects.md)
92
93
### Twisted Integration
94
95
Specialized helpers for the Twisted framework that convert PEM objects into Twisted TLS contexts, handling certificate chains and key matching automatically.
96
97
```python { .api }
98
def certificateOptionsFromPEMs(
99
pemObjects: list[AbstractPEMObject],
100
**kw: object
101
) -> ssl.CertificateOptions: ...
102
103
def certificateOptionsFromFiles(
104
*pemFiles: str,
105
**kw: object
106
) -> ssl.CertificateOptions: ...
107
```
108
109
[Twisted Integration](./twisted-integration.md)
110
111
## Common Types
112
113
```python { .api }
114
class AbstractPEMObject:
115
"""Base class for all PEM objects."""
116
117
def __str__(self) -> str:
118
"""Return the PEM-encoded content as a native string."""
119
120
def __repr__(self) -> str:
121
"""Return a string representation with class name and SHA-1 digest."""
122
123
def __eq__(self, other: object) -> bool:
124
"""Compare objects for equality based on type and content."""
125
126
def __hash__(self) -> int:
127
"""Return hash of the PEM bytes for use in sets and dictionaries."""
128
129
@property
130
def sha1_hexdigest(self) -> str:
131
"""SHA-1 digest of the whole object for differentiation."""
132
133
def as_bytes(self) -> bytes:
134
"""Return PEM-encoded content as bytes."""
135
136
def as_text(self) -> str:
137
"""Return PEM-encoded content as text."""
138
139
@property
140
def bytes_payload(self) -> bytes:
141
"""Base64 payload without headers."""
142
143
@property
144
def text_payload(self) -> str:
145
"""Base64 payload as text."""
146
147
@property
148
def decoded_payload(self) -> bytes:
149
"""Base64-decoded payload."""
150
151
@property
152
def meta_headers(self) -> dict[str, str]:
153
"""Dictionary of payload headers."""
154
```
155
156
## Module Metadata
157
158
The module provides access to package metadata through special attributes:
159
160
```python { .api }
161
def __getattr__(name: str) -> str:
162
"""
163
Access package metadata attributes dynamically.
164
165
Supported attributes:
166
- __version__: Package version
167
- __description__: Package summary (deprecated)
168
- __uri__: Project URL (deprecated)
169
- __url__: Project URL (deprecated)
170
- __email__: Author email (deprecated)
171
172
Returns:
173
str: The requested metadata value
174
175
Raises:
176
AttributeError: If attribute name is not supported
177
"""
178
```
179
180
**Usage Example:**
181
182
```python
183
import pem
184
185
# Get package version
186
version = pem.__version__
187
print(f"PEM package version: {version}")
188
189
# Deprecated attributes (will show warnings)
190
# Use importlib.metadata directly instead
191
description = pem.__description__ # Deprecated
192
url = pem.__url__ # Deprecated
193
```