cmac.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 CMACBackend
  13. from cryptography.hazmat.primitives import ciphers
  14. class CMAC(object):
  15. def __init__(self, algorithm, backend=None, ctx=None):
  16. backend = _get_backend(backend)
  17. if not isinstance(backend, CMACBackend):
  18. raise UnsupportedAlgorithm(
  19. "Backend object does not implement CMACBackend.",
  20. _Reasons.BACKEND_MISSING_INTERFACE,
  21. )
  22. if not isinstance(algorithm, ciphers.BlockCipherAlgorithm):
  23. raise TypeError("Expected instance of BlockCipherAlgorithm.")
  24. self._algorithm = algorithm
  25. self._backend = backend
  26. if ctx is None:
  27. self._ctx = self._backend.create_cmac_ctx(self._algorithm)
  28. else:
  29. self._ctx = ctx
  30. def update(self, data):
  31. if self._ctx is None:
  32. raise AlreadyFinalized("Context was already finalized.")
  33. utils._check_bytes("data", data)
  34. self._ctx.update(data)
  35. def finalize(self):
  36. if self._ctx is None:
  37. raise AlreadyFinalized("Context was already finalized.")
  38. digest = self._ctx.finalize()
  39. self._ctx = None
  40. return digest
  41. def verify(self, signature):
  42. utils._check_bytes("signature", signature)
  43. if self._ctx is None:
  44. raise AlreadyFinalized("Context was already finalized.")
  45. ctx, self._ctx = self._ctx, None
  46. ctx.verify(signature)
  47. def copy(self):
  48. if self._ctx is None:
  49. raise AlreadyFinalized("Context was already finalized.")
  50. return CMAC(
  51. self._algorithm, backend=self._backend, ctx=self._ctx.copy()
  52. )