Skip to content

Commit aabeb06

Browse files
Explicit check the key for ECAlgorithm (#713)
* Explicit check the key for ECAlgorithm * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 43d38a0 commit aabeb06

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

jwt/algorithms.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,12 @@ def prepare_key(self, key):
417417
except ValueError:
418418
key = load_pem_private_key(key, password=None)
419419

420+
# Explicit check the key to prevent confusing errors from cryptography
421+
if not isinstance(key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)):
422+
raise InvalidKeyError(
423+
"Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for ECDSA algorithms"
424+
)
425+
420426
return key
421427

422428
def sign(self, msg, key):

tests/test_algorithms.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,18 @@ def test_ec_verify_should_return_false_if_signature_wrong_length(self):
494494
result = algo.verify(message, pub_key, sig)
495495
assert not result
496496

497+
@crypto_required
498+
def test_ec_should_throw_exception_on_wrong_key(self):
499+
algo = ECAlgorithm(ECAlgorithm.SHA256)
500+
501+
with pytest.raises(InvalidKeyError):
502+
with open(key_path("testkey_rsa.priv")) as keyfile:
503+
algo.prepare_key(keyfile.read())
504+
505+
with pytest.raises(InvalidKeyError):
506+
with open(key_path("testkey2_rsa.pub.pem")) as pem_key:
507+
algo.prepare_key(pem_key.read())
508+
497509
@crypto_required
498510
def test_rsa_pss_sign_then_verify_should_return_true(self):
499511
algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)

0 commit comments

Comments
 (0)