From 4b75a1a72a9ada56db24b6febff54019daf1fd32 Mon Sep 17 00:00:00 2001 From: Evgeniy Tatarkin Date: Sun, 28 Nov 2021 16:25:42 +0300 Subject: [PATCH 1/2] Explicit check the key for ECAlgorithm --- jwt/algorithms.py | 4 ++++ tests/test_algorithms.py | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/jwt/algorithms.py b/jwt/algorithms.py index 1f8865afb..e8d49c4cd 100644 --- a/jwt/algorithms.py +++ b/jwt/algorithms.py @@ -417,6 +417,10 @@ def prepare_key(self, key): except ValueError: key = load_pem_private_key(key, password=None) + # Explicit check the key to prevent confusing errors from cryptography + if not isinstance(key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)): + raise InvalidKeyError("Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for ECDSA algorithms") + return key def sign(self, msg, key): diff --git a/tests/test_algorithms.py b/tests/test_algorithms.py index b6a73fc4d..f4ab75bbc 100644 --- a/tests/test_algorithms.py +++ b/tests/test_algorithms.py @@ -494,6 +494,18 @@ def test_ec_verify_should_return_false_if_signature_wrong_length(self): result = algo.verify(message, pub_key, sig) assert not result + @crypto_required + def test_ec_should_throw_exception_on_wrong_key(self): + algo = ECAlgorithm(ECAlgorithm.SHA256) + + with pytest.raises(InvalidKeyError): + with open(key_path("testkey_rsa.priv")) as keyfile: + algo.prepare_key(keyfile.read()) + + with pytest.raises(InvalidKeyError): + with open(key_path("testkey2_rsa.pub.pem")) as pem_key: + algo.prepare_key(pem_key.read()) + @crypto_required def test_rsa_pss_sign_then_verify_should_return_true(self): algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256) From 509695e05dce53b504652f84e7166a3e4094569c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 28 Nov 2021 13:36:51 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- jwt/algorithms.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jwt/algorithms.py b/jwt/algorithms.py index e8d49c4cd..739df808f 100644 --- a/jwt/algorithms.py +++ b/jwt/algorithms.py @@ -419,7 +419,9 @@ def prepare_key(self, key): # Explicit check the key to prevent confusing errors from cryptography if not isinstance(key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)): - raise InvalidKeyError("Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for ECDSA algorithms") + raise InvalidKeyError( + "Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for ECDSA algorithms" + ) return key