-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathrsa.py
498 lines (413 loc) · 14.8 KB
/
rsa.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import base64
import logging
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptojwt.exception import KeyNotFound
from ..exception import DeSerializationNotPossible
from ..exception import JWKESTException
from ..exception import SerializationNotPossible
from ..exception import UnsupportedKeyType
from ..utils import as_unicode
from ..utils import deser
from ..utils import long_to_base64
from . import JWK
from .asym import AsymmetricKey
from .x509 import der_cert
from .x509 import import_private_key_from_pem_file
from .x509 import import_public_key_from_pem_data
from .x509 import import_public_key_from_pem_file
from .x509 import x5t_calculation
logger = logging.getLogger(__name__)
PREFIX = "-----BEGIN CERTIFICATE-----"
POSTFIX = "-----END CERTIFICATE-----"
def generate_and_store_rsa_key(key_size=2048, filename="rsa.key", passphrase=""):
"""
Generate a private RSA key and store a PEM representation of it in a
file.
:param key_size: The size of the key, default 2048 bytes.
:param filename: The name of the file to which the key should be written
:param passphrase: If the PEM representation should be protected with a
pass phrase.
:return: A
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance
"""
private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size)
with open(filename, "wb") as keyfile:
if passphrase:
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
)
else:
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
keyfile.write(pem)
keyfile.close()
return private_key
def import_private_rsa_key_from_file(filename, passphrase=None):
"""
Read a private RSA key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file.
:return: A
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance
"""
private_key = import_private_key_from_pem_file(filename, passphrase)
if isinstance(private_key, rsa.RSAPrivateKey):
return private_key
else:
return ValueError("Not a RSA key")
def import_public_rsa_key_from_file(filename):
"""
Read a public RSA key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file.
:return: A cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance
"""
public_key = import_public_key_from_pem_file(filename)
if isinstance(public_key, rsa.RSAPublicKey):
return public_key
else:
return ValueError("Not a RSA key")
def import_rsa_key(pem_data):
"""
Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance
"""
public_key = import_public_key_from_pem_data(pem_data)
if isinstance(public_key, rsa.RSAPublicKey):
return public_key
else:
return ValueError("Not a RSA key")
def import_rsa_key_from_cert_file(pem_file):
with open(pem_file, "r") as cert_file:
return import_rsa_key(cert_file.read())
def rsa_eq(key1, key2):
"""
Only works for RSAPublic Keys
:param key1:
:param key2:
:return:
"""
pn1 = key1.public_numbers()
pn2 = key2.public_numbers()
# Check if two RSA keys are in fact the same
if pn1 == pn2:
return True
else:
return False
def x509_rsa_load(txt):
"""So I get the same output format as loads produces
:param txt:
:return:
"""
pub_key = import_rsa_key(txt)
if isinstance(pub_key, rsa.RSAPublicKey):
return [("rsa", pub_key)]
def rsa_construct_public(numbers):
rpn = rsa.RSAPublicNumbers(**numbers)
return rpn.public_key()
def rsa_construct_private(numbers):
args = dict([(k, v) for k, v in numbers.items() if k in ["n", "e", "d"]])
cnum = {"d": numbers["d"]}
if "p" not in numbers and "q" not in numbers:
(p, q) = rsa.rsa_recover_prime_factors(**args)
cnum["p"] = p
cnum["q"] = q
else:
cnum["p"] = numbers["p"]
cnum["q"] = numbers["q"]
try:
cnum["dmp1"] = numbers["dp"]
except KeyError:
cnum["dmp1"] = rsa.rsa_crt_dmp1(cnum["d"], cnum["p"])
else:
if not numbers["dp"]:
cnum["dmp1"] = rsa.rsa_crt_dmp1(cnum["d"], cnum["p"])
try:
cnum["dmq1"] = numbers["dq"]
except KeyError:
cnum["dmq1"] = rsa.rsa_crt_dmq1(cnum["d"], cnum["q"])
else:
if not numbers["dq"]:
cnum["dmq1"] = rsa.rsa_crt_dmq1(cnum["d"], cnum["q"])
try:
cnum["iqmp"] = numbers["di"]
except KeyError:
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["q"])
else:
if not numbers["di"]:
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["q"])
rpubn = rsa.RSAPublicNumbers(e=numbers["e"], n=numbers["n"])
rprivn = rsa.RSAPrivateNumbers(public_numbers=rpubn, **cnum)
return rprivn.private_key()
def cmp_public_numbers(pn1, pn2):
"""
Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False.
"""
if pn1.n == pn2.n:
if pn1.e == pn2.e:
return True
return False
def cmp_private_numbers(pn1, pn2):
"""
Compare 2 sets of private numbers. This is for comparing 2
private RSA keys.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False.
"""
if not cmp_public_numbers(pn1.public_numbers, pn2.public_numbers):
return False
for param in ["d", "p", "q"]:
if getattr(pn1, param) != getattr(pn2, param):
return False
return True
class RSAKey(AsymmetricKey):
"""
JSON Web key representation of a RSA key
The name of parameters used in this class are the same as
specified in the RFC 7517.
According to RFC7517 the JWK representation of a RSA (public key) can be
something like this:
{
"kty": "RSA",
"use": "sig",
"kid": "1b94c",
"n": "vrjOfz9Ccdgx5nQudyhdoR17V...",
"e": "AQAB",
}
Parameters according to https://tools.ietf.org/html/rfc7518#section-6.3
"""
members = JWK.members[:]
# These are the RSA key specific parameters, they are always supposed to
# be strings or bytes
members.extend(["n", "e", "d", "p", "q"])
# The parameters that represent long ints in the key instances
longs = ["n", "e", "d", "p", "q", "dp", "dq", "di", "qi"]
public_members = JWK.public_members[:]
# the public members of the key
public_members.extend(["n", "e"])
required = ["kty", "n", "e"]
def __init__(
self,
kty="RSA",
alg="",
use="",
kid="",
x5c=None,
x5t="",
x5u="",
n="",
e="",
d="",
p="",
q="",
dp="",
dq="",
di="",
qi="",
**kwargs
):
AsymmetricKey.__init__(self, kty, alg, use, kid, x5c, x5t, x5u, **kwargs)
self.n = n
self.e = e
self.d = d
self.p = p
self.q = q
self.dp = dp
self.dq = dq
self.di = di
self.qi = qi
has_public_key_parts = len(self.n) > 0 and len(self.e)
has_x509_cert_chain = len(self.x5c) > 0
if self.priv_key:
self._serialize(self.priv_key)
self.pub_key = self.priv_key.public_key()
elif self.pub_key:
self._serialize(self.pub_key)
elif has_public_key_parts:
self.deserialize()
elif has_x509_cert_chain:
self.deserialize()
elif not self.n and not self.e:
pass
else: # one of n or e but not both
raise JWKESTException("Missing required parameter")
def deserialize(self):
"""
Based on a text based representation of an RSA key this method
instantiates a
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance
"""
# first look for the public parts of a RSA key
if self.n and self.e:
try:
numbers = {}
# loop over all the parameters that define a RSA key
for param in self.longs:
item = getattr(self, param)
if not item:
continue
else:
try:
val = int(deser(item))
except Exception:
raise
else:
numbers[param] = val
if "d" in numbers:
self.priv_key = rsa_construct_private(numbers)
self.pub_key = self.priv_key.public_key()
else:
self.pub_key = rsa_construct_public(numbers)
except ValueError as err:
raise DeSerializationNotPossible("%s" % err)
if self.x5c:
_cert_chain = []
for der_data in self.x5c:
_cert_chain.append(der_cert(base64.b64decode(der_data)))
if self.x5t: # verify the cert thumbprint
if isinstance(self.x5t, bytes):
_x5t = self.x5t
else:
_x5t = self.x5t.encode("ascii")
if _x5t != x5t_calculation(self.x5c[0]):
raise DeSerializationNotPossible(
"The thumbprint 'x5t' does not match the certificate."
)
if self.pub_key:
if not rsa_eq(self.pub_key, _cert_chain[0].public_key()):
raise ValueError("key described by components and key in x5c not equal")
else:
self.pub_key = _cert_chain[0].public_key()
self._serialize(self.pub_key)
if len(self.x5c) > 1: # verify chain
pass
if not self.priv_key and not self.pub_key:
raise DeSerializationNotPossible()
def serialize(self, private=False):
"""
Given a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance construct the JWK representation.
:param private: Should I do the private part or not
:return: A JWK as a dictionary
"""
if not self.priv_key and not self.pub_key:
raise SerializationNotPossible()
res = self.common()
public_longs = list(set(self.public_members) & set(self.longs))
for param in public_longs:
item = getattr(self, param)
if item:
res[param] = item
if private:
for param in self.longs:
if not private and param in ["d", "p", "q", "dp", "dq", "di", "qi"]:
continue
item = getattr(self, param)
if item:
res[param] = item
if self.x5c:
res["x5c"] = [as_unicode(x) for x in self.x5c]
return res
def _serialize(self, key):
if isinstance(key, rsa.RSAPrivateKey):
pn = key.private_numbers()
self.n = long_to_base64(pn.public_numbers.n)
self.e = long_to_base64(pn.public_numbers.e)
self.d = long_to_base64(pn.d)
self.p = long_to_base64(pn.p)
self.q = long_to_base64(pn.q)
elif isinstance(key, rsa.RSAPublicKey):
pn = key.public_numbers()
self.n = long_to_base64(pn.n)
self.e = long_to_base64(pn.e)
else:
raise UnsupportedKeyType()
def load_key(self, key):
"""
Load a RSA key. Try to serialize the key before binding it to this
instance.
:param key: An RSA key instance
"""
self._serialize(key)
if isinstance(key, rsa.RSAPrivateKey):
self.priv_key = key
self.pub_key = key.public_key()
else:
self.pub_key = key
return self
def load(self, filename):
"""
Load a RSA key from a PEM encoded file. Once we have the key do a serialization.
:param filename: File name
"""
return self.load_key(import_private_rsa_key_from_file(filename))
def __eq__(self, other):
"""
Verify that this other key is the same as myself.
:param other: The other key
:return: True if equal otherwise False
"""
if not isinstance(other, RSAKey):
return False
if not self.pub_key:
self.deserialize()
if not other.pub_key:
other.deserialize()
if self.use and other.use:
if self.use != other.use:
return False
if self.kid:
if other.kid:
if self.kid != other.kid:
return False
else:
return False
else:
if other.kid:
return False
try:
pn1 = self.priv_key.private_numbers()
pn2 = other.priv_key.private_numbers()
except Exception:
try:
return cmp_public_numbers(
self.pub_key.public_numbers(), other.pub_key.public_numbers()
)
except Exception:
return False
else:
return cmp_private_numbers(pn1, pn2)
def key_len(self):
if self.priv_key:
return self.priv_key.key_size
elif self.pub_key:
return self.pub_key.key_size
else:
raise KeyNotFound
def new_rsa_key(key_size=2048, kid="", public_exponent=65537, **kwargs):
"""
Creates a new RSA key pair and wraps it in a
:py:class:`cryptojwt.jwk.rsa.RSAKey` instance
:param key_size: The size of the key
:param kid: The key ID
:param public_exponent: The value of the public exponent.
:return: A :py:class:`cryptojwt.jwk.rsa.RSAKey` instance
"""
_key = rsa.generate_private_key(public_exponent=public_exponent, key_size=key_size)
_rk = RSAKey(priv_key=_key, kid=kid, **kwargs)
if not _rk.kid:
_rk.add_kid()
return _rk