ec.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.backends.openssl.utils import (
  11. _calculate_digest_and_algorithm,
  12. _check_not_prehashed,
  13. _evp_pkey_derive,
  14. _warn_sign_verify_deprecated,
  15. )
  16. from cryptography.hazmat.primitives import hashes, serialization
  17. from cryptography.hazmat.primitives.asymmetric import (
  18. AsymmetricSignatureContext,
  19. AsymmetricVerificationContext,
  20. ec,
  21. )
  22. def _check_signature_algorithm(
  23. signature_algorithm: ec.EllipticCurveSignatureAlgorithm,
  24. ):
  25. if not isinstance(signature_algorithm, ec.ECDSA):
  26. raise UnsupportedAlgorithm(
  27. "Unsupported elliptic curve signature algorithm.",
  28. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  29. )
  30. def _ec_key_curve_sn(backend, ec_key):
  31. group = backend._lib.EC_KEY_get0_group(ec_key)
  32. backend.openssl_assert(group != backend._ffi.NULL)
  33. nid = backend._lib.EC_GROUP_get_curve_name(group)
  34. # The following check is to find EC keys with unnamed curves and raise
  35. # an error for now.
  36. if nid == backend._lib.NID_undef:
  37. raise NotImplementedError(
  38. "ECDSA keys with unnamed curves are unsupported at this time"
  39. )
  40. # This is like the above check, but it also catches the case where you
  41. # explicitly encoded a curve with the same parameters as a named curve.
  42. # Don't do that.
  43. if (
  44. not backend._lib.CRYPTOGRAPHY_IS_LIBRESSL
  45. and backend._lib.EC_GROUP_get_asn1_flag(group) == 0
  46. ):
  47. raise NotImplementedError(
  48. "ECDSA keys with unnamed curves are unsupported at this time"
  49. )
  50. curve_name = backend._lib.OBJ_nid2sn(nid)
  51. backend.openssl_assert(curve_name != backend._ffi.NULL)
  52. sn = backend._ffi.string(curve_name).decode("ascii")
  53. return sn
  54. def _mark_asn1_named_ec_curve(backend, ec_cdata):
  55. """
  56. Set the named curve flag on the EC_KEY. This causes OpenSSL to
  57. serialize EC keys along with their curve OID which makes
  58. deserialization easier.
  59. """
  60. backend._lib.EC_KEY_set_asn1_flag(
  61. ec_cdata, backend._lib.OPENSSL_EC_NAMED_CURVE
  62. )
  63. def _sn_to_elliptic_curve(backend, sn):
  64. try:
  65. return ec._CURVE_TYPES[sn]()
  66. except KeyError:
  67. raise UnsupportedAlgorithm(
  68. "{} is not a supported elliptic curve".format(sn),
  69. _Reasons.UNSUPPORTED_ELLIPTIC_CURVE,
  70. )
  71. def _ecdsa_sig_sign(backend, private_key, data):
  72. max_size = backend._lib.ECDSA_size(private_key._ec_key)
  73. backend.openssl_assert(max_size > 0)
  74. sigbuf = backend._ffi.new("unsigned char[]", max_size)
  75. siglen_ptr = backend._ffi.new("unsigned int[]", 1)
  76. res = backend._lib.ECDSA_sign(
  77. 0, data, len(data), sigbuf, siglen_ptr, private_key._ec_key
  78. )
  79. backend.openssl_assert(res == 1)
  80. return backend._ffi.buffer(sigbuf)[: siglen_ptr[0]]
  81. def _ecdsa_sig_verify(backend, public_key, signature, data):
  82. res = backend._lib.ECDSA_verify(
  83. 0, data, len(data), signature, len(signature), public_key._ec_key
  84. )
  85. if res != 1:
  86. backend._consume_errors()
  87. raise InvalidSignature
  88. class _ECDSASignatureContext(AsymmetricSignatureContext):
  89. def __init__(
  90. self,
  91. backend,
  92. private_key: ec.EllipticCurvePrivateKey,
  93. algorithm: hashes.HashAlgorithm,
  94. ):
  95. self._backend = backend
  96. self._private_key = private_key
  97. self._digest = hashes.Hash(algorithm, backend)
  98. def update(self, data: bytes) -> None:
  99. self._digest.update(data)
  100. def finalize(self) -> bytes:
  101. digest = self._digest.finalize()
  102. return _ecdsa_sig_sign(self._backend, self._private_key, digest)
  103. class _ECDSAVerificationContext(AsymmetricVerificationContext):
  104. def __init__(
  105. self,
  106. backend,
  107. public_key: ec.EllipticCurvePublicKey,
  108. signature: bytes,
  109. algorithm: hashes.HashAlgorithm,
  110. ):
  111. self._backend = backend
  112. self._public_key = public_key
  113. self._signature = signature
  114. self._digest = hashes.Hash(algorithm, backend)
  115. def update(self, data: bytes) -> None:
  116. self._digest.update(data)
  117. def verify(self) -> None:
  118. digest = self._digest.finalize()
  119. _ecdsa_sig_verify(
  120. self._backend, self._public_key, self._signature, digest
  121. )
  122. class _EllipticCurvePrivateKey(ec.EllipticCurvePrivateKey):
  123. def __init__(self, backend, ec_key_cdata, evp_pkey):
  124. self._backend = backend
  125. self._ec_key = ec_key_cdata
  126. self._evp_pkey = evp_pkey
  127. sn = _ec_key_curve_sn(backend, ec_key_cdata)
  128. self._curve = _sn_to_elliptic_curve(backend, sn)
  129. _mark_asn1_named_ec_curve(backend, ec_key_cdata)
  130. curve = utils.read_only_property("_curve")
  131. @property
  132. def key_size(self) -> int:
  133. return self.curve.key_size
  134. def signer(
  135. self, signature_algorithm: ec.EllipticCurveSignatureAlgorithm
  136. ) -> AsymmetricSignatureContext:
  137. _warn_sign_verify_deprecated()
  138. _check_signature_algorithm(signature_algorithm)
  139. _check_not_prehashed(signature_algorithm.algorithm)
  140. # This assert is to help mypy realize what type this object holds
  141. assert isinstance(signature_algorithm.algorithm, hashes.HashAlgorithm)
  142. return _ECDSASignatureContext(
  143. self._backend, self, signature_algorithm.algorithm
  144. )
  145. def exchange(
  146. self, algorithm: ec.ECDH, peer_public_key: ec.EllipticCurvePublicKey
  147. ) -> bytes:
  148. if not (
  149. self._backend.elliptic_curve_exchange_algorithm_supported(
  150. algorithm, self.curve
  151. )
  152. ):
  153. raise UnsupportedAlgorithm(
  154. "This backend does not support the ECDH algorithm.",
  155. _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
  156. )
  157. if peer_public_key.curve.name != self.curve.name:
  158. raise ValueError(
  159. "peer_public_key and self are not on the same curve"
  160. )
  161. return _evp_pkey_derive(self._backend, self._evp_pkey, peer_public_key)
  162. def public_key(self) -> ec.EllipticCurvePublicKey:
  163. group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
  164. self._backend.openssl_assert(group != self._backend._ffi.NULL)
  165. curve_nid = self._backend._lib.EC_GROUP_get_curve_name(group)
  166. public_ec_key = self._backend._ec_key_new_by_curve_nid(curve_nid)
  167. point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
  168. self._backend.openssl_assert(point != self._backend._ffi.NULL)
  169. res = self._backend._lib.EC_KEY_set_public_key(public_ec_key, point)
  170. self._backend.openssl_assert(res == 1)
  171. evp_pkey = self._backend._ec_cdata_to_evp_pkey(public_ec_key)
  172. return _EllipticCurvePublicKey(self._backend, public_ec_key, evp_pkey)
  173. def private_numbers(self) -> ec.EllipticCurvePrivateNumbers:
  174. bn = self._backend._lib.EC_KEY_get0_private_key(self._ec_key)
  175. private_value = self._backend._bn_to_int(bn)
  176. return ec.EllipticCurvePrivateNumbers(
  177. private_value=private_value,
  178. public_numbers=self.public_key().public_numbers(),
  179. )
  180. def private_bytes(
  181. self,
  182. encoding: serialization.Encoding,
  183. format: serialization.PrivateFormat,
  184. encryption_algorithm: serialization.KeySerializationEncryption,
  185. ) -> bytes:
  186. return self._backend._private_key_bytes(
  187. encoding,
  188. format,
  189. encryption_algorithm,
  190. self,
  191. self._evp_pkey,
  192. self._ec_key,
  193. )
  194. def sign(
  195. self,
  196. data: bytes,
  197. signature_algorithm: ec.EllipticCurveSignatureAlgorithm,
  198. ) -> bytes:
  199. _check_signature_algorithm(signature_algorithm)
  200. data, algorithm = _calculate_digest_and_algorithm(
  201. self._backend,
  202. data,
  203. signature_algorithm._algorithm, # type: ignore[attr-defined]
  204. )
  205. return _ecdsa_sig_sign(self._backend, self, data)
  206. class _EllipticCurvePublicKey(ec.EllipticCurvePublicKey):
  207. def __init__(self, backend, ec_key_cdata, evp_pkey):
  208. self._backend = backend
  209. self._ec_key = ec_key_cdata
  210. self._evp_pkey = evp_pkey
  211. sn = _ec_key_curve_sn(backend, ec_key_cdata)
  212. self._curve = _sn_to_elliptic_curve(backend, sn)
  213. _mark_asn1_named_ec_curve(backend, ec_key_cdata)
  214. curve = utils.read_only_property("_curve")
  215. @property
  216. def key_size(self) -> int:
  217. return self.curve.key_size
  218. def verifier(
  219. self,
  220. signature: bytes,
  221. signature_algorithm: ec.EllipticCurveSignatureAlgorithm,
  222. ) -> AsymmetricVerificationContext:
  223. _warn_sign_verify_deprecated()
  224. utils._check_bytes("signature", signature)
  225. _check_signature_algorithm(signature_algorithm)
  226. _check_not_prehashed(signature_algorithm.algorithm)
  227. # This assert is to help mypy realize what type this object holds
  228. assert isinstance(signature_algorithm.algorithm, hashes.HashAlgorithm)
  229. return _ECDSAVerificationContext(
  230. self._backend, self, signature, signature_algorithm.algorithm
  231. )
  232. def public_numbers(self) -> ec.EllipticCurvePublicNumbers:
  233. get_func, group = self._backend._ec_key_determine_group_get_func(
  234. self._ec_key
  235. )
  236. point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
  237. self._backend.openssl_assert(point != self._backend._ffi.NULL)
  238. with self._backend._tmp_bn_ctx() as bn_ctx:
  239. bn_x = self._backend._lib.BN_CTX_get(bn_ctx)
  240. bn_y = self._backend._lib.BN_CTX_get(bn_ctx)
  241. res = get_func(group, point, bn_x, bn_y, bn_ctx)
  242. self._backend.openssl_assert(res == 1)
  243. x = self._backend._bn_to_int(bn_x)
  244. y = self._backend._bn_to_int(bn_y)
  245. return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=self._curve)
  246. def _encode_point(self, format: serialization.PublicFormat) -> bytes:
  247. if format is serialization.PublicFormat.CompressedPoint:
  248. conversion = self._backend._lib.POINT_CONVERSION_COMPRESSED
  249. else:
  250. assert format is serialization.PublicFormat.UncompressedPoint
  251. conversion = self._backend._lib.POINT_CONVERSION_UNCOMPRESSED
  252. group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
  253. self._backend.openssl_assert(group != self._backend._ffi.NULL)
  254. point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
  255. self._backend.openssl_assert(point != self._backend._ffi.NULL)
  256. with self._backend._tmp_bn_ctx() as bn_ctx:
  257. buflen = self._backend._lib.EC_POINT_point2oct(
  258. group, point, conversion, self._backend._ffi.NULL, 0, bn_ctx
  259. )
  260. self._backend.openssl_assert(buflen > 0)
  261. buf = self._backend._ffi.new("char[]", buflen)
  262. res = self._backend._lib.EC_POINT_point2oct(
  263. group, point, conversion, buf, buflen, bn_ctx
  264. )
  265. self._backend.openssl_assert(buflen == res)
  266. return self._backend._ffi.buffer(buf)[:]
  267. def public_bytes(
  268. self,
  269. encoding: serialization.Encoding,
  270. format: serialization.PublicFormat,
  271. ) -> bytes:
  272. if (
  273. encoding is serialization.Encoding.X962
  274. or format is serialization.PublicFormat.CompressedPoint
  275. or format is serialization.PublicFormat.UncompressedPoint
  276. ):
  277. if encoding is not serialization.Encoding.X962 or format not in (
  278. serialization.PublicFormat.CompressedPoint,
  279. serialization.PublicFormat.UncompressedPoint,
  280. ):
  281. raise ValueError(
  282. "X962 encoding must be used with CompressedPoint or "
  283. "UncompressedPoint format"
  284. )
  285. return self._encode_point(format)
  286. else:
  287. return self._backend._public_key_bytes(
  288. encoding, format, self, self._evp_pkey, None
  289. )
  290. def verify(
  291. self,
  292. signature: bytes,
  293. data: bytes,
  294. signature_algorithm: ec.EllipticCurveSignatureAlgorithm,
  295. ) -> None:
  296. _check_signature_algorithm(signature_algorithm)
  297. data, algorithm = _calculate_digest_and_algorithm(
  298. self._backend,
  299. data,
  300. signature_algorithm._algorithm, # type: ignore[attr-defined]
  301. )
  302. _ecdsa_sig_verify(self._backend, self, signature, data)