Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

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