poly1305.py 2.4 KB

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