hmac.py 2.4 KB

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