mirror of
https://github.com/Tautulli/Tautulli.git
synced 2025-07-06 05:01:14 -07:00
Bump pyjwt from 2.6.0 to 2.8.0 (#2115)
* Bump pyjwt from 2.6.0 to 2.8.0 Bumps [pyjwt](https://github.com/jpadilla/pyjwt) from 2.6.0 to 2.8.0. - [Release notes](https://github.com/jpadilla/pyjwt/releases) - [Changelog](https://github.com/jpadilla/pyjwt/blob/master/CHANGELOG.rst) - [Commits](https://github.com/jpadilla/pyjwt/compare/2.6.0...2.8.0) --- updated-dependencies: - dependency-name: pyjwt dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> * Update pyjwt==2.8.0 --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: JonnyWong16 <9099342+JonnyWong16@users.noreply.github.com> [skip ci]
This commit is contained in:
parent
77f38bbf93
commit
c93f470371
12 changed files with 542 additions and 260 deletions
|
@ -1,8 +1,14 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import sys
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, Union, cast, overload
|
||||
|
||||
from .exceptions import InvalidKeyError
|
||||
from .types import HashlibHash, JWKDict
|
||||
from .utils import (
|
||||
base64url_decode,
|
||||
base64url_encode,
|
||||
|
@ -15,14 +21,28 @@ from .utils import (
|
|||
to_base64url_uint,
|
||||
)
|
||||
|
||||
if sys.version_info >= (3, 8):
|
||||
from typing import Literal
|
||||
else:
|
||||
from typing_extensions import Literal
|
||||
|
||||
|
||||
try:
|
||||
import cryptography.exceptions
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, padding
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.asymmetric.ec import (
|
||||
ECDSA,
|
||||
SECP256K1,
|
||||
SECP256R1,
|
||||
SECP384R1,
|
||||
SECP521R1,
|
||||
EllipticCurve,
|
||||
EllipticCurvePrivateKey,
|
||||
EllipticCurvePrivateNumbers,
|
||||
EllipticCurvePublicKey,
|
||||
EllipticCurvePublicNumbers,
|
||||
)
|
||||
from cryptography.hazmat.primitives.asymmetric.ed448 import (
|
||||
Ed448PrivateKey,
|
||||
|
@ -56,6 +76,23 @@ try:
|
|||
except ModuleNotFoundError:
|
||||
has_crypto = False
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Type aliases for convenience in algorithms method signatures
|
||||
AllowedRSAKeys = RSAPrivateKey | RSAPublicKey
|
||||
AllowedECKeys = EllipticCurvePrivateKey | EllipticCurvePublicKey
|
||||
AllowedOKPKeys = (
|
||||
Ed25519PrivateKey | Ed25519PublicKey | Ed448PrivateKey | Ed448PublicKey
|
||||
)
|
||||
AllowedKeys = AllowedRSAKeys | AllowedECKeys | AllowedOKPKeys
|
||||
AllowedPrivateKeys = (
|
||||
RSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey | Ed448PrivateKey
|
||||
)
|
||||
AllowedPublicKeys = (
|
||||
RSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey
|
||||
)
|
||||
|
||||
|
||||
requires_cryptography = {
|
||||
"RS256",
|
||||
"RS384",
|
||||
|
@ -72,7 +109,7 @@ requires_cryptography = {
|
|||
}
|
||||
|
||||
|
||||
def get_default_algorithms():
|
||||
def get_default_algorithms() -> dict[str, Algorithm]:
|
||||
"""
|
||||
Returns the algorithms that are implemented by the library.
|
||||
"""
|
||||
|
@ -106,45 +143,79 @@ def get_default_algorithms():
|
|||
return default_algorithms
|
||||
|
||||
|
||||
class Algorithm:
|
||||
class Algorithm(ABC):
|
||||
"""
|
||||
The interface for an algorithm used to sign and verify tokens.
|
||||
"""
|
||||
|
||||
def prepare_key(self, key):
|
||||
def compute_hash_digest(self, bytestr: bytes) -> bytes:
|
||||
"""
|
||||
Compute a hash digest using the specified algorithm's hash algorithm.
|
||||
|
||||
If there is no hash algorithm, raises a NotImplementedError.
|
||||
"""
|
||||
# lookup self.hash_alg if defined in a way that mypy can understand
|
||||
hash_alg = getattr(self, "hash_alg", None)
|
||||
if hash_alg is None:
|
||||
raise NotImplementedError
|
||||
|
||||
if (
|
||||
has_crypto
|
||||
and isinstance(hash_alg, type)
|
||||
and issubclass(hash_alg, hashes.HashAlgorithm)
|
||||
):
|
||||
digest = hashes.Hash(hash_alg(), backend=default_backend())
|
||||
digest.update(bytestr)
|
||||
return bytes(digest.finalize())
|
||||
else:
|
||||
return bytes(hash_alg(bytestr).digest())
|
||||
|
||||
@abstractmethod
|
||||
def prepare_key(self, key: Any) -> Any:
|
||||
"""
|
||||
Performs necessary validation and conversions on the key and returns
|
||||
the key value in the proper format for sign() and verify().
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def sign(self, msg, key):
|
||||
@abstractmethod
|
||||
def sign(self, msg: bytes, key: Any) -> bytes:
|
||||
"""
|
||||
Returns a digital signature for the specified message
|
||||
using the specified key value.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def verify(self, msg, key, sig):
|
||||
@abstractmethod
|
||||
def verify(self, msg: bytes, key: Any, sig: bytes) -> bool:
|
||||
"""
|
||||
Verifies that the specified digital signature is valid
|
||||
for the specified message and key values.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def to_jwk(key_obj, as_dict: Literal[True]) -> JWKDict:
|
||||
... # pragma: no cover
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
@abstractmethod
|
||||
def to_jwk(key_obj, as_dict: Literal[False] = False) -> str:
|
||||
... # pragma: no cover
|
||||
|
||||
@staticmethod
|
||||
def to_jwk(key_obj):
|
||||
@abstractmethod
|
||||
def to_jwk(key_obj, as_dict: bool = False) -> Union[JWKDict, str]:
|
||||
"""
|
||||
Serializes a given RSA key into a JWK
|
||||
Serializes a given key into a JWK
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@staticmethod
|
||||
def from_jwk(jwk):
|
||||
@abstractmethod
|
||||
def from_jwk(jwk: str | JWKDict) -> Any:
|
||||
"""
|
||||
Deserializes a given RSA key from JWK back into a PublicKey or PrivateKey object
|
||||
Deserializes a given key from JWK back into a key object
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class NoneAlgorithm(Algorithm):
|
||||
|
@ -153,7 +224,7 @@ class NoneAlgorithm(Algorithm):
|
|||
operations are required.
|
||||
"""
|
||||
|
||||
def prepare_key(self, key):
|
||||
def prepare_key(self, key: str | None) -> None:
|
||||
if key == "":
|
||||
key = None
|
||||
|
||||
|
@ -162,12 +233,20 @@ class NoneAlgorithm(Algorithm):
|
|||
|
||||
return key
|
||||
|
||||
def sign(self, msg, key):
|
||||
def sign(self, msg: bytes, key: None) -> bytes:
|
||||
return b""
|
||||
|
||||
def verify(self, msg, key, sig):
|
||||
def verify(self, msg: bytes, key: None, sig: bytes) -> bool:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def to_jwk(key_obj: Any, as_dict: bool = False) -> NoReturn:
|
||||
raise NotImplementedError()
|
||||
|
||||
@staticmethod
|
||||
def from_jwk(jwk: str | JWKDict) -> NoReturn:
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class HMACAlgorithm(Algorithm):
|
||||
"""
|
||||
|
@ -175,38 +254,51 @@ class HMACAlgorithm(Algorithm):
|
|||
and the specified hash function.
|
||||
"""
|
||||
|
||||
SHA256 = hashlib.sha256
|
||||
SHA384 = hashlib.sha384
|
||||
SHA512 = hashlib.sha512
|
||||
SHA256: ClassVar[HashlibHash] = hashlib.sha256
|
||||
SHA384: ClassVar[HashlibHash] = hashlib.sha384
|
||||
SHA512: ClassVar[HashlibHash] = hashlib.sha512
|
||||
|
||||
def __init__(self, hash_alg):
|
||||
def __init__(self, hash_alg: HashlibHash) -> None:
|
||||
self.hash_alg = hash_alg
|
||||
|
||||
def prepare_key(self, key):
|
||||
key = force_bytes(key)
|
||||
def prepare_key(self, key: str | bytes) -> bytes:
|
||||
key_bytes = force_bytes(key)
|
||||
|
||||
if is_pem_format(key) or is_ssh_key(key):
|
||||
if is_pem_format(key_bytes) or is_ssh_key(key_bytes):
|
||||
raise InvalidKeyError(
|
||||
"The specified key is an asymmetric key or x509 certificate and"
|
||||
" should not be used as an HMAC secret."
|
||||
)
|
||||
|
||||
return key
|
||||
return key_bytes
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key_obj: str | bytes, as_dict: Literal[True]) -> JWKDict:
|
||||
... # pragma: no cover
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key_obj: str | bytes, as_dict: Literal[False] = False) -> str:
|
||||
... # pragma: no cover
|
||||
|
||||
@staticmethod
|
||||
def to_jwk(key_obj):
|
||||
return json.dumps(
|
||||
{
|
||||
"k": base64url_encode(force_bytes(key_obj)).decode(),
|
||||
"kty": "oct",
|
||||
}
|
||||
)
|
||||
def to_jwk(key_obj: str | bytes, as_dict: bool = False) -> Union[JWKDict, str]:
|
||||
jwk = {
|
||||
"k": base64url_encode(force_bytes(key_obj)).decode(),
|
||||
"kty": "oct",
|
||||
}
|
||||
|
||||
if as_dict:
|
||||
return jwk
|
||||
else:
|
||||
return json.dumps(jwk)
|
||||
|
||||
@staticmethod
|
||||
def from_jwk(jwk):
|
||||
def from_jwk(jwk: str | JWKDict) -> bytes:
|
||||
try:
|
||||
if isinstance(jwk, str):
|
||||
obj = json.loads(jwk)
|
||||
obj: JWKDict = json.loads(jwk)
|
||||
elif isinstance(jwk, dict):
|
||||
obj = jwk
|
||||
else:
|
||||
|
@ -219,10 +311,10 @@ class HMACAlgorithm(Algorithm):
|
|||
|
||||
return base64url_decode(obj["k"])
|
||||
|
||||
def sign(self, msg, key):
|
||||
def sign(self, msg: bytes, key: bytes) -> bytes:
|
||||
return hmac.new(key, msg, self.hash_alg).digest()
|
||||
|
||||
def verify(self, msg, key, sig):
|
||||
def verify(self, msg: bytes, key: bytes, sig: bytes) -> bool:
|
||||
return hmac.compare_digest(sig, self.sign(msg, key))
|
||||
|
||||
|
||||
|
@ -234,36 +326,49 @@ if has_crypto:
|
|||
RSASSA-PKCS-v1_5 and the specified hash function.
|
||||
"""
|
||||
|
||||
SHA256 = hashes.SHA256
|
||||
SHA384 = hashes.SHA384
|
||||
SHA512 = hashes.SHA512
|
||||
SHA256: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA256
|
||||
SHA384: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA384
|
||||
SHA512: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA512
|
||||
|
||||
def __init__(self, hash_alg):
|
||||
def __init__(self, hash_alg: type[hashes.HashAlgorithm]) -> None:
|
||||
self.hash_alg = hash_alg
|
||||
|
||||
def prepare_key(self, key):
|
||||
def prepare_key(self, key: AllowedRSAKeys | str | bytes) -> AllowedRSAKeys:
|
||||
if isinstance(key, (RSAPrivateKey, RSAPublicKey)):
|
||||
return key
|
||||
|
||||
if not isinstance(key, (bytes, str)):
|
||||
raise TypeError("Expecting a PEM-formatted key.")
|
||||
|
||||
key = force_bytes(key)
|
||||
key_bytes = force_bytes(key)
|
||||
|
||||
try:
|
||||
if key.startswith(b"ssh-rsa"):
|
||||
key = load_ssh_public_key(key)
|
||||
if key_bytes.startswith(b"ssh-rsa"):
|
||||
return cast(RSAPublicKey, load_ssh_public_key(key_bytes))
|
||||
else:
|
||||
key = load_pem_private_key(key, password=None)
|
||||
return cast(
|
||||
RSAPrivateKey, load_pem_private_key(key_bytes, password=None)
|
||||
)
|
||||
except ValueError:
|
||||
key = load_pem_public_key(key)
|
||||
return key
|
||||
return cast(RSAPublicKey, load_pem_public_key(key_bytes))
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key_obj: AllowedRSAKeys, as_dict: Literal[True]) -> JWKDict:
|
||||
... # pragma: no cover
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key_obj: AllowedRSAKeys, as_dict: Literal[False] = False) -> str:
|
||||
... # pragma: no cover
|
||||
|
||||
@staticmethod
|
||||
def to_jwk(key_obj):
|
||||
obj = None
|
||||
def to_jwk(
|
||||
key_obj: AllowedRSAKeys, as_dict: bool = False
|
||||
) -> Union[JWKDict, str]:
|
||||
obj: dict[str, Any] | None = None
|
||||
|
||||
if getattr(key_obj, "private_numbers", None):
|
||||
if hasattr(key_obj, "private_numbers"):
|
||||
# Private key
|
||||
numbers = key_obj.private_numbers()
|
||||
|
||||
|
@ -280,7 +385,7 @@ if has_crypto:
|
|||
"qi": to_base64url_uint(numbers.iqmp).decode(),
|
||||
}
|
||||
|
||||
elif getattr(key_obj, "verify", None):
|
||||
elif hasattr(key_obj, "verify"):
|
||||
# Public key
|
||||
numbers = key_obj.public_numbers()
|
||||
|
||||
|
@ -293,10 +398,13 @@ if has_crypto:
|
|||
else:
|
||||
raise InvalidKeyError("Not a public or private key")
|
||||
|
||||
return json.dumps(obj)
|
||||
if as_dict:
|
||||
return obj
|
||||
else:
|
||||
return json.dumps(obj)
|
||||
|
||||
@staticmethod
|
||||
def from_jwk(jwk):
|
||||
def from_jwk(jwk: str | JWKDict) -> AllowedRSAKeys:
|
||||
try:
|
||||
if isinstance(jwk, str):
|
||||
obj = json.loads(jwk)
|
||||
|
@ -360,19 +468,17 @@ if has_crypto:
|
|||
return numbers.private_key()
|
||||
elif "n" in obj and "e" in obj:
|
||||
# Public key
|
||||
numbers = RSAPublicNumbers(
|
||||
return RSAPublicNumbers(
|
||||
from_base64url_uint(obj["e"]),
|
||||
from_base64url_uint(obj["n"]),
|
||||
)
|
||||
|
||||
return numbers.public_key()
|
||||
).public_key()
|
||||
else:
|
||||
raise InvalidKeyError("Not a public or private key")
|
||||
|
||||
def sign(self, msg, key):
|
||||
def sign(self, msg: bytes, key: RSAPrivateKey) -> bytes:
|
||||
return key.sign(msg, padding.PKCS1v15(), self.hash_alg())
|
||||
|
||||
def verify(self, msg, key, sig):
|
||||
def verify(self, msg: bytes, key: RSAPublicKey, sig: bytes) -> bool:
|
||||
try:
|
||||
key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg())
|
||||
return True
|
||||
|
@ -385,63 +491,79 @@ if has_crypto:
|
|||
ECDSA and the specified hash function
|
||||
"""
|
||||
|
||||
SHA256 = hashes.SHA256
|
||||
SHA384 = hashes.SHA384
|
||||
SHA512 = hashes.SHA512
|
||||
SHA256: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA256
|
||||
SHA384: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA384
|
||||
SHA512: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA512
|
||||
|
||||
def __init__(self, hash_alg):
|
||||
def __init__(self, hash_alg: type[hashes.HashAlgorithm]) -> None:
|
||||
self.hash_alg = hash_alg
|
||||
|
||||
def prepare_key(self, key):
|
||||
def prepare_key(self, key: AllowedECKeys | str | bytes) -> AllowedECKeys:
|
||||
if isinstance(key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)):
|
||||
return key
|
||||
|
||||
if not isinstance(key, (bytes, str)):
|
||||
raise TypeError("Expecting a PEM-formatted key.")
|
||||
|
||||
key = force_bytes(key)
|
||||
key_bytes = force_bytes(key)
|
||||
|
||||
# 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.
|
||||
try:
|
||||
if key.startswith(b"ecdsa-sha2-"):
|
||||
key = load_ssh_public_key(key)
|
||||
if key_bytes.startswith(b"ecdsa-sha2-"):
|
||||
crypto_key = load_ssh_public_key(key_bytes)
|
||||
else:
|
||||
key = load_pem_public_key(key)
|
||||
crypto_key = load_pem_public_key(key_bytes) # type: ignore[assignment]
|
||||
except ValueError:
|
||||
key = load_pem_private_key(key, password=None)
|
||||
crypto_key = load_pem_private_key(key_bytes, password=None) # type: ignore[assignment]
|
||||
|
||||
# Explicit check the key to prevent confusing errors from cryptography
|
||||
if not isinstance(key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)):
|
||||
if not isinstance(
|
||||
crypto_key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)
|
||||
):
|
||||
raise InvalidKeyError(
|
||||
"Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for ECDSA algorithms"
|
||||
)
|
||||
|
||||
return key
|
||||
return crypto_key
|
||||
|
||||
def sign(self, msg, key):
|
||||
der_sig = key.sign(msg, ec.ECDSA(self.hash_alg()))
|
||||
def sign(self, msg: bytes, key: EllipticCurvePrivateKey) -> bytes:
|
||||
der_sig = key.sign(msg, ECDSA(self.hash_alg()))
|
||||
|
||||
return der_to_raw_signature(der_sig, key.curve)
|
||||
|
||||
def verify(self, msg, key, sig):
|
||||
def verify(self, msg: bytes, key: "AllowedECKeys", sig: bytes) -> bool:
|
||||
try:
|
||||
der_sig = raw_to_der_signature(sig, key.curve)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
try:
|
||||
if isinstance(key, EllipticCurvePrivateKey):
|
||||
key = key.public_key()
|
||||
key.verify(der_sig, msg, ec.ECDSA(self.hash_alg()))
|
||||
public_key = (
|
||||
key.public_key()
|
||||
if isinstance(key, EllipticCurvePrivateKey)
|
||||
else key
|
||||
)
|
||||
public_key.verify(der_sig, msg, ECDSA(self.hash_alg()))
|
||||
return True
|
||||
except InvalidSignature:
|
||||
return False
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key_obj):
|
||||
def to_jwk(key_obj: AllowedECKeys, as_dict: Literal[True]) -> JWKDict:
|
||||
... # pragma: no cover
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key_obj: AllowedECKeys, as_dict: Literal[False] = False) -> str:
|
||||
... # pragma: no cover
|
||||
|
||||
@staticmethod
|
||||
def to_jwk(
|
||||
key_obj: AllowedECKeys, as_dict: bool = False
|
||||
) -> Union[JWKDict, str]:
|
||||
if isinstance(key_obj, EllipticCurvePrivateKey):
|
||||
public_numbers = key_obj.public_key().public_numbers()
|
||||
elif isinstance(key_obj, EllipticCurvePublicKey):
|
||||
|
@ -449,18 +571,18 @@ if has_crypto:
|
|||
else:
|
||||
raise InvalidKeyError("Not a public or private key")
|
||||
|
||||
if isinstance(key_obj.curve, ec.SECP256R1):
|
||||
if isinstance(key_obj.curve, SECP256R1):
|
||||
crv = "P-256"
|
||||
elif isinstance(key_obj.curve, ec.SECP384R1):
|
||||
elif isinstance(key_obj.curve, SECP384R1):
|
||||
crv = "P-384"
|
||||
elif isinstance(key_obj.curve, ec.SECP521R1):
|
||||
elif isinstance(key_obj.curve, SECP521R1):
|
||||
crv = "P-521"
|
||||
elif isinstance(key_obj.curve, ec.SECP256K1):
|
||||
elif isinstance(key_obj.curve, SECP256K1):
|
||||
crv = "secp256k1"
|
||||
else:
|
||||
raise InvalidKeyError(f"Invalid curve: {key_obj.curve}")
|
||||
|
||||
obj = {
|
||||
obj: dict[str, Any] = {
|
||||
"kty": "EC",
|
||||
"crv": crv,
|
||||
"x": to_base64url_uint(public_numbers.x).decode(),
|
||||
|
@ -472,10 +594,13 @@ if has_crypto:
|
|||
key_obj.private_numbers().private_value
|
||||
).decode()
|
||||
|
||||
return json.dumps(obj)
|
||||
if as_dict:
|
||||
return obj
|
||||
else:
|
||||
return json.dumps(obj)
|
||||
|
||||
@staticmethod
|
||||
def from_jwk(jwk):
|
||||
def from_jwk(jwk: str | JWKDict) -> AllowedECKeys:
|
||||
try:
|
||||
if isinstance(jwk, str):
|
||||
obj = json.loads(jwk)
|
||||
|
@ -496,24 +621,26 @@ if has_crypto:
|
|||
y = base64url_decode(obj.get("y"))
|
||||
|
||||
curve = obj.get("crv")
|
||||
curve_obj: EllipticCurve
|
||||
|
||||
if curve == "P-256":
|
||||
if len(x) == len(y) == 32:
|
||||
curve_obj = ec.SECP256R1()
|
||||
curve_obj = SECP256R1()
|
||||
else:
|
||||
raise InvalidKeyError("Coords should be 32 bytes for curve P-256")
|
||||
elif curve == "P-384":
|
||||
if len(x) == len(y) == 48:
|
||||
curve_obj = ec.SECP384R1()
|
||||
curve_obj = SECP384R1()
|
||||
else:
|
||||
raise InvalidKeyError("Coords should be 48 bytes for curve P-384")
|
||||
elif curve == "P-521":
|
||||
if len(x) == len(y) == 66:
|
||||
curve_obj = ec.SECP521R1()
|
||||
curve_obj = SECP521R1()
|
||||
else:
|
||||
raise InvalidKeyError("Coords should be 66 bytes for curve P-521")
|
||||
elif curve == "secp256k1":
|
||||
if len(x) == len(y) == 32:
|
||||
curve_obj = ec.SECP256K1()
|
||||
curve_obj = SECP256K1()
|
||||
else:
|
||||
raise InvalidKeyError(
|
||||
"Coords should be 32 bytes for curve secp256k1"
|
||||
|
@ -521,7 +648,7 @@ if has_crypto:
|
|||
else:
|
||||
raise InvalidKeyError(f"Invalid curve: {curve}")
|
||||
|
||||
public_numbers = ec.EllipticCurvePublicNumbers(
|
||||
public_numbers = EllipticCurvePublicNumbers(
|
||||
x=int.from_bytes(x, byteorder="big"),
|
||||
y=int.from_bytes(y, byteorder="big"),
|
||||
curve=curve_obj,
|
||||
|
@ -536,7 +663,7 @@ if has_crypto:
|
|||
"D should be {} bytes for curve {}", len(x), curve
|
||||
)
|
||||
|
||||
return ec.EllipticCurvePrivateNumbers(
|
||||
return EllipticCurvePrivateNumbers(
|
||||
int.from_bytes(d, byteorder="big"), public_numbers
|
||||
).private_key()
|
||||
|
||||
|
@ -545,24 +672,24 @@ if has_crypto:
|
|||
Performs a signature using RSASSA-PSS with MGF1
|
||||
"""
|
||||
|
||||
def sign(self, msg, key):
|
||||
def sign(self, msg: bytes, key: RSAPrivateKey) -> bytes:
|
||||
return key.sign(
|
||||
msg,
|
||||
padding.PSS(
|
||||
mgf=padding.MGF1(self.hash_alg()),
|
||||
salt_length=self.hash_alg.digest_size,
|
||||
salt_length=self.hash_alg().digest_size,
|
||||
),
|
||||
self.hash_alg(),
|
||||
)
|
||||
|
||||
def verify(self, msg, key, sig):
|
||||
def verify(self, msg: bytes, key: RSAPublicKey, sig: bytes) -> bool:
|
||||
try:
|
||||
key.verify(
|
||||
sig,
|
||||
msg,
|
||||
padding.PSS(
|
||||
mgf=padding.MGF1(self.hash_alg()),
|
||||
salt_length=self.hash_alg.digest_size,
|
||||
salt_length=self.hash_alg().digest_size,
|
||||
),
|
||||
self.hash_alg(),
|
||||
)
|
||||
|
@ -577,21 +704,20 @@ if has_crypto:
|
|||
This class requires ``cryptography>=2.6`` to be installed.
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
pass
|
||||
|
||||
def prepare_key(self, key):
|
||||
def prepare_key(self, key: AllowedOKPKeys | str | bytes) -> AllowedOKPKeys:
|
||||
if isinstance(key, (bytes, str)):
|
||||
if isinstance(key, str):
|
||||
key = key.encode("utf-8")
|
||||
str_key = key.decode("utf-8")
|
||||
key_str = key.decode("utf-8") if isinstance(key, bytes) else key
|
||||
key_bytes = key.encode("utf-8") if isinstance(key, str) else key
|
||||
|
||||
if "-----BEGIN PUBLIC" in str_key:
|
||||
key = load_pem_public_key(key)
|
||||
elif "-----BEGIN PRIVATE" in str_key:
|
||||
key = load_pem_private_key(key, password=None)
|
||||
elif str_key[0:4] == "ssh-":
|
||||
key = load_ssh_public_key(key)
|
||||
if "-----BEGIN PUBLIC" in key_str:
|
||||
key = load_pem_public_key(key_bytes) # type: ignore[assignment]
|
||||
elif "-----BEGIN PRIVATE" in key_str:
|
||||
key = load_pem_private_key(key_bytes, password=None) # type: ignore[assignment]
|
||||
elif key_str[0:4] == "ssh-":
|
||||
key = load_ssh_public_key(key_bytes) # type: ignore[assignment]
|
||||
|
||||
# Explicit check the key to prevent confusing errors from cryptography
|
||||
if not isinstance(
|
||||
|
@ -604,7 +730,9 @@ if has_crypto:
|
|||
|
||||
return key
|
||||
|
||||
def sign(self, msg, key):
|
||||
def sign(
|
||||
self, msg: str | bytes, key: Ed25519PrivateKey | Ed448PrivateKey
|
||||
) -> bytes:
|
||||
"""
|
||||
Sign a message ``msg`` using the EdDSA private key ``key``
|
||||
:param str|bytes msg: Message to sign
|
||||
|
@ -612,10 +740,12 @@ if has_crypto:
|
|||
or :class:`.Ed448PrivateKey` isinstance
|
||||
:return bytes signature: The signature, as bytes
|
||||
"""
|
||||
msg = bytes(msg, "utf-8") if type(msg) is not bytes else msg
|
||||
return key.sign(msg)
|
||||
msg_bytes = msg.encode("utf-8") if isinstance(msg, str) else msg
|
||||
return key.sign(msg_bytes)
|
||||
|
||||
def verify(self, msg, key, sig):
|
||||
def verify(
|
||||
self, msg: str | bytes, key: AllowedOKPKeys, sig: str | bytes
|
||||
) -> bool:
|
||||
"""
|
||||
Verify a given ``msg`` against a signature ``sig`` using the EdDSA key ``key``
|
||||
|
||||
|
@ -626,31 +756,48 @@ if has_crypto:
|
|||
:return bool verified: True if signature is valid, False if not.
|
||||
"""
|
||||
try:
|
||||
msg = bytes(msg, "utf-8") if type(msg) is not bytes else msg
|
||||
sig = bytes(sig, "utf-8") if type(sig) is not bytes else sig
|
||||
msg_bytes = msg.encode("utf-8") if isinstance(msg, str) else msg
|
||||
sig_bytes = sig.encode("utf-8") if isinstance(sig, str) else sig
|
||||
|
||||
if isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)):
|
||||
key = key.public_key()
|
||||
key.verify(sig, msg)
|
||||
public_key = (
|
||||
key.public_key()
|
||||
if isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey))
|
||||
else key
|
||||
)
|
||||
public_key.verify(sig_bytes, msg_bytes)
|
||||
return True # If no exception was raised, the signature is valid.
|
||||
except cryptography.exceptions.InvalidSignature:
|
||||
except InvalidSignature:
|
||||
return False
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key):
|
||||
def to_jwk(key: AllowedOKPKeys, as_dict: Literal[True]) -> JWKDict:
|
||||
... # pragma: no cover
|
||||
|
||||
@overload
|
||||
@staticmethod
|
||||
def to_jwk(key: AllowedOKPKeys, as_dict: Literal[False] = False) -> str:
|
||||
... # pragma: no cover
|
||||
|
||||
@staticmethod
|
||||
def to_jwk(key: AllowedOKPKeys, as_dict: bool = False) -> Union[JWKDict, str]:
|
||||
if isinstance(key, (Ed25519PublicKey, Ed448PublicKey)):
|
||||
x = key.public_bytes(
|
||||
encoding=Encoding.Raw,
|
||||
format=PublicFormat.Raw,
|
||||
)
|
||||
crv = "Ed25519" if isinstance(key, Ed25519PublicKey) else "Ed448"
|
||||
return json.dumps(
|
||||
{
|
||||
"x": base64url_encode(force_bytes(x)).decode(),
|
||||
"kty": "OKP",
|
||||
"crv": crv,
|
||||
}
|
||||
)
|
||||
|
||||
obj = {
|
||||
"x": base64url_encode(force_bytes(x)).decode(),
|
||||
"kty": "OKP",
|
||||
"crv": crv,
|
||||
}
|
||||
|
||||
if as_dict:
|
||||
return obj
|
||||
else:
|
||||
return json.dumps(obj)
|
||||
|
||||
if isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)):
|
||||
d = key.private_bytes(
|
||||
|
@ -665,19 +812,22 @@ if has_crypto:
|
|||
)
|
||||
|
||||
crv = "Ed25519" if isinstance(key, Ed25519PrivateKey) else "Ed448"
|
||||
return json.dumps(
|
||||
{
|
||||
"x": base64url_encode(force_bytes(x)).decode(),
|
||||
"d": base64url_encode(force_bytes(d)).decode(),
|
||||
"kty": "OKP",
|
||||
"crv": crv,
|
||||
}
|
||||
)
|
||||
obj = {
|
||||
"x": base64url_encode(force_bytes(x)).decode(),
|
||||
"d": base64url_encode(force_bytes(d)).decode(),
|
||||
"kty": "OKP",
|
||||
"crv": crv,
|
||||
}
|
||||
|
||||
if as_dict:
|
||||
return obj
|
||||
else:
|
||||
return json.dumps(obj)
|
||||
|
||||
raise InvalidKeyError("Not a public or private key")
|
||||
|
||||
@staticmethod
|
||||
def from_jwk(jwk):
|
||||
def from_jwk(jwk: str | JWKDict) -> AllowedOKPKeys:
|
||||
try:
|
||||
if isinstance(jwk, str):
|
||||
obj = json.loads(jwk)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue