You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

67 line
2.1 KiB

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