ec.py 11 KB

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