Skip to content

Work around bad RSAKey import #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/cryptojwt/jwe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,14 @@
"ECDH-ES+A192KW",
"ECDH-ES+A256KW",
],
"enc": ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512", "A128GCM", "A192GCM", "A256GCM",],
"enc": [
"A128CBC-HS256",
"A192CBC-HS384",
"A256CBC-HS512",
"A128GCM",
"A192GCM",
"A256GCM",
],
}


Expand Down
3 changes: 1 addition & 2 deletions src/cryptojwt/jwe/aes.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@


class AES_CBCEncrypter(Encrypter):
"""
"""
""""""

def __init__(self, key_len=32, key=None, msg_padding="PKCS7"):
Encrypter.__init__(self)
Expand Down
7 changes: 6 additions & 1 deletion src/cryptojwt/jwe/jwe_ec.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,12 @@ def dec_setup(self, token, key=None, **kwargs):
raise Exception("Unknown key length for algorithm")

self.cek = ecdh_derive_key(
key, epubkey.pub_key, apu, apv, str(self.headers["enc"]).encode(), dk_len,
key,
epubkey.pub_key,
apu,
apv,
str(self.headers["enc"]).encode(),
dk_len,
)
elif self.headers["alg"] in [
"ECDH-ES+A128KW",
Expand Down
2 changes: 1 addition & 1 deletion src/cryptojwt/jwe/jwe_rsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def encrypt(self, key, iv="", cek="", **kwargs):
return jwe.pack(parts=[jwe_enc_key, iv, ctxt, tag])

def decrypt(self, token, key, cek=None):
""" Decrypts a JWT
"""Decrypts a JWT

:param token: The JWT
:param key: A key to use for decrypting
Expand Down
4 changes: 2 additions & 2 deletions src/cryptojwt/jwe/jwekey.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def alg2keytype(self, alg):
return alg2keytype(alg)

def enc_setup(self, enc_alg, msg, auth_data=b"", key=None, iv=""):
""" Encrypt JWE content.
"""Encrypt JWE content.

:param enc_alg: The JWE "enc" value specifying the encryption algorithm
:param msg: The plain text message
Expand All @@ -62,7 +62,7 @@ def enc_setup(self, enc_alg, msg, auth_data=b"", key=None, iv=""):

@staticmethod
def _decrypt(enc, key, ctxt, iv, tag, auth_data=b""):
""" Decrypt JWE content.
"""Decrypt JWE content.

:param enc: The JWE "enc" value specifying the encryption algorithm
:param key: Key (CEK)
Expand Down
4 changes: 3 additions & 1 deletion src/cryptojwt/jwe/rsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ def encrypt(self, msg, key, sign_padding="pkcs1_padding"):
return key.encrypt(
msg,
_padding(
mgf=padding.MGF1(algorithm=_chosen_hash()), algorithm=_chosen_hash(), label=None,
mgf=padding.MGF1(algorithm=_chosen_hash()),
algorithm=_chosen_hash(),
label=None,
),
)

Expand Down
4 changes: 3 additions & 1 deletion src/cryptojwt/jwk/jwk.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ def key_from_jwk_dict(jwk_dict, private=None):
else:
# Ecdsa public key.
ec_pub_numbers = ec.EllipticCurvePublicNumbers(
base64url_to_long(_jwk_dict["x"]), base64url_to_long(_jwk_dict["y"]), curve,
base64url_to_long(_jwk_dict["x"]),
base64url_to_long(_jwk_dict["y"]),
curve,
)
_jwk_dict["pub_key"] = ec_pub_numbers.public_key(backends.default_backend())
return ECKey(**_jwk_dict)
Expand Down
6 changes: 3 additions & 3 deletions src/cryptojwt/jwk/rsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def rsa_eq(key1, key2):


def x509_rsa_load(txt):
""" So I get the same output format as loads produces
"""So I get the same output format as loads produces
:param txt:
:return:
"""
Expand Down Expand Up @@ -172,10 +172,10 @@ def rsa_construct_private(numbers):
try:
cnum["iqmp"] = numbers["di"]
except KeyError:
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["p"])
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["q"])
else:
if not numbers["di"]:
cnum["iqmp"] = rsa.rsa_crt_iqmp(cnum["p"], cnum["p"])
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)
Expand Down
6 changes: 5 additions & 1 deletion src/cryptojwt/jws/jws.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,11 @@ def verify_json(self, jws, keys=None, allow_none=False, at_least_one=False):
for _sign in _signs:
protected_headers = _sign.get("protected", "")
token = b".".join(
[protected_headers.encode(), _payload.encode(), _sign["signature"].encode(),]
[
protected_headers.encode(),
_payload.encode(),
_sign["signature"].encode(),
]
)

unprotected_headers = _sign.get("header", {})
Expand Down
6 changes: 4 additions & 2 deletions src/cryptojwt/jws/pss.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ def sign(self, msg, key):
sig = key.sign(
digest,
padding.PSS(
mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH,
mgf=padding.MGF1(self.hash_algorithm()),
salt_length=padding.PSS.MAX_LENGTH,
),
utils.Prehashed(self.hash_algorithm()),
)
Expand All @@ -59,7 +60,8 @@ def verify(self, msg, signature, key):
signature,
msg,
padding.PSS(
mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH,
mgf=padding.MGF1(self.hash_algorithm()),
salt_length=padding.PSS.MAX_LENGTH,
),
self.hash_algorithm(),
)
Expand Down
2 changes: 1 addition & 1 deletion src/cryptojwt/jws/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


def left_hash(msg, func="HS256"):
""" Calculate left hash as described in
"""Calculate left hash as described in
https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
for at_hash and in
for c_hash
Expand Down
4 changes: 3 additions & 1 deletion src/cryptojwt/key_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,9 @@ def do_remote(self):

else:
LOGGER.warning(
"HTTP status %d reading remote JWKS from %s", _http_resp.status_code, self.source,
"HTTP status %d reading remote JWKS from %s",
_http_resp.status_code,
self.source,
)
raise UpdateFailed(REMOTE_FAILED.format(self.source, _http_resp.status_code))
self.last_updated = time.time()
Expand Down
12 changes: 10 additions & 2 deletions src/cryptojwt/key_jar.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,12 @@ def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id="", storage=N

@deprecated_alias(issuer="issuer_id", owner="issuer_id")
def init_key_jar(
public_path="", private_path="", key_defs="", issuer_id="", read_only=True, storage=None,
public_path="",
private_path="",
key_defs="",
issuer_id="",
read_only=True,
storage=None,
):
"""
A number of cases here:
Expand Down Expand Up @@ -805,7 +810,10 @@ def init_key_jar(
"""

_issuer = init_key_issuer(
public_path=public_path, private_path=private_path, key_defs=key_defs, read_only=read_only,
public_path=public_path,
private_path=private_path,
key_defs=key_defs,
read_only=read_only,
)

if _issuer is None:
Expand Down
5 changes: 4 additions & 1 deletion src/cryptojwt/tools/keyconv.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,10 @@ def pem2jwk(


def export_jwk(
jwk: JWK, private: bool = False, encrypt: bool = False, passphrase: Optional[str] = None,
jwk: JWK,
private: bool = False,
encrypt: bool = False,
passphrase: Optional[str] = None,
) -> bytes:
"""Export JWK as PEM/bin"""

Expand Down
3 changes: 1 addition & 2 deletions src/cryptojwt/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,7 @@ def as_unicode(b):


def bytes2str_conv(item):
"""
"""
""""""
if isinstance(item, bytes):
return item.decode("utf-8")
elif item is None or isinstance(item, (str, int, bool)):
Expand Down
5 changes: 4 additions & 1 deletion tests/test_01_simplejwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ def _eq(l1, l2):
def test_pack_jwt():
_jwt = SimpleJWT(**{"alg": "none", "cty": "jwt"})
jwt = _jwt.pack(
parts=[{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True}, "",]
parts=[
{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": True},
"",
]
)

p = jwt.split(".")
Expand Down
8 changes: 7 additions & 1 deletion tests/test_02_jwk.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,9 @@ def test_key_from_jwk_dict_rsa():
_key = key_from_jwk_dict(jwk)
assert isinstance(_key, RSAKey)
assert _key.has_private_key()
_key2 = RSAKey(**jwk)
assert isinstance(_key2, RSAKey)
assert _key2.has_private_key()


def test_key_from_jwk_dict_ec():
Expand Down Expand Up @@ -707,7 +710,10 @@ def test_x5t_calculation():

@pytest.mark.parametrize(
"filename,key_type",
[("ec-public.pem", ec.EllipticCurvePublicKey), ("rsa-public.pem", rsa.RSAPublicKey),],
[
("ec-public.pem", ec.EllipticCurvePublicKey),
("rsa-public.pem", rsa.RSAPublicKey),
],
)
def test_import_public_key_from_pem_file(filename, key_type):
_file = full_path(filename)
Expand Down
22 changes: 18 additions & 4 deletions tests/test_04_key_issuer.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,11 @@ def test_build_keyissuer_usage():

def test_build_keyissuer_missing(tmpdir):
keys = [
{"type": "RSA", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
{
"type": "RSA",
"key": os.path.join(tmpdir.dirname, "missing_file"),
"use": ["enc", "sig"],
}
]

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

def test_build_EC_keyissuer_missing(tmpdir):
keys = [
{"type": "EC", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
{
"type": "EC",
"key": os.path.join(tmpdir.dirname, "missing_file"),
"use": ["enc", "sig"],
}
]

key_issuer = build_keyissuer(keys)
Expand Down Expand Up @@ -616,7 +624,10 @@ def test_init_key_issuer_update():

# New set of keys, JWKSs with keys and public written to file
_keyissuer_1 = init_key_issuer(
private_path=PRIVATE_FILE, key_defs=KEYSPEC, public_path=PUBLIC_FILE, read_only=False,
private_path=PRIVATE_FILE,
key_defs=KEYSPEC,
public_path=PUBLIC_FILE,
read_only=False,
)
assert len(_keyissuer_1) == 2

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

_keyissuer_4 = init_key_issuer(
private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE, read_only=False,
private_path=PRIVATE_FILE,
key_defs=KEYSPEC_2,
public_path=PUBLIC_FILE,
read_only=False,
)

# Now it should
Expand Down
35 changes: 26 additions & 9 deletions tests/test_04_key_jar.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,11 @@ def test_build_keyjar_usage():

def test_build_keyjar_missing(tmpdir):
keys = [
{"type": "RSA", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
{
"type": "RSA",
"key": os.path.join(tmpdir.dirname, "missing_file"),
"use": ["enc", "sig"],
}
]

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

def test_build_EC_keyjar_missing(tmpdir):
keys = [
{"type": "EC", "key": os.path.join(tmpdir.dirname, "missing_file"), "use": ["enc", "sig"],}
{
"type": "EC",
"key": os.path.join(tmpdir.dirname, "missing_file"),
"use": ["enc", "sig"],
}
]

key_jar = build_keyjar(keys)
Expand Down Expand Up @@ -303,7 +311,8 @@ def test_items(self):
),
)
ks.add_kb(
"http://www.example.org", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
"http://www.example.org",
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
)

assert len(ks.items()) == 2
Expand All @@ -329,7 +338,8 @@ def test_issuer_extra_slash(self):
),
)
ks.add_kb(
"http://www.example.org", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
"http://www.example.org",
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
)

assert ks.get("sig", "RSA", "http://www.example.org/")
Expand All @@ -355,7 +365,8 @@ def test_issuer_missing_slash(self):
),
)
ks.add_kb(
"http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
"http://www.example.org/",
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
)

assert ks.get("sig", "RSA", "http://www.example.org")
Expand All @@ -381,7 +392,8 @@ def test_get_enc(self):
),
)
ks.add_kb(
"http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
"http://www.example.org/",
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
)

assert ks.get("enc", "oct")
Expand All @@ -407,7 +419,8 @@ def test_get_enc_not_mine(self):
),
)
ks.add_kb(
"http://www.example.org/", keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
"http://www.example.org/",
keybundle_from_local_file(RSAKEY, "der", ["ver", "sig"]),
)

assert ks.get("enc", "oct", "http://www.example.org/")
Expand Down Expand Up @@ -449,7 +462,8 @@ def test_provider(self):
kj = KeyJar()
_url = "https://connect-op.herokuapp.com/jwks.json"
kj.load_keys(
"https://connect-op.heroku.com", jwks_uri=_url,
"https://connect-op.heroku.com",
jwks_uri=_url,
)
iss_keys = kj.get_issuer_keys("https://connect-op.heroku.com")
if not iss_keys:
Expand Down Expand Up @@ -968,7 +982,10 @@ def test_init_key_jar_update():
assert len(_keyjar_3.get_signing_key("EC")) == 1

_keyjar_4 = init_key_jar(
private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE, read_only=False,
private_path=PRIVATE_FILE,
key_defs=KEYSPEC_2,
public_path=PUBLIC_FILE,
read_only=False,
)

# Now it should
Expand Down
Loading