cmac.py 2.1 KB

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