Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/cryptography/hazmat/primitives/hmac.py: 45%
40 statements
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +0000
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +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 (
10 AlreadyFinalized,
11)
12from cryptography.hazmat.backends.openssl.hmac import _HMACContext
13from cryptography.hazmat.primitives import hashes
16class HMAC(hashes.HashContext):
17 _ctx: typing.Optional[_HMACContext]
19 def __init__(
20 self,
21 key: bytes,
22 algorithm: hashes.HashAlgorithm,
23 backend: typing.Any = None,
24 ctx=None,
25 ):
26 if not isinstance(algorithm, hashes.HashAlgorithm):
27 raise TypeError("Expected instance of hashes.HashAlgorithm.")
28 self._algorithm = algorithm
30 self._key = key
31 if ctx is None:
32 from cryptography.hazmat.backends.openssl.backend import (
33 backend as ossl,
34 )
36 self._ctx = ossl.create_hmac_ctx(key, self.algorithm)
37 else:
38 self._ctx = ctx
40 @property
41 def algorithm(self) -> hashes.HashAlgorithm:
42 return self._algorithm
44 def update(self, data: bytes) -> None:
45 if self._ctx is None:
46 raise AlreadyFinalized("Context was already finalized.")
47 utils._check_byteslike("data", data)
48 self._ctx.update(data)
50 def copy(self) -> "HMAC":
51 if self._ctx is None:
52 raise AlreadyFinalized("Context was already finalized.")
53 return HMAC(
54 self._key,
55 self.algorithm,
56 ctx=self._ctx.copy(),
57 )
59 def finalize(self) -> bytes:
60 if self._ctx is None:
61 raise AlreadyFinalized("Context was already finalized.")
62 digest = self._ctx.finalize()
63 self._ctx = None
64 return digest
66 def verify(self, signature: bytes) -> None:
67 utils._check_bytes("signature", signature)
68 if self._ctx is None:
69 raise AlreadyFinalized("Context was already finalized.")
71 ctx, self._ctx = self._ctx, None
72 ctx.verify(signature)