0
# Cryptographic Keys
1
2
Asymmetric key operations supporting RSA, DSA, EC, Ed25519, and Ed448 keys with generation, loading, serialization, and conversion capabilities.
3
4
## Capabilities
5
6
### Private and Public Key Management
7
8
Complete asymmetric key handling with support for multiple key types and cryptographic operations.
9
10
```python { .api }
11
class PKey:
12
def __init__(self):
13
"""Create new empty key object"""
14
15
def generate_key(self, type: int, bits: int) -> None:
16
"""
17
Generate key pair.
18
19
Parameters:
20
- type: Key type (TYPE_RSA, TYPE_DSA)
21
- bits: Key size in bits (1024, 2048, 4096, etc.)
22
"""
23
24
def check(self) -> bool:
25
"""
26
Verify RSA private key consistency.
27
28
Returns:
29
True if key is valid, raises exception if invalid
30
"""
31
32
def type(self) -> int:
33
"""
34
Get key type.
35
36
Returns:
37
Key type constant (TYPE_RSA, TYPE_DSA, etc.)
38
"""
39
40
def bits(self) -> int:
41
"""
42
Get key size in bits.
43
44
Returns:
45
Key size (1024, 2048, 4096, etc.)
46
"""
47
48
def to_cryptography_key(self):
49
"""
50
Convert to cryptography library key object.
51
52
Returns:
53
cryptography private or public key object
54
"""
55
56
@classmethod
57
def from_cryptography_key(cls, crypto_key):
58
"""
59
Create PKey from cryptography library key.
60
61
Parameters:
62
- crypto_key: cryptography private or public key
63
64
Returns:
65
New PKey object
66
"""
67
```
68
69
### Key Loading and Serialization
70
71
Functions for loading keys from various sources and serializing to different formats with optional encryption.
72
73
```python { .api }
74
def load_privatekey(type: int, buffer: str | bytes, passphrase=None) -> PKey:
75
"""
76
Load private key from buffer.
77
78
Parameters:
79
- type: Format type (FILETYPE_PEM, FILETYPE_ASN1)
80
- buffer: Key data as string or bytes
81
- passphrase: Optional passphrase (str, bytes, or callable)
82
83
Returns:
84
PKey object containing private key
85
"""
86
87
def dump_privatekey(type: int, pkey: PKey, cipher=None, passphrase=None) -> bytes:
88
"""
89
Export private key to buffer.
90
91
Parameters:
92
- type: Output format (FILETYPE_PEM, FILETYPE_ASN1)
93
- pkey: Private key to export
94
- cipher: Optional encryption cipher (e.g., 'aes256')
95
- passphrase: Optional passphrase for encryption
96
97
Returns:
98
Private key data as bytes
99
"""
100
101
def load_publickey(type: int, buffer: str | bytes) -> PKey:
102
"""
103
Load public key from buffer.
104
105
Parameters:
106
- type: Format type (FILETYPE_PEM, FILETYPE_ASN1)
107
- buffer: Key data as string or bytes
108
109
Returns:
110
PKey object containing public key
111
"""
112
113
def dump_publickey(type: int, pkey: PKey) -> bytes:
114
"""
115
Export public key to buffer.
116
117
Parameters:
118
- type: Output format (FILETYPE_PEM, FILETYPE_ASN1)
119
- pkey: Public key to export
120
121
Returns:
122
Public key data as bytes
123
"""
124
```
125
126
### Key Type Constants
127
128
Constants identifying different asymmetric key algorithms.
129
130
```python { .api }
131
TYPE_RSA: int # RSA key type
132
TYPE_DSA: int # DSA key type
133
```
134
135
## Usage Examples
136
137
### Generating RSA Key Pairs
138
139
```python
140
from OpenSSL import crypto
141
142
# Generate 2048-bit RSA key pair
143
key = crypto.PKey()
144
key.generate_key(crypto.TYPE_RSA, 2048)
145
146
print(f"Generated {key.bits()}-bit RSA key")
147
print(f"Key type: {key.type()}")
148
149
# Verify key consistency
150
if key.check():
151
print("Key is valid")
152
153
# Save private key with encryption
154
private_key_data = crypto.dump_privatekey(
155
crypto.FILETYPE_PEM,
156
key,
157
cipher='aes256',
158
passphrase=b'secretpassword'
159
)
160
161
with open('private_key.pem', 'wb') as f:
162
f.write(private_key_data)
163
164
# Save public key
165
public_key_data = crypto.dump_publickey(crypto.FILETYPE_PEM, key)
166
167
with open('public_key.pem', 'wb') as f:
168
f.write(public_key_data)
169
```
170
171
### Loading Encrypted Private Keys
172
173
```python
174
from OpenSSL import crypto
175
176
# Load encrypted private key with passphrase
177
with open('private_key.pem', 'rb') as f:
178
key_data = f.read()
179
180
# Method 1: Passphrase as string
181
private_key = crypto.load_privatekey(
182
crypto.FILETYPE_PEM,
183
key_data,
184
passphrase='secretpassword'
185
)
186
187
# Method 2: Passphrase callback function
188
def get_passphrase():
189
return input("Enter passphrase: ").encode()
190
191
private_key = crypto.load_privatekey(
192
crypto.FILETYPE_PEM,
193
key_data,
194
passphrase=get_passphrase
195
)
196
197
print(f"Loaded {private_key.bits()}-bit key")
198
```
199
200
### Working with DSA Keys
201
202
```python
203
from OpenSSL import crypto
204
205
# Generate DSA key pair
206
dsa_key = crypto.PKey()
207
dsa_key.generate_key(crypto.TYPE_DSA, 2048)
208
209
print(f"Generated {dsa_key.bits()}-bit DSA key")
210
211
# DSA keys cannot use check() method (RSA-specific)
212
try:
213
dsa_key.check()
214
except crypto.Error as e:
215
print("DSA key check not supported")
216
217
# Export DSA key
218
dsa_private = crypto.dump_privatekey(crypto.FILETYPE_PEM, dsa_key)
219
dsa_public = crypto.dump_publickey(crypto.FILETYPE_PEM, dsa_key)
220
```
221
222
### Converting Between pyOpenSSL and Cryptography
223
224
```python
225
from OpenSSL import crypto
226
from cryptography.hazmat.primitives import serialization
227
from cryptography.hazmat.primitives.asymmetric import rsa
228
229
# Generate key with cryptography library
230
crypto_private_key = rsa.generate_private_key(
231
public_exponent=65537,
232
key_size=2048
233
)
234
235
# Convert to pyOpenSSL
236
pyopenssl_key = crypto.PKey.from_cryptography_key(crypto_private_key)
237
238
print(f"Converted key: {pyopenssl_key.bits()} bits")
239
240
# Convert back to cryptography
241
converted_back = pyopenssl_key.to_cryptography_key()
242
243
# Use cryptography library features
244
pem_data = converted_back.private_bytes(
245
encoding=serialization.Encoding.PEM,
246
format=serialization.PrivateFormat.PKCS8,
247
encryption_algorithm=serialization.NoEncryption()
248
)
249
250
print("Key converted successfully between libraries")
251
```
252
253
### Loading Public Keys from Certificates
254
255
```python
256
from OpenSSL import crypto
257
258
# Load certificate
259
with open('certificate.pem', 'rb') as f:
260
cert_data = f.read()
261
262
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
263
264
# Extract public key from certificate
265
public_key = cert.get_pubkey()
266
267
print(f"Certificate public key: {public_key.bits()} bits")
268
print(f"Key type: {public_key.type()}")
269
270
# Export public key
271
public_key_pem = crypto.dump_publickey(crypto.FILETYPE_PEM, public_key)
272
273
with open('extracted_public_key.pem', 'wb') as f:
274
f.write(public_key_pem)
275
```
276
277
### Key Format Conversion
278
279
```python
280
from OpenSSL import crypto
281
282
# Load PEM key
283
with open('key.pem', 'rb') as f:
284
pem_data = f.read()
285
286
key = crypto.load_privatekey(crypto.FILETYPE_PEM, pem_data)
287
288
# Convert to DER format
289
der_data = crypto.dump_privatekey(crypto.FILETYPE_ASN1, key)
290
291
with open('key.der', 'wb') as f:
292
f.write(der_data)
293
294
# Load DER key back
295
with open('key.der', 'rb') as f:
296
der_data = f.read()
297
298
key_from_der = crypto.load_privatekey(crypto.FILETYPE_ASN1, der_data)
299
300
print("Key conversion successful")
301
print(f"Key size: {key_from_der.bits()} bits")
302
```
303
304
### Using Keys for Certificate Signing
305
306
```python
307
from OpenSSL import crypto
308
309
# Generate CA key
310
ca_key = crypto.PKey()
311
ca_key.generate_key(crypto.TYPE_RSA, 4096)
312
313
# Create CA certificate
314
ca_cert = crypto.X509()
315
ca_cert.set_version(2)
316
ca_cert.set_serial_number(1)
317
318
# Set CA subject
319
ca_subject = ca_cert.get_subject()
320
ca_subject.CN = "My CA"
321
ca_subject.O = "My Organization"
322
323
ca_cert.set_issuer(ca_subject)
324
ca_cert.set_pubkey(ca_key)
325
326
# Set validity
327
ca_cert.gmtime_adj_notBefore(0)
328
ca_cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) # 10 years
329
330
# Self-sign CA certificate
331
ca_cert.sign(ca_key, 'sha256')
332
333
# Generate server key
334
server_key = crypto.PKey()
335
server_key.generate_key(crypto.TYPE_RSA, 2048)
336
337
# Create server certificate
338
server_cert = crypto.X509()
339
server_cert.set_version(2)
340
server_cert.set_serial_number(2)
341
342
# Set server subject
343
server_subject = server_cert.get_subject()
344
server_subject.CN = "example.com"
345
346
server_cert.set_issuer(ca_subject) # Issued by CA
347
server_cert.set_pubkey(server_key)
348
349
# Set validity
350
server_cert.gmtime_adj_notBefore(0)
351
server_cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) # 1 year
352
353
# Sign server certificate with CA key
354
server_cert.sign(ca_key, 'sha256')
355
356
print("Certificate chain created successfully")
357
```