hmac.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.
  4. from cryptography import utils
  5. from cryptography.exceptions import (
  6. AlreadyFinalized,
  7. UnsupportedAlgorithm,
  8. _Reasons,
  9. )
  10. from cryptography.hazmat.backends import _get_backend
  11. from cryptography.hazmat.backends.interfaces import HMACBackend
  12. from cryptography.hazmat.primitives import hashes
  13. class HMAC(hashes.HashContext):
  14. def __init__(
  15. self,
  16. key: bytes,
  17. algorithm: hashes.HashAlgorithm,
  18. backend=None,
  19. ctx=None,
  20. ):
  21. backend = _get_backend(backend)
  22. if not isinstance(backend, HMACBackend):
  23. raise UnsupportedAlgorithm(
  24. "Backend object does not implement HMACBackend.",
  25. _Reasons.BACKEND_MISSING_INTERFACE,
  26. )
  27. if not isinstance(algorithm, hashes.HashAlgorithm):
  28. raise TypeError("Expected instance of hashes.HashAlgorithm.")
  29. self._algorithm = algorithm
  30. self._backend = backend
  31. self._key = key
  32. if ctx is None:
  33. self._ctx = self._backend.create_hmac_ctx(key, self.algorithm)
  34. else:
  35. self._ctx = ctx
  36. algorithm = utils.read_only_property("_algorithm")
  37. def update(self, data: bytes) -> None:
  38. if self._ctx is None:
  39. raise AlreadyFinalized("Context was already finalized.")
  40. utils._check_byteslike("data", data)
  41. self._ctx.update(data)
  42. def copy(self) -> "HMAC":
  43. if self._ctx is None:
  44. raise AlreadyFinalized("Context was already finalized.")
  45. return HMAC(
  46. self._key,
  47. self.algorithm,
  48. backend=self._backend,
  49. ctx=self._ctx.copy(),
  50. )
  51. def finalize(self) -> bytes:
  52. if self._ctx is None:
  53. raise AlreadyFinalized("Context was already finalized.")
  54. digest = self._ctx.finalize()
  55. self._ctx = None
  56. return digest
  57. def verify(self, signature: bytes) -> None:
  58. utils._check_bytes("signature", signature)
  59. if self._ctx is None:
  60. raise AlreadyFinalized("Context was already finalized.")
  61. ctx, self._ctx = self._ctx, None
  62. ctx.verify(signature)