poly1305.py 1.6 KB

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