Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/cryptography/hazmat/primitives/hmac.py: 80%
40 statements
« prev ^ index » next coverage.py v7.2.1, created at 2023-03-14 06:36 +0000
« prev ^ index » next coverage.py v7.2.1, created at 2023-03-14 06:36 +0000
1# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
6import typing
8from cryptography import utils
9from cryptography.exceptions import AlreadyFinalized
10from cryptography.hazmat.backends.openssl.hmac import _HMACContext
11from cryptography.hazmat.primitives import hashes
14class HMAC(hashes.HashContext):
15 _ctx: typing.Optional[_HMACContext]
17 def __init__(
18 self,
19 key: bytes,
20 algorithm: hashes.HashAlgorithm,
21 backend: typing.Any = None,
22 ctx=None,
23 ):
24 if not isinstance(algorithm, hashes.HashAlgorithm):
25 raise TypeError("Expected instance of hashes.HashAlgorithm.")
26 self._algorithm = algorithm
28 self._key = key
29 if ctx is None:
30 from cryptography.hazmat.backends.openssl.backend import (
31 backend as ossl,
32 )
34 self._ctx = ossl.create_hmac_ctx(key, self.algorithm)
35 else:
36 self._ctx = ctx
38 @property
39 def algorithm(self) -> hashes.HashAlgorithm:
40 return self._algorithm
42 def update(self, data: bytes) -> None:
43 if self._ctx is None:
44 raise AlreadyFinalized("Context was already finalized.")
45 utils._check_byteslike("data", data)
46 self._ctx.update(data)
48 def copy(self) -> "HMAC":
49 if self._ctx is None:
50 raise AlreadyFinalized("Context was already finalized.")
51 return HMAC(
52 self._key,
53 self.algorithm,
54 ctx=self._ctx.copy(),
55 )
57 def finalize(self) -> bytes:
58 if self._ctx is None:
59 raise AlreadyFinalized("Context was already finalized.")
60 digest = self._ctx.finalize()
61 self._ctx = None
62 return digest
64 def verify(self, signature: bytes) -> None:
65 utils._check_bytes("signature", signature)
66 if self._ctx is None:
67 raise AlreadyFinalized("Context was already finalized.")
69 ctx, self._ctx = self._ctx, None
70 ctx.verify(signature)