summaryrefslogtreecommitdiff
path: root/jwt/algorithms.py
diff options
context:
space:
mode:
Diffstat (limited to 'jwt/algorithms.py')
-rw-r--r--jwt/algorithms.py23
1 files changed, 23 insertions, 0 deletions
diff --git a/jwt/algorithms.py b/jwt/algorithms.py
index 93fadf4..4fae441 100644
--- a/jwt/algorithms.py
+++ b/jwt/algorithms.py
@@ -18,6 +18,7 @@ from .utils import (
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.ec import (
@@ -111,6 +112,28 @@ class Algorithm:
The interface for an algorithm used to sign and verify tokens.
"""
+ 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 digest.finalize()
+ else:
+ return hash_alg(bytestr).digest()
+
def prepare_key(self, key):
"""
Performs necessary validation and conversions on the key and returns