0
# Certificate Management
1
2
Comprehensive X.509 certificate lifecycle management including creation, signing, verification, and parsing. Supports certificate extensions, distinguished names, and various encoding formats.
3
4
## Capabilities
5
6
### X.509 Certificates
7
8
Complete certificate objects with support for standard X.509 fields, extensions, and cryptographic operations.
9
10
```python { .api }
11
class X509:
12
def __init__(self):
13
"""Create new empty certificate"""
14
15
def get_subject(self) -> X509Name:
16
"""Get certificate subject name"""
17
18
def set_subject(self, subject: X509Name):
19
"""Set certificate subject name"""
20
21
def get_issuer(self) -> X509Name:
22
"""Get certificate issuer name"""
23
24
def set_issuer(self, issuer: X509Name):
25
"""Set certificate issuer name"""
26
27
def get_pubkey(self) -> PKey:
28
"""Get certificate public key"""
29
30
def set_pubkey(self, pkey: PKey):
31
"""Set certificate public key"""
32
33
def get_serial_number(self) -> int:
34
"""Get certificate serial number"""
35
36
def set_serial_number(self, serial: int):
37
"""Set certificate serial number"""
38
39
def get_version(self) -> int:
40
"""Get certificate version (0=v1, 2=v3)"""
41
42
def set_version(self, version: int):
43
"""Set certificate version"""
44
45
def get_notBefore(self) -> bytes:
46
"""Get validity start time as ASN.1 time string"""
47
48
def set_notBefore(self, when: bytes):
49
"""Set validity start time"""
50
51
def get_notAfter(self) -> bytes:
52
"""Get validity end time as ASN.1 time string"""
53
54
def set_notAfter(self, when: bytes):
55
"""Set validity end time"""
56
57
def gmtime_adj_notBefore(self, amount: int):
58
"""Adjust validity start time by seconds offset"""
59
60
def gmtime_adj_notAfter(self, amount: int):
61
"""Adjust validity end time by seconds offset"""
62
63
def has_expired(self) -> bool:
64
"""Check if certificate has expired"""
65
66
def sign(self, pkey: PKey, digest: str):
67
"""
68
Sign certificate with private key.
69
70
Parameters:
71
- pkey: Private key for signing
72
- digest: Hash algorithm ('sha256', 'sha1', etc.)
73
"""
74
75
def get_signature_algorithm(self) -> bytes:
76
"""Get signature algorithm name"""
77
78
def digest(self, digest_name: str) -> bytes:
79
"""Calculate certificate digest/fingerprint"""
80
81
def add_extensions(self, extensions):
82
"""Add list of X509Extension objects"""
83
84
def get_extension_count(self) -> int:
85
"""Get number of extensions"""
86
87
def get_extension(self, index: int) -> X509Extension:
88
"""Get extension by index"""
89
90
def to_cryptography(self):
91
"""Convert to cryptography.x509.Certificate"""
92
93
@classmethod
94
def from_cryptography(cls, crypto_cert):
95
"""Create from cryptography.x509.Certificate"""
96
```
97
98
### Distinguished Names
99
100
X.509 distinguished names with attribute access for standard fields like country, organization, and common name.
101
102
```python { .api }
103
class X509Name:
104
def __init__(self, name: X509Name):
105
"""Create copy of existing X509Name"""
106
107
def hash(self) -> int:
108
"""Get MD5 hash of DER representation"""
109
110
def der(self) -> bytes:
111
"""Get DER encoding of name"""
112
113
def get_components(self) -> list:
114
"""
115
Get list of (name, value) tuples for all components.
116
117
Returns:
118
List of (bytes, bytes) tuples
119
"""
120
121
# Direct attribute access for standard fields
122
countryName: str # or C
123
stateOrProvinceName: str # or ST
124
localityName: str # or L
125
organizationName: str # or O
126
organizationalUnitName: str # or OU
127
commonName: str # or CN
128
emailAddress: str
129
```
130
131
### Certificate Loading and Serialization
132
133
Functions for loading certificates from various sources and serializing to different formats.
134
135
```python { .api }
136
def load_certificate(type: int, buffer: bytes) -> X509:
137
"""
138
Load certificate from buffer.
139
140
Parameters:
141
- type: Format type (FILETYPE_PEM, FILETYPE_ASN1)
142
- buffer: Certificate data
143
144
Returns:
145
X509 certificate object
146
"""
147
148
def dump_certificate(type: int, cert: X509) -> bytes:
149
"""
150
Export certificate to buffer.
151
152
Parameters:
153
- type: Output format (FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT)
154
- cert: Certificate to export
155
156
Returns:
157
Certificate data as bytes
158
"""
159
160
# File format constants
161
FILETYPE_PEM: int # PEM encoding (Base64 with headers)
162
FILETYPE_ASN1: int # ASN.1 DER binary encoding
163
FILETYPE_TEXT: int # Human-readable text format
164
```
165
166
### Certificate Extensions (Deprecated)
167
168
X.509 v3 certificate extensions for additional certificate metadata. Note: This class is deprecated - use the cryptography library for new code.
169
170
```python { .api }
171
class X509Extension:
172
def __init__(self, type_name: bytes, critical: bool, value: bytes, subject=None, issuer=None):
173
"""
174
Create certificate extension.
175
176
Parameters:
177
- type_name: Extension type (e.g., b'basicConstraints')
178
- critical: Whether extension is critical
179
- value: Extension value in OpenSSL format
180
- subject: Subject certificate for relative extensions
181
- issuer: Issuer certificate for relative extensions
182
"""
183
184
def get_critical(self) -> bool:
185
"""Check if extension is marked critical"""
186
187
def get_short_name(self) -> bytes:
188
"""Get extension type short name"""
189
190
def get_data(self) -> bytes:
191
"""Get ASN.1 encoded extension data"""
192
```
193
194
### Certificate Signing Requests (Deprecated)
195
196
Certificate signing request handling. Note: This class is deprecated - use the cryptography library for new code.
197
198
```python { .api }
199
class X509Req:
200
def __init__(self):
201
"""Create new certificate signing request"""
202
203
def set_pubkey(self, pkey: PKey):
204
"""Set public key"""
205
206
def get_pubkey(self) -> PKey:
207
"""Get public key"""
208
209
def get_subject(self) -> X509Name:
210
"""Get subject name"""
211
212
def set_version(self, version: int):
213
"""Set version (must be 0)"""
214
215
def get_version(self) -> int:
216
"""Get version"""
217
218
def add_extensions(self, extensions):
219
"""Add extensions list"""
220
221
def get_extensions(self) -> list:
222
"""Get extensions list"""
223
224
def sign(self, pkey: PKey, digest: str):
225
"""Sign CSR with private key"""
226
227
def verify(self, pkey: PKey) -> bool:
228
"""Verify CSR signature"""
229
230
def to_cryptography(self):
231
"""Convert to cryptography CSR"""
232
233
@classmethod
234
def from_cryptography(cls, crypto_req):
235
"""Create from cryptography CSR"""
236
237
def load_certificate_request(type: int, buffer: bytes) -> X509Req:
238
"""Load CSR from buffer"""
239
240
def dump_certificate_request(type: int, req: X509Req) -> bytes:
241
"""Export CSR to buffer"""
242
```
243
244
## Usage Examples
245
246
### Creating a Self-Signed Certificate
247
248
```python
249
from OpenSSL import crypto
250
import datetime
251
252
# Generate key pair
253
key = crypto.PKey()
254
key.generate_key(crypto.TYPE_RSA, 2048)
255
256
# Create certificate
257
cert = crypto.X509()
258
cert.set_version(2) # Version 3
259
cert.set_serial_number(1000)
260
261
# Set validity period
262
cert.gmtime_adj_notBefore(0) # Valid from now
263
cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) # Valid for 1 year
264
265
# Set subject and issuer (same for self-signed)
266
subject = cert.get_subject()
267
subject.countryName = "US"
268
subject.stateOrProvinceName = "California"
269
subject.localityName = "San Francisco"
270
subject.organizationName = "My Organization"
271
subject.commonName = "localhost"
272
273
cert.set_issuer(subject)
274
cert.set_pubkey(key)
275
276
# Sign the certificate
277
cert.sign(key, 'sha256')
278
279
# Save certificate and key
280
cert_data = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
281
key_data = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
282
283
with open('self_signed.crt', 'wb') as f:
284
f.write(cert_data)
285
286
with open('self_signed.key', 'wb') as f:
287
f.write(key_data)
288
```
289
290
### Loading and Examining Certificates
291
292
```python
293
from OpenSSL import crypto
294
295
# Load certificate from file
296
with open('certificate.pem', 'rb') as f:
297
cert_data = f.read()
298
299
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
300
301
# Examine certificate properties
302
print("Subject:", cert.get_subject().commonName)
303
print("Issuer:", cert.get_issuer().commonName)
304
print("Serial Number:", cert.get_serial_number())
305
print("Version:", cert.get_version())
306
print("Signature Algorithm:", cert.get_signature_algorithm().decode())
307
308
# Check validity
309
print("Valid From:", cert.get_notBefore().decode())
310
print("Valid Until:", cert.get_notAfter().decode())
311
print("Has Expired:", cert.has_expired())
312
313
# Get certificate fingerprint
314
fingerprint = cert.digest('sha256')
315
print("SHA256 Fingerprint:", fingerprint.decode())
316
317
# Examine extensions
318
for i in range(cert.get_extension_count()):
319
ext = cert.get_extension(i)
320
print(f"Extension {i}: {ext.get_short_name().decode()}")
321
```
322
323
### Working with Distinguished Names
324
325
```python
326
from OpenSSL import crypto
327
328
# Create new certificate
329
cert = crypto.X509()
330
subject = cert.get_subject()
331
332
# Set subject fields using attribute access
333
subject.countryName = "US"
334
subject.ST = "California" # stateOrProvinceName
335
subject.L = "San Francisco" # localityName
336
subject.O = "My Organization" # organizationName
337
subject.OU = "IT Department" # organizationalUnitName
338
subject.CN = "example.com" # commonName
339
subject.emailAddress = "admin@example.com"
340
341
# Print all components
342
components = subject.get_components()
343
for name, value in components:
344
print(f"{name.decode()}: {value.decode()}")
345
346
# Get hash of distinguished name
347
print("Name Hash:", hex(subject.hash()))
348
```
349
350
### Converting to Cryptography Library
351
352
```python
353
from OpenSSL import crypto
354
import cryptography.x509
355
356
# Load with pyOpenSSL
357
with open('certificate.pem', 'rb') as f:
358
cert_data = f.read()
359
360
pyopenssl_cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
361
362
# Convert to cryptography library
363
crypto_cert = pyopenssl_cert.to_cryptography()
364
365
# Use cryptography library features
366
print("Subject:", crypto_cert.subject.rfc4514_string())
367
print("Extensions:", [ext.oid._name for ext in crypto_cert.extensions])
368
369
# Convert back to pyOpenSSL
370
new_pyopenssl_cert = crypto.X509.from_cryptography(crypto_cert)
371
```