Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmac.py 2.0KB

1 year ago
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 __future__ import annotations
  5. import typing
  6. from cryptography import utils
  7. from cryptography.exceptions import AlreadyFinalized
  8. from cryptography.hazmat.primitives import ciphers
  9. if typing.TYPE_CHECKING:
  10. from cryptography.hazmat.backends.openssl.cmac import _CMACContext
  11. class CMAC:
  12. _ctx: typing.Optional[_CMACContext]
  13. _algorithm: ciphers.BlockCipherAlgorithm
  14. def __init__(
  15. self,
  16. algorithm: ciphers.BlockCipherAlgorithm,
  17. backend: typing.Any = None,
  18. ctx: typing.Optional[_CMACContext] = None,
  19. ) -> None:
  20. if not isinstance(algorithm, ciphers.BlockCipherAlgorithm):
  21. raise TypeError("Expected instance of BlockCipherAlgorithm.")
  22. self._algorithm = algorithm
  23. if ctx is None:
  24. from cryptography.hazmat.backends.openssl.backend import (
  25. backend as ossl,
  26. )
  27. self._ctx = ossl.create_cmac_ctx(self._algorithm)
  28. else:
  29. self._ctx = ctx
  30. def update(self, data: bytes) -> None:
  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) -> bytes:
  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: bytes) -> None:
  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) -> CMAC:
  48. if self._ctx is None:
  49. raise AlreadyFinalized("Context was already finalized.")
  50. return CMAC(self._algorithm, ctx=self._ctx.copy())