hmac.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 import utils
  5. from cryptography.exceptions import (
  6. InvalidSignature,
  7. UnsupportedAlgorithm,
  8. _Reasons,
  9. )
  10. from cryptography.hazmat.primitives import constant_time, hashes
  11. class _HMACContext(hashes.HashContext):
  12. def __init__(
  13. self, backend, key: bytes, algorithm: hashes.HashAlgorithm, ctx=None
  14. ):
  15. self._algorithm = algorithm
  16. self._backend = backend
  17. if ctx is None:
  18. ctx = self._backend._lib.HMAC_CTX_new()
  19. self._backend.openssl_assert(ctx != self._backend._ffi.NULL)
  20. ctx = self._backend._ffi.gc(ctx, self._backend._lib.HMAC_CTX_free)
  21. evp_md = self._backend._evp_md_from_algorithm(algorithm)
  22. if evp_md == self._backend._ffi.NULL:
  23. raise UnsupportedAlgorithm(
  24. "{} is not a supported hash on this backend".format(
  25. algorithm.name
  26. ),
  27. _Reasons.UNSUPPORTED_HASH,
  28. )
  29. key_ptr = self._backend._ffi.from_buffer(key)
  30. res = self._backend._lib.HMAC_Init_ex(
  31. ctx, key_ptr, len(key), evp_md, self._backend._ffi.NULL
  32. )
  33. self._backend.openssl_assert(res != 0)
  34. self._ctx = ctx
  35. self._key = key
  36. algorithm = utils.read_only_property("_algorithm")
  37. def copy(self) -> "_HMACContext":
  38. copied_ctx = self._backend._lib.HMAC_CTX_new()
  39. self._backend.openssl_assert(copied_ctx != self._backend._ffi.NULL)
  40. copied_ctx = self._backend._ffi.gc(
  41. copied_ctx, self._backend._lib.HMAC_CTX_free
  42. )
  43. res = self._backend._lib.HMAC_CTX_copy(copied_ctx, self._ctx)
  44. self._backend.openssl_assert(res != 0)
  45. return _HMACContext(
  46. self._backend, self._key, self.algorithm, ctx=copied_ctx
  47. )
  48. def update(self, data: bytes) -> None:
  49. data_ptr = self._backend._ffi.from_buffer(data)
  50. res = self._backend._lib.HMAC_Update(self._ctx, data_ptr, len(data))
  51. self._backend.openssl_assert(res != 0)
  52. def finalize(self) -> bytes:
  53. buf = self._backend._ffi.new(
  54. "unsigned char[]", self._backend._lib.EVP_MAX_MD_SIZE
  55. )
  56. outlen = self._backend._ffi.new("unsigned int *")
  57. res = self._backend._lib.HMAC_Final(self._ctx, buf, outlen)
  58. self._backend.openssl_assert(res != 0)
  59. self._backend.openssl_assert(outlen[0] == self.algorithm.digest_size)
  60. return self._backend._ffi.buffer(buf)[: outlen[0]]
  61. def verify(self, signature: bytes) -> None:
  62. digest = self.finalize()
  63. if not constant_time.bytes_eq(digest, signature):
  64. raise InvalidSignature("Signature did not match digest.")