0
# Key Management
1
2
RSA key pair generation and key object management including loading/saving keys in various formats and key manipulation operations.
3
4
## Capabilities
5
6
### Key Generation
7
8
Generate RSA key pairs with customizable parameters for security and performance requirements.
9
10
```python { .api }
11
def newkeys(nbits: int, accurate: bool = True, poolsize: int = 1, exponent: int = 65537) -> Tuple[PublicKey, PrivateKey]:
12
"""
13
Generates public and private keys, and returns them as (pub, priv).
14
15
Parameters:
16
- nbits: int - the number of bits required to store n = p*q
17
- accurate: bool - when True, n will have exactly the number of bits specified (slower)
18
- poolsize: int - number of processes to use for prime generation (>=1)
19
- exponent: int - the exponent for the key (default 65537)
20
21
Returns:
22
Tuple[PublicKey, PrivateKey] - Generated key pair
23
"""
24
```
25
26
**Usage Example:**
27
28
```python
29
import rsa
30
31
# Generate 2048-bit key pair (recommended for security)
32
(public_key, private_key) = rsa.newkeys(2048)
33
34
# Generate 1024-bit key pair with parallel processing
35
(pub, priv) = rsa.newkeys(1024, poolsize=4)
36
37
# Generate key pair with custom exponent
38
(pub, priv) = rsa.newkeys(2048, exponent=3)
39
```
40
41
### PublicKey Class
42
43
Represents an RSA public key with methods for loading, saving, and manipulating public key data.
44
45
```python { .api }
46
class PublicKey:
47
def __init__(self, n: int, e: int):
48
"""
49
Create a PublicKey instance.
50
51
Parameters:
52
- n: int - the RSA modulus
53
- e: int - the public exponent
54
"""
55
56
@classmethod
57
def load_pkcs1(cls, keyfile: bytes, format: str = "PEM") -> 'PublicKey':
58
"""
59
Load a public key from PKCS#1 PEM or DER format.
60
61
Parameters:
62
- keyfile: bytes - encoded public key data
63
- format: str - key format, either "PEM" (default) or "DER"
64
65
Returns:
66
PublicKey - loaded public key instance
67
"""
68
69
@classmethod
70
def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> 'PublicKey':
71
"""
72
Load a public key from OpenSSL PEM format.
73
74
Parameters:
75
- keyfile: bytes - OpenSSL PEM-encoded public key data
76
77
Returns:
78
PublicKey - loaded public key instance
79
"""
80
81
@classmethod
82
def load_pkcs1_openssl_der(cls, keyfile: bytes) -> 'PublicKey':
83
"""
84
Load a public key from OpenSSL DER format.
85
86
Parameters:
87
- keyfile: bytes - OpenSSL DER-encoded public key data
88
89
Returns:
90
PublicKey - loaded public key instance
91
"""
92
93
def save_pkcs1_pem(self) -> bytes:
94
"""
95
Save the public key in PKCS#1 PEM format.
96
97
Returns:
98
bytes - PEM-encoded public key data
99
"""
100
101
def save_pkcs1_der(self) -> bytes:
102
"""
103
Save the public key in PKCS#1 DER format.
104
105
Returns:
106
bytes - DER-encoded public key data
107
"""
108
109
def save_pkcs1_openssl_pem(self) -> bytes:
110
"""
111
Save the public key in OpenSSL PEM format.
112
113
Returns:
114
bytes - OpenSSL PEM-encoded public key data
115
"""
116
```
117
118
**Attributes:**
119
120
```python { .api }
121
class PublicKey:
122
n: int # RSA modulus (product of two large primes)
123
e: int # Public exponent (typically 65537)
124
```
125
126
**Usage Example:**
127
128
```python
129
import rsa
130
131
# Create from integers
132
public_key = rsa.PublicKey(12345678901234567890, 65537)
133
134
# Load from PEM file
135
with open('public_key.pem', 'rb') as f:
136
public_key = rsa.PublicKey.load_pkcs1_pem(f.read())
137
138
# Save as PEM
139
pem_data = public_key.save_pkcs1_pem()
140
with open('public_key.pem', 'wb') as f:
141
f.write(pem_data)
142
143
# Save as DER
144
der_data = public_key.save_pkcs1_der()
145
```
146
147
### PrivateKey Class
148
149
Represents an RSA private key with methods for loading, saving, and cryptographic operations including blinded operations for timing attack protection.
150
151
```python { .api }
152
class PrivateKey:
153
def __init__(self, n: int, e: int, d: int, p: int, q: int):
154
"""
155
Create a PrivateKey instance.
156
157
Parameters:
158
- n: int - the RSA modulus
159
- e: int - the public exponent
160
- d: int - the private exponent
161
- p: int - first prime factor of n
162
- q: int - second prime factor of n
163
"""
164
165
@classmethod
166
def load_pkcs1(cls, keyfile: bytes, format: str = "PEM") -> 'PrivateKey':
167
"""
168
Load a private key from PKCS#1 PEM or DER format.
169
170
Parameters:
171
- keyfile: bytes - encoded private key data
172
- format: str - key format, either "PEM" (default) or "DER"
173
174
Returns:
175
PrivateKey - loaded private key instance
176
"""
177
178
def save_pkcs1_pem(self) -> bytes:
179
"""
180
Save the private key in PKCS#1 PEM format.
181
182
Returns:
183
bytes - PEM-encoded private key data
184
"""
185
186
def save_pkcs1_der(self) -> bytes:
187
"""
188
Save the private key in PKCS#1 DER format.
189
190
Returns:
191
bytes - DER-encoded private key data
192
"""
193
194
def blinded_decrypt(self, encrypted: int) -> int:
195
"""
196
Decrypt an integer using blinding to prevent timing attacks.
197
198
Parameters:
199
- encrypted: int - encrypted integer value
200
201
Returns:
202
int - decrypted integer value
203
"""
204
205
def blinded_encrypt(self, message: int) -> int:
206
"""
207
Encrypt an integer using blinding.
208
209
Parameters:
210
- message: int - message integer value
211
212
Returns:
213
int - encrypted integer value
214
"""
215
```
216
217
**Attributes:**
218
219
```python { .api }
220
class PrivateKey:
221
n: int # RSA modulus (same as in public key)
222
e: int # Public exponent (same as in public key)
223
d: int # Private exponent
224
p: int # First prime factor of n
225
q: int # Second prime factor of n
226
exp1: int # d mod (p-1), for Chinese Remainder Theorem
227
exp2: int # d mod (q-1), for Chinese Remainder Theorem
228
coef: int # Inverse of q mod p, for Chinese Remainder Theorem
229
```
230
231
**Usage Example:**
232
233
```python
234
import rsa
235
236
# Load from PEM file
237
with open('private_key.pem', 'rb') as f:
238
private_key = rsa.PrivateKey.load_pkcs1_pem(f.read())
239
240
# Save as PEM
241
pem_data = private_key.save_pkcs1_pem()
242
with open('private_key.pem', 'wb') as f:
243
f.write(pem_data)
244
245
# Access key components
246
print(f"Modulus: {private_key.n}")
247
print(f"Public exponent: {private_key.e}")
248
print(f"Private exponent: {private_key.d}")
249
```
250
251
252
## Error Handling
253
254
Key management operations may raise the following exceptions:
255
256
- **ValueError** - Invalid key parameters or malformed key data
257
- **ImportError** - Missing pyasn1 dependency for PEM/DER operations
258
- **TypeError** - Incorrect parameter types
259
260
## Security Considerations
261
262
- **Key Size**: Use at least 2048 bits for security (4096 bits recommended for long-term use)
263
- **Random Number Generation**: The library uses the system's secure random number generator
264
- **Timing Attacks**: Private key operations use blinding to prevent timing-based attacks
265
- **Key Storage**: Store private keys securely and never transmit them over insecure channels