11import base64
2- import hashlib
32import logging
43
5- from cryptography import x509
64from cryptography .hazmat .backends import default_backend
75from cryptography .hazmat .primitives import serialization
86from cryptography .hazmat .primitives .asymmetric import rsa
97
8+ from . import JWK
9+ from .asym import AsymmetricKey
10+ from .x509 import der_cert
11+ from .x509 import import_private_key_from_pem_file
12+ from .x509 import import_public_key_from_pem_data
13+ from .x509 import import_public_key_from_pem_file
14+ from .x509 import x5t_calculation
1015from ..exception import DeSerializationNotPossible
1116from ..exception import JWKESTException
1217from ..exception import SerializationNotPossible
1318from ..exception import UnsupportedKeyType
1419from ..utils import as_unicode
15- from ..utils import b64e
1620from ..utils import deser
1721from ..utils import long_to_base64
18- from . import JWK
19- from .asym import AsymmetricKey
2022
2123logger = logging .getLogger (__name__ )
2224
@@ -67,11 +69,11 @@ def import_private_rsa_key_from_file(filename, passphrase=None):
6769 :return: A
6870 cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance
6971 """
70- with open (filename , "rb" ) as key_file :
71- private_key = serialization . load_pem_private_key (
72- key_file . read (), password = passphrase , backend = default_backend ()
73- )
74- return private_key
72+ private_key = import_private_key_from_pem_file (filename , passphrase )
73+ if isinstance ( private_key , rsa . RSAPrivateKey ):
74+ return private_key
75+ else :
76+ return ValueError ( 'Not a RSA key' )
7577
7678
7779def import_public_rsa_key_from_file (filename ):
@@ -80,14 +82,13 @@ def import_public_rsa_key_from_file(filename):
8082
8183 :param filename: The name of the file
8284 :param passphrase: A pass phrase to use to unpack the PEM file.
83- :return: A
84- cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance
85+ :return: A cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance
8586 """
86- with open (filename , "rb" ) as key_file :
87- public_key = serialization . load_pem_public_key (
88- key_file . read (), backend = default_backend ()
89- )
90- return public_key
87+ public_key = import_public_key_from_pem_file (filename )
88+ if isinstance ( public_key , rsa . RSAPublicKey ):
89+ return public_key
90+ else :
91+ return ValueError ( 'Not a RSA key' )
9192
9293
9394def import_rsa_key (pem_data ):
@@ -97,12 +98,11 @@ def import_rsa_key(pem_data):
9798 :param pem_data: RSA key encoded in standard form
9899 :return: rsa.RSAPublicKey instance
99100 """
100- if not pem_data .startswith (PREFIX ):
101- pem_data = bytes ("{}\n {}\n {}" .format (PREFIX , pem_data , POSTFIX ), "utf-8" )
101+ public_key = import_public_key_from_pem_data (pem_data )
102+ if isinstance (public_key , rsa .RSAPublicKey ):
103+ return public_key
102104 else :
103- pem_data = bytes (pem_data , "utf-8" )
104- cert = x509 .load_pem_x509_certificate (pem_data , default_backend ())
105- return cert .public_key ()
105+ return ValueError ('Not a RSA key' )
106106
107107
108108def import_rsa_key_from_cert_file (pem_file ):
@@ -182,46 +182,6 @@ def rsa_construct_private(numbers):
182182 return rprivn .private_key (default_backend ())
183183
184184
185- def der_cert (der_data ):
186- """
187- Load a DER encoded certificate
188-
189- :param der_data: DER-encoded certificate
190- :return: A cryptography.x509.certificate instance
191- """
192- if isinstance (der_data , str ):
193- der_data = bytes (der_data , "utf-8" )
194- return x509 .load_der_x509_certificate (der_data , default_backend ())
195-
196-
197- def load_x509_cert (url , httpc , spec2key , ** get_args ):
198- """
199- Get and transform a X509 cert into a key.
200-
201- :param url: Where the X509 cert can be found
202- :param httpc: HTTP client to use for fetching
203- :param spec2key: A dictionary over keys already seen
204- :param get_args: Extra key word arguments to the HTTP GET request
205- :return: List of 2-tuples (keytype, key)
206- """
207- try :
208- r = httpc ("GET" , url , allow_redirects = True , ** get_args )
209- if r .status_code == 200 :
210- cert = str (r .text )
211- try :
212- public_key = spec2key [cert ] # If I've already seen it
213- except KeyError :
214- public_key = import_rsa_key (cert )
215- spec2key [cert ] = public_key
216- if isinstance (public_key , rsa .RSAPublicKey ):
217- return {"rsa" : public_key }
218- else :
219- raise Exception ("HTTP Get error: %s" % r .status_code )
220- except Exception as err : # not a RSA key
221- logger .warning ("Can't load key: %s" % err )
222- return []
223-
224-
225185def cmp_public_numbers (pn1 , pn2 ):
226186 """
227187 Compare 2 sets of public numbers. These is a way to compare
@@ -255,22 +215,6 @@ def cmp_private_numbers(pn1, pn2):
255215 return True
256216
257217
258- def x5t_calculation (cert ):
259- """
260- base64url-encoded SHA-1 thumbprint (a.k.a. digest) of the DER
261- encoding of an X.509 certificate.
262-
263- :param cert: DER encoded X.509 certificate
264- :return: x5t value
265- """
266- if isinstance (cert , str ):
267- der_cert = base64 .b64decode (cert .encode ("ascii" ))
268- else :
269- der_cert = base64 .b64decode (cert )
270-
271- return b64e (hashlib .sha1 (der_cert ).digest ())
272-
273-
274218class RSAKey (AsymmetricKey ):
275219 """
276220 JSON Web key representation of a RSA key
@@ -303,24 +247,24 @@ class RSAKey(AsymmetricKey):
303247 required = ["kty" , "n" , "e" ]
304248
305249 def __init__ (
306- self ,
307- kty = "RSA" ,
308- alg = "" ,
309- use = "" ,
310- kid = "" ,
311- x5c = None ,
312- x5t = "" ,
313- x5u = "" ,
314- n = "" ,
315- e = "" ,
316- d = "" ,
317- p = "" ,
318- q = "" ,
319- dp = "" ,
320- dq = "" ,
321- di = "" ,
322- qi = "" ,
323- ** kwargs
250+ self ,
251+ kty = "RSA" ,
252+ alg = "" ,
253+ use = "" ,
254+ kid = "" ,
255+ x5c = None ,
256+ x5t = "" ,
257+ x5u = "" ,
258+ n = "" ,
259+ e = "" ,
260+ d = "" ,
261+ p = "" ,
262+ q = "" ,
263+ dp = "" ,
264+ dq = "" ,
265+ di = "" ,
266+ qi = "" ,
267+ ** kwargs
324268 ):
325269 AsymmetricKey .__init__ (self , kty , alg , use , kid , x5c , x5t , x5u , ** kwargs )
326270 self .n = n
0 commit comments