poly1305.py 2.3 KB

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