hmac.py 2.3 KB

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