Skip to content

Commit 930dd5f

Browse files
authored
Merge pull request #61 from IdentityPython/rsa_import
Work around bad RSAKey import
2 parents 0569939 + dbbe46d commit 930dd5f

22 files changed

+131
-43
lines changed

src/cryptojwt/jwe/__init__.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,14 @@
2222
"ECDH-ES+A192KW",
2323
"ECDH-ES+A256KW",
2424
],
25-
"enc": ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512", "A128GCM", "A192GCM", "A256GCM",],
25+
"enc": [
26+
"A128CBC-HS256",
27+
"A192CBC-HS384",
28+
"A256CBC-HS512",
29+
"A128GCM",
30+
"A192GCM",
31+
"A256GCM",
32+
],
2633
}
2734

2835

src/cryptojwt/jwe/aes.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@
1818

1919

2020
class AES_CBCEncrypter(Encrypter):
21-
"""
22-
"""
21+
""""""
2322

2423
def __init__(self, key_len=32, key=None, msg_padding="PKCS7"):
2524
Encrypter.__init__(self)

src/cryptojwt/jwe/jwe_ec.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,12 @@ def dec_setup(self, token, key=None, **kwargs):
157157
raise Exception("Unknown key length for algorithm")
158158

159159
self.cek = ecdh_derive_key(
160-
key, epubkey.pub_key, apu, apv, str(self.headers["enc"]).encode(), dk_len,
160+
key,
161+
epubkey.pub_key,
162+
apu,
163+
apv,
164+
str(self.headers["enc"]).encode(),
165+
dk_len,
161166
)
162167
elif self.headers["alg"] in [
163168
"ECDH-ES+A128KW",

src/cryptojwt/jwe/jwe_rsa.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def encrypt(self, key, iv="", cek="", **kwargs):
8585
return jwe.pack(parts=[jwe_enc_key, iv, ctxt, tag])
8686

8787
def decrypt(self, token, key, cek=None):
88-
""" Decrypts a JWT
88+
"""Decrypts a JWT
8989
9090
:param token: The JWT
9191
:param key: A key to use for decrypting

src/cryptojwt/jwe/jwekey.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def alg2keytype(self, alg):
3838
return alg2keytype(alg)
3939

4040
def enc_setup(self, enc_alg, msg, auth_data=b"", key=None, iv=""):
41-
""" Encrypt JWE content.
41+
"""Encrypt JWE content.
4242
4343
:param enc_alg: The JWE "enc" value specifying the encryption algorithm
4444
:param msg: The plain text message
@@ -62,7 +62,7 @@ def enc_setup(self, enc_alg, msg, auth_data=b"", key=None, iv=""):
6262

6363
@staticmethod
6464
def _decrypt(enc, key, ctxt, iv, tag, auth_data=b""):
65-
""" Decrypt JWE content.
65+
"""Decrypt JWE content.
6666
6767
:param enc: The JWE "enc" value specifying the encryption algorithm
6868
:param key: Key (CEK)

src/cryptojwt/jwe/rsa.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ def encrypt(self, msg, key, sign_padding="pkcs1_padding"):
2020
return key.encrypt(
2121
msg,
2222
_padding(
23-
mgf=padding.MGF1(algorithm=_chosen_hash()), algorithm=_chosen_hash(), label=None,
23+
mgf=padding.MGF1(algorithm=_chosen_hash()),
24+
algorithm=_chosen_hash(),
25+
label=None,
2426
),
2527
)
2628

src/cryptojwt/jwk/jwk.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ def key_from_jwk_dict(jwk_dict, private=None):
9393
else:
9494
# Ecdsa public key.
9595
ec_pub_numbers = ec.EllipticCurvePublicNumbers(
96-
base64url_to_long(_jwk_dict["x"]), base64url_to_long(_jwk_dict["y"]), curve,
96+
base64url_to_long(_jwk_dict["x"]),
97+
base64url_to_long(_jwk_dict["y"]),
98+
curve,
9799
)
98100
_jwk_dict["pub_key"] = ec_pub_numbers.public_key(backends.default_backend())
99101
return ECKey(**_jwk_dict)

src/cryptojwt/jwk/rsa.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def rsa_eq(key1, key2):
128128

129129

130130
def x509_rsa_load(txt):
131-
""" So I get the same output format as loads produces
131+
"""So I get the same output format as loads produces
132132
:param txt:
133133
:return:
134134
"""
@@ -172,10 +172,10 @@ def rsa_construct_private(numbers):
172172
try:
173173
cnum["iqmp"] = numbers["di"]
174174
except KeyError:
175-
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["p"])
175+
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["q"])
176176
else:
177177
if not numbers["di"]:
178-
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["p"])
178+
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["q"])
179179

180180
rpubn = rsa.RSAPublicNumbers(e=numbers["e"], n=numbers["n"])
181181
rprivn = rsa.RSAPrivateNumbers(public_numbers=rpubn, **cnum)

src/cryptojwt/jws/jws.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,11 @@ def verify_json(self, jws, keys=None, allow_none=False, at_least_one=False):
321321
for _sign in _signs:
322322
protected_headers = _sign.get("protected", "")
323323
token = b".".join(
324-
[protected_headers.encode(), _payload.encode(), _sign["signature"].encode(),]
324+
[
325+
protected_headers.encode(),
326+
_payload.encode(),
327+
_sign["signature"].encode(),
328+
]
325329
)
326330

327331
unprotected_headers = _sign.get("header", {})

src/cryptojwt/jws/pss.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ def sign(self, msg, key):
3838
sig = key.sign(
3939
digest,
4040
padding.PSS(
41-
mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH,
41+
mgf=padding.MGF1(self.hash_algorithm()),
42+
salt_length=padding.PSS.MAX_LENGTH,
4243
),
4344
utils.Prehashed(self.hash_algorithm()),
4445
)
@@ -59,7 +60,8 @@ def verify(self, msg, signature, key):
5960
signature,
6061
msg,
6162
padding.PSS(
62-
mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH,
63+
mgf=padding.MGF1(self.hash_algorithm()),
64+
salt_length=padding.PSS.MAX_LENGTH,
6365
),
6466
self.hash_algorithm(),
6567
)

src/cryptojwt/jws/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212

1313
def left_hash(msg, func="HS256"):
14-
""" Calculate left hash as described in
14+
"""Calculate left hash as described in
1515
https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
1616
for at_hash and in
1717
for c_hash

src/cryptojwt/key_bundle.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,9 @@ def do_remote(self):
402402

403403
else:
404404
LOGGER.warning(
405-
"HTTP status %d reading remote JWKS from %s", _http_resp.status_code, self.source,
405+
"HTTP status %d reading remote JWKS from %s",
406+
_http_resp.status_code,
407+
self.source,
406408
)
407409
raise UpdateFailed(REMOTE_FAILED.format(self.source, _http_resp.status_code))
408410
self.last_updated = time.time()

src/cryptojwt/key_jar.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,12 @@ def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id="", storage=N
762762

763763
@deprecated_alias(issuer="issuer_id", owner="issuer_id")
764764
def init_key_jar(
765-
public_path="", private_path="", key_defs="", issuer_id="", read_only=True, storage=None,
765+
public_path="",
766+
private_path="",
767+
key_defs="",
768+
issuer_id="",
769+
read_only=True,
770+
storage=None,
766771
):
767772
"""
768773
A number of cases here:
@@ -805,7 +810,10 @@ def init_key_jar(
805810
"""
806811

807812
_issuer = init_key_issuer(
808-
public_path=public_path, private_path=private_path, key_defs=key_defs, read_only=read_only,
813+
public_path=public_path,
814+
private_path=private_path,
815+
key_defs=key_defs,
816+
read_only=read_only,
809817
)
810818

811819
if _issuer is None:

src/cryptojwt/tools/keyconv.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,10 @@ def pem2jwk(
115115

116116

117117
def export_jwk(
118-
jwk: JWK, private: bool = False, encrypt: bool = False, passphrase: Optional[str] = None,
118+
jwk: JWK,
119+
private: bool = False,
120+
encrypt: bool = False,
121+
passphrase: Optional[str] = None,
119122
) -> bytes:
120123
"""Export JWK as PEM/bin"""
121124

src/cryptojwt/utils.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,7 @@ def as_unicode(b):
158158

159159

160160
def bytes2str_conv(item):
161-
"""
162-
"""
161+
""""""
163162
if isinstance(item, bytes):
164163
return item.decode("utf-8")
165164
elif item is None or isinstance(item, (str, int, bool)):

tests/test_01_simplejwt.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ def _eq(l1, l2):
1010
def test_pack_jwt():
1111
_jwt = SimpleJWT(**{"alg": "none", "cty": "jwt"})
1212
jwt = _jwt.pack(
13-
parts=[{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}, "",]
13+
parts=[
14+
{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True},
15+
"",
16+
]
1417
)
1518

1619
p = jwt.split(".")

tests/test_02_jwk.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,9 @@ def test_key_from_jwk_dict_rsa():
515515
_key = key_from_jwk_dict(jwk)
516516
assert isinstance(_key, RSAKey)
517517
assert _key.has_private_key()
518+
_key2 = RSAKey(**jwk)
519+
assert isinstance(_key2, RSAKey)
520+
assert _key2.has_private_key()
518521

519522

520523
def test_key_from_jwk_dict_ec():
@@ -707,7 +710,10 @@ def test_x5t_calculation():
707710

708711
@pytest.mark.parametrize(
709712
"filename,key_type",
710-
[("ec-public.pem", ec.EllipticCurvePublicKey), ("rsa-public.pem", rsa.RSAPublicKey),],
713+
[
714+
("ec-public.pem", ec.EllipticCurvePublicKey),
715+
("rsa-public.pem", rsa.RSAPublicKey),
716+
],
711717
)
712718
def test_import_public_key_from_pem_file(filename, key_type):
713719
_file = full_path(filename)

tests/test_04_key_issuer.py

+18-4
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,11 @@ def test_build_keyissuer_usage():
221221

222222
def test_build_keyissuer_missing(tmpdir):
223223
keys = [
224-
{"type": "RSA", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
224+
{
225+
"type": "RSA",
226+
"key": os.path.join(tmpdir.dirname, "missing_file"),
227+
"use": ["enc", "sig"],
228+
}
225229
]
226230

227231
key_issuer = build_keyissuer(keys)
@@ -239,7 +243,11 @@ def test_build_RSA_keyissuer_from_file(tmpdir):
239243

240244
def test_build_EC_keyissuer_missing(tmpdir):
241245
keys = [
242-
{"type": "EC", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
246+
{
247+
"type": "EC",
248+
"key": os.path.join(tmpdir.dirname, "missing_file"),
249+
"use": ["enc", "sig"],
250+
}
243251
]
244252

245253
key_issuer = build_keyissuer(keys)
@@ -616,7 +624,10 @@ def test_init_key_issuer_update():
616624

617625
# New set of keys, JWKSs with keys and public written to file
618626
_keyissuer_1 = init_key_issuer(
619-
private_path=PRIVATE_FILE, key_defs=KEYSPEC, public_path=PUBLIC_FILE, read_only=False,
627+
private_path=PRIVATE_FILE,
628+
key_defs=KEYSPEC,
629+
public_path=PUBLIC_FILE,
630+
read_only=False,
620631
)
621632
assert len(_keyissuer_1) == 2
622633

@@ -646,7 +657,10 @@ def test_init_key_issuer_update():
646657
assert len(_keyissuer_3.get("sig", "EC")) == 1
647658

648659
_keyissuer_4 = init_key_issuer(
649-
private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE, read_only=False,
660+
private_path=PRIVATE_FILE,
661+
key_defs=KEYSPEC_2,
662+
public_path=PUBLIC_FILE,
663+
read_only=False,
650664
)
651665

652666
# Now it should

tests/test_04_key_jar.py

+26-9
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,11 @@ def test_build_keyjar_usage():
229229

230230
def test_build_keyjar_missing(tmpdir):
231231
keys = [
232-
{"type": "RSA", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
232+
{
233+
"type": "RSA",
234+
"key": os.path.join(tmpdir.dirname, "missing_file"),
235+
"use": ["enc", "sig"],
236+
}
233237
]
234238

235239
key_jar = build_keyjar(keys)
@@ -247,7 +251,11 @@ def test_build_RSA_keyjar_from_file(tmpdir):
247251

248252
def test_build_EC_keyjar_missing(tmpdir):
249253
keys = [
250-
{"type": "EC", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
254+
{
255+
"type": "EC",
256+
"key": os.path.join(tmpdir.dirname, "missing_file"),
257+
"use": ["enc", "sig"],
258+
}
251259
]
252260

253261
key_jar = build_keyjar(keys)
@@ -303,7 +311,8 @@ def test_items(self):
303311
),
304312
)
305313
ks.add_kb(
306-
"http://www.example.org", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
314+
"http://www.example.org",
315+
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
307316
)
308317

309318
assert len(ks.items()) == 2
@@ -329,7 +338,8 @@ def test_issuer_extra_slash(self):
329338
),
330339
)
331340
ks.add_kb(
332-
"http://www.example.org", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
341+
"http://www.example.org",
342+
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
333343
)
334344

335345
assert ks.get("sig", "RSA", "http://www.example.org/")
@@ -355,7 +365,8 @@ def test_issuer_missing_slash(self):
355365
),
356366
)
357367
ks.add_kb(
358-
"http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
368+
"http://www.example.org/",
369+
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
359370
)
360371

361372
assert ks.get("sig", "RSA", "http://www.example.org")
@@ -381,7 +392,8 @@ def test_get_enc(self):
381392
),
382393
)
383394
ks.add_kb(
384-
"http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
395+
"http://www.example.org/",
396+
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
385397
)
386398

387399
assert ks.get("enc", "oct")
@@ -407,7 +419,8 @@ def test_get_enc_not_mine(self):
407419
),
408420
)
409421
ks.add_kb(
410-
"http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
422+
"http://www.example.org/",
423+
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
411424
)
412425

413426
assert ks.get("enc", "oct", "http://www.example.org/")
@@ -449,7 +462,8 @@ def test_provider(self):
449462
kj = KeyJar()
450463
_url = "https://connect-op.herokuapp.com/jwks.json"
451464
kj.load_keys(
452-
"https://connect-op.heroku.com", jwks_uri=_url,
465+
"https://connect-op.heroku.com",
466+
jwks_uri=_url,
453467
)
454468
iss_keys = kj.get_issuer_keys("https://connect-op.heroku.com")
455469
if not iss_keys:
@@ -968,7 +982,10 @@ def test_init_key_jar_update():
968982
assert len(_keyjar_3.get_signing_key("EC")) == 1
969983

970984
_keyjar_4 = init_key_jar(
971-
private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE, read_only=False,
985+
private_path=PRIVATE_FILE,
986+
key_defs=KEYSPEC_2,
987+
public_path=PUBLIC_FILE,
988+
read_only=False,
972989
)
973990

974991
# Now it should

0 commit comments

Comments
 (0)