1import hashlib
2import hmac
3import os
4
5from jose.backends.base import Key
6from jose.constants import ALGORITHMS
7from jose.exceptions import JWKError
8from jose.utils import base64url_decode, base64url_encode, is_pem_format, is_ssh_key
9
10
11def get_random_bytes(num_bytes):
12 return bytes(os.urandom(num_bytes))
13
14
15class HMACKey(Key):
16 """
17 Performs signing and verification operations using HMAC
18 and the specified hash function.
19 """
20
21 HASHES = {ALGORITHMS.HS256: hashlib.sha256, ALGORITHMS.HS384: hashlib.sha384, ALGORITHMS.HS512: hashlib.sha512}
22
23 def __init__(self, key, algorithm):
24 if algorithm not in ALGORITHMS.HMAC:
25 raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm)
26 self._algorithm = algorithm
27 self._hash_alg = self.HASHES.get(algorithm)
28
29 if isinstance(key, dict):
30 self.prepared_key = self._process_jwk(key)
31 return
32
33 if not isinstance(key, str) and not isinstance(key, bytes):
34 raise JWKError("Expecting a string- or bytes-formatted key.")
35
36 if isinstance(key, str):
37 key = key.encode("utf-8")
38
39 if is_pem_format(key) or is_ssh_key(key):
40 raise JWKError(
41 "The specified key is an asymmetric key or x509 certificate and"
42 " should not be used as an HMAC secret."
43 )
44
45 self.prepared_key = key
46
47 def _process_jwk(self, jwk_dict):
48 if not jwk_dict.get("kty") == "oct":
49 raise JWKError("Incorrect key type. Expected: 'oct', Received: %s" % jwk_dict.get("kty"))
50
51 k = jwk_dict.get("k")
52 k = k.encode("utf-8")
53 k = bytes(k)
54 k = base64url_decode(k)
55
56 return k
57
58 def sign(self, msg):
59 return hmac.new(self.prepared_key, msg, self._hash_alg).digest()
60
61 def verify(self, msg, sig):
62 return hmac.compare_digest(sig, self.sign(msg))
63
64 def to_dict(self):
65 return {
66 "alg": self._algorithm,
67 "kty": "oct",
68 "k": base64url_encode(self.prepared_key).decode("ASCII"),
69 }