Skip to content
Open
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 jose/backends/ecdsa_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from jose.backends.base import Key
from jose.constants import ALGORITHMS
from jose.exceptions import JWKError
from jose.utils import base64_to_long, long_to_base64
from jose.utils import base64_to_long, is_pem_format, long_to_base64


class ECDSAECKey(Key):
Expand Down Expand Up @@ -58,6 +58,13 @@ def __init__(self, key, algorithm):
key = key.encode("utf-8")

if isinstance(key, bytes):
# python-ecdsa's from_pem() skips the "-----" armor lines and also
# decodes bare base64 DER. HMACKey only refuses PEM-armored keys,
# so a key accepted here without armor could also be used as an
# HMAC secret. Require real PEM, as the cryptography backend does.
if not is_pem_format(key):
raise JWKError("Unable to parse an ECKey from key: key is not in PEM format")

# Attempt to load key. We don't know if it's
# a Signing Key or a Verifying Key, so we try
# the Verifying Key first.
Expand Down
16 changes: 16 additions & 0 deletions tests/algorithms/test_EC.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,22 @@ def test_key_from_ecdsa():
assert not ECKey(key, ALGORITHMS.ES256).is_public()


@pytest.mark.ecdsa
@pytest.mark.skipif(None in (ECDSAECKey, ecdsa), reason="python-ecdsa backend not available")
def test_ecdsa_key_without_pem_armor_rejected():
pem = ecdsa.SigningKey.from_pem(private_key).get_verifying_key().to_pem().decode()
bare = "".join(line for line in pem.splitlines() if not line.startswith("-----"))

# Without the armor the key would also pass HMACKey's asymmetric key
# check, so the same public key string could verify an HS256 token.
with pytest.raises(JWKError):
ECDSAECKey(bare, ALGORITHMS.ES256)
with pytest.raises(JWKError):
ECDSAECKey(pem.replace("PUBLIC KEY", "EC PUBLIC KEY"), ALGORITHMS.ES256)

assert ECDSAECKey(pem, ALGORITHMS.ES256).is_public()


@pytest.mark.cryptography
@pytest.mark.skipif(CryptographyECKey is None, reason="pyca/cryptography backend not available")
@pytest.mark.parametrize(
Expand Down