cmac.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. )
  9. from cryptography.hazmat.primitives import ciphers
  10. if typing.TYPE_CHECKING:
  11. from cryptography.hazmat.backends.openssl.cmac import _CMACContext
  12. class CMAC:
  13. _ctx: typing.Optional["_CMACContext"]
  14. _algorithm: ciphers.BlockCipherAlgorithm
  15. def __init__(
  16. self,
  17. algorithm: ciphers.BlockCipherAlgorithm,
  18. backend: typing.Any = None,
  19. ctx: typing.Optional["_CMACContext"] = None,
  20. ):
  21. if not isinstance(algorithm, ciphers.BlockCipherAlgorithm):
  22. raise TypeError("Expected instance of BlockCipherAlgorithm.")
  23. self._algorithm = algorithm
  24. if ctx is None:
  25. from cryptography.hazmat.backends.openssl.backend import (
  26. backend as ossl,
  27. )
  28. self._ctx = ossl.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(self._algorithm, ctx=self._ctx.copy())