poly1305.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.exceptions import InvalidSignature
  6. from cryptography.hazmat.primitives import constant_time
  7. _POLY1305_TAG_SIZE = 16
  8. _POLY1305_KEY_SIZE = 32
  9. if typing.TYPE_CHECKING:
  10. from cryptography.hazmat.backends.openssl.backend import Backend
  11. class _Poly1305Context:
  12. def __init__(self, backend: "Backend", key: bytes) -> None:
  13. self._backend = backend
  14. key_ptr = self._backend._ffi.from_buffer(key)
  15. # This function copies the key into OpenSSL-owned memory so we don't
  16. # need to retain it ourselves
  17. evp_pkey = self._backend._lib.EVP_PKEY_new_raw_private_key(
  18. self._backend._lib.NID_poly1305,
  19. self._backend._ffi.NULL,
  20. key_ptr,
  21. len(key),
  22. )
  23. self._backend.openssl_assert(evp_pkey != self._backend._ffi.NULL)
  24. self._evp_pkey = self._backend._ffi.gc(
  25. evp_pkey, self._backend._lib.EVP_PKEY_free
  26. )
  27. ctx = self._backend._lib.EVP_MD_CTX_new()
  28. self._backend.openssl_assert(ctx != self._backend._ffi.NULL)
  29. self._ctx = self._backend._ffi.gc(
  30. ctx, self._backend._lib.EVP_MD_CTX_free
  31. )
  32. res = self._backend._lib.EVP_DigestSignInit(
  33. self._ctx,
  34. self._backend._ffi.NULL,
  35. self._backend._ffi.NULL,
  36. self._backend._ffi.NULL,
  37. self._evp_pkey,
  38. )
  39. self._backend.openssl_assert(res == 1)
  40. def update(self, data: bytes) -> None:
  41. data_ptr = self._backend._ffi.from_buffer(data)
  42. res = self._backend._lib.EVP_DigestSignUpdate(
  43. self._ctx, data_ptr, len(data)
  44. )
  45. self._backend.openssl_assert(res != 0)
  46. def finalize(self) -> bytes:
  47. buf = self._backend._ffi.new("unsigned char[]", _POLY1305_TAG_SIZE)
  48. outlen = self._backend._ffi.new("size_t *", _POLY1305_TAG_SIZE)
  49. res = self._backend._lib.EVP_DigestSignFinal(self._ctx, buf, outlen)
  50. self._backend.openssl_assert(res != 0)
  51. self._backend.openssl_assert(outlen[0] == _POLY1305_TAG_SIZE)
  52. return self._backend._ffi.buffer(buf)[: outlen[0]]
  53. def verify(self, tag: bytes) -> None:
  54. mac = self.finalize()
  55. if not constant_time.bytes_eq(mac, tag):
  56. raise InvalidSignature("Value did not match computed tag.")