poly1305.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.openssl.poly1305 import _Poly1305Context
  12. class Poly1305:
  13. _ctx: typing.Optional[_Poly1305Context]
  14. def __init__(self, key: bytes):
  15. from cryptography.hazmat.backends.openssl.backend import backend
  16. if not backend.poly1305_supported():
  17. raise UnsupportedAlgorithm(
  18. "poly1305 is not supported by this version of OpenSSL.",
  19. _Reasons.UNSUPPORTED_MAC,
  20. )
  21. self._ctx = backend.create_poly1305_ctx(key)
  22. def update(self, data: bytes) -> None:
  23. if self._ctx is None:
  24. raise AlreadyFinalized("Context was already finalized.")
  25. utils._check_byteslike("data", data)
  26. self._ctx.update(data)
  27. def finalize(self) -> bytes:
  28. if self._ctx is None:
  29. raise AlreadyFinalized("Context was already finalized.")
  30. mac = self._ctx.finalize()
  31. self._ctx = None
  32. return mac
  33. def verify(self, tag: bytes) -> None:
  34. utils._check_bytes("tag", tag)
  35. if self._ctx is None:
  36. raise AlreadyFinalized("Context was already finalized.")
  37. ctx, self._ctx = self._ctx, None
  38. ctx.verify(tag)
  39. @classmethod
  40. def generate_tag(cls, key: bytes, data: bytes) -> bytes:
  41. p = Poly1305(key)
  42. p.update(data)
  43. return p.finalize()
  44. @classmethod
  45. def verify_tag(cls, key: bytes, data: bytes, tag: bytes) -> None:
  46. p = Poly1305(key)
  47. p.update(data)
  48. p.verify(tag)