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