ec.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 abc
  5. import typing
  6. import warnings
  7. from cryptography import utils
  8. from cryptography.hazmat._oid import ObjectIdentifier
  9. from cryptography.hazmat.primitives import _serialization, hashes
  10. from cryptography.hazmat.primitives.asymmetric import (
  11. utils as asym_utils,
  12. )
  13. class EllipticCurveOID:
  14. SECP192R1 = ObjectIdentifier("1.2.840.10045.3.1.1")
  15. SECP224R1 = ObjectIdentifier("1.3.132.0.33")
  16. SECP256K1 = ObjectIdentifier("1.3.132.0.10")
  17. SECP256R1 = ObjectIdentifier("1.2.840.10045.3.1.7")
  18. SECP384R1 = ObjectIdentifier("1.3.132.0.34")
  19. SECP521R1 = ObjectIdentifier("1.3.132.0.35")
  20. BRAINPOOLP256R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.7")
  21. BRAINPOOLP384R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.11")
  22. BRAINPOOLP512R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.13")
  23. SECT163K1 = ObjectIdentifier("1.3.132.0.1")
  24. SECT163R2 = ObjectIdentifier("1.3.132.0.15")
  25. SECT233K1 = ObjectIdentifier("1.3.132.0.26")
  26. SECT233R1 = ObjectIdentifier("1.3.132.0.27")
  27. SECT283K1 = ObjectIdentifier("1.3.132.0.16")
  28. SECT283R1 = ObjectIdentifier("1.3.132.0.17")
  29. SECT409K1 = ObjectIdentifier("1.3.132.0.36")
  30. SECT409R1 = ObjectIdentifier("1.3.132.0.37")
  31. SECT571K1 = ObjectIdentifier("1.3.132.0.38")
  32. SECT571R1 = ObjectIdentifier("1.3.132.0.39")
  33. class EllipticCurve(metaclass=abc.ABCMeta):
  34. @abc.abstractproperty
  35. def name(self) -> str:
  36. """
  37. The name of the curve. e.g. secp256r1.
  38. """
  39. @abc.abstractproperty
  40. def key_size(self) -> int:
  41. """
  42. Bit size of a secret scalar for the curve.
  43. """
  44. class EllipticCurveSignatureAlgorithm(metaclass=abc.ABCMeta):
  45. @abc.abstractproperty
  46. def algorithm(
  47. self,
  48. ) -> typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm]:
  49. """
  50. The digest algorithm used with this signature.
  51. """
  52. class EllipticCurvePrivateKey(metaclass=abc.ABCMeta):
  53. @abc.abstractmethod
  54. def exchange(
  55. self, algorithm: "ECDH", peer_public_key: "EllipticCurvePublicKey"
  56. ) -> bytes:
  57. """
  58. Performs a key exchange operation using the provided algorithm with the
  59. provided peer's public key.
  60. """
  61. @abc.abstractmethod
  62. def public_key(self) -> "EllipticCurvePublicKey":
  63. """
  64. The EllipticCurvePublicKey for this private key.
  65. """
  66. @abc.abstractproperty
  67. def curve(self) -> EllipticCurve:
  68. """
  69. The EllipticCurve that this key is on.
  70. """
  71. @abc.abstractproperty
  72. def key_size(self) -> int:
  73. """
  74. Bit size of a secret scalar for the curve.
  75. """
  76. @abc.abstractmethod
  77. def sign(
  78. self,
  79. data: bytes,
  80. signature_algorithm: EllipticCurveSignatureAlgorithm,
  81. ) -> bytes:
  82. """
  83. Signs the data
  84. """
  85. @abc.abstractmethod
  86. def private_numbers(self) -> "EllipticCurvePrivateNumbers":
  87. """
  88. Returns an EllipticCurvePrivateNumbers.
  89. """
  90. @abc.abstractmethod
  91. def private_bytes(
  92. self,
  93. encoding: _serialization.Encoding,
  94. format: _serialization.PrivateFormat,
  95. encryption_algorithm: _serialization.KeySerializationEncryption,
  96. ) -> bytes:
  97. """
  98. Returns the key serialized as bytes.
  99. """
  100. EllipticCurvePrivateKeyWithSerialization = EllipticCurvePrivateKey
  101. class EllipticCurvePublicKey(metaclass=abc.ABCMeta):
  102. @abc.abstractproperty
  103. def curve(self) -> EllipticCurve:
  104. """
  105. The EllipticCurve that this key is on.
  106. """
  107. @abc.abstractproperty
  108. def key_size(self) -> int:
  109. """
  110. Bit size of a secret scalar for the curve.
  111. """
  112. @abc.abstractmethod
  113. def public_numbers(self) -> "EllipticCurvePublicNumbers":
  114. """
  115. Returns an EllipticCurvePublicNumbers.
  116. """
  117. @abc.abstractmethod
  118. def public_bytes(
  119. self,
  120. encoding: _serialization.Encoding,
  121. format: _serialization.PublicFormat,
  122. ) -> bytes:
  123. """
  124. Returns the key serialized as bytes.
  125. """
  126. @abc.abstractmethod
  127. def verify(
  128. self,
  129. signature: bytes,
  130. data: bytes,
  131. signature_algorithm: EllipticCurveSignatureAlgorithm,
  132. ) -> None:
  133. """
  134. Verifies the signature of the data.
  135. """
  136. @classmethod
  137. def from_encoded_point(
  138. cls, curve: EllipticCurve, data: bytes
  139. ) -> "EllipticCurvePublicKey":
  140. utils._check_bytes("data", data)
  141. if not isinstance(curve, EllipticCurve):
  142. raise TypeError("curve must be an EllipticCurve instance")
  143. if len(data) == 0:
  144. raise ValueError("data must not be an empty byte string")
  145. if data[0] not in [0x02, 0x03, 0x04]:
  146. raise ValueError("Unsupported elliptic curve point type")
  147. from cryptography.hazmat.backends.openssl.backend import backend
  148. return backend.load_elliptic_curve_public_bytes(curve, data)
  149. EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey
  150. class SECT571R1(EllipticCurve):
  151. name = "sect571r1"
  152. key_size = 570
  153. class SECT409R1(EllipticCurve):
  154. name = "sect409r1"
  155. key_size = 409
  156. class SECT283R1(EllipticCurve):
  157. name = "sect283r1"
  158. key_size = 283
  159. class SECT233R1(EllipticCurve):
  160. name = "sect233r1"
  161. key_size = 233
  162. class SECT163R2(EllipticCurve):
  163. name = "sect163r2"
  164. key_size = 163
  165. class SECT571K1(EllipticCurve):
  166. name = "sect571k1"
  167. key_size = 571
  168. class SECT409K1(EllipticCurve):
  169. name = "sect409k1"
  170. key_size = 409
  171. class SECT283K1(EllipticCurve):
  172. name = "sect283k1"
  173. key_size = 283
  174. class SECT233K1(EllipticCurve):
  175. name = "sect233k1"
  176. key_size = 233
  177. class SECT163K1(EllipticCurve):
  178. name = "sect163k1"
  179. key_size = 163
  180. class SECP521R1(EllipticCurve):
  181. name = "secp521r1"
  182. key_size = 521
  183. class SECP384R1(EllipticCurve):
  184. name = "secp384r1"
  185. key_size = 384
  186. class SECP256R1(EllipticCurve):
  187. name = "secp256r1"
  188. key_size = 256
  189. class SECP256K1(EllipticCurve):
  190. name = "secp256k1"
  191. key_size = 256
  192. class SECP224R1(EllipticCurve):
  193. name = "secp224r1"
  194. key_size = 224
  195. class SECP192R1(EllipticCurve):
  196. name = "secp192r1"
  197. key_size = 192
  198. class BrainpoolP256R1(EllipticCurve):
  199. name = "brainpoolP256r1"
  200. key_size = 256
  201. class BrainpoolP384R1(EllipticCurve):
  202. name = "brainpoolP384r1"
  203. key_size = 384
  204. class BrainpoolP512R1(EllipticCurve):
  205. name = "brainpoolP512r1"
  206. key_size = 512
  207. _CURVE_TYPES: typing.Dict[str, typing.Type[EllipticCurve]] = {
  208. "prime192v1": SECP192R1,
  209. "prime256v1": SECP256R1,
  210. "secp192r1": SECP192R1,
  211. "secp224r1": SECP224R1,
  212. "secp256r1": SECP256R1,
  213. "secp384r1": SECP384R1,
  214. "secp521r1": SECP521R1,
  215. "secp256k1": SECP256K1,
  216. "sect163k1": SECT163K1,
  217. "sect233k1": SECT233K1,
  218. "sect283k1": SECT283K1,
  219. "sect409k1": SECT409K1,
  220. "sect571k1": SECT571K1,
  221. "sect163r2": SECT163R2,
  222. "sect233r1": SECT233R1,
  223. "sect283r1": SECT283R1,
  224. "sect409r1": SECT409R1,
  225. "sect571r1": SECT571R1,
  226. "brainpoolP256r1": BrainpoolP256R1,
  227. "brainpoolP384r1": BrainpoolP384R1,
  228. "brainpoolP512r1": BrainpoolP512R1,
  229. }
  230. class ECDSA(EllipticCurveSignatureAlgorithm):
  231. def __init__(
  232. self,
  233. algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],
  234. ):
  235. self._algorithm = algorithm
  236. @property
  237. def algorithm(
  238. self,
  239. ) -> typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm]:
  240. return self._algorithm
  241. def generate_private_key(
  242. curve: EllipticCurve, backend: typing.Any = None
  243. ) -> EllipticCurvePrivateKey:
  244. from cryptography.hazmat.backends.openssl.backend import backend as ossl
  245. return ossl.generate_elliptic_curve_private_key(curve)
  246. def derive_private_key(
  247. private_value: int,
  248. curve: EllipticCurve,
  249. backend: typing.Any = None,
  250. ) -> EllipticCurvePrivateKey:
  251. from cryptography.hazmat.backends.openssl.backend import backend as ossl
  252. if not isinstance(private_value, int):
  253. raise TypeError("private_value must be an integer type.")
  254. if private_value <= 0:
  255. raise ValueError("private_value must be a positive integer.")
  256. if not isinstance(curve, EllipticCurve):
  257. raise TypeError("curve must provide the EllipticCurve interface.")
  258. return ossl.derive_elliptic_curve_private_key(private_value, curve)
  259. class EllipticCurvePublicNumbers:
  260. def __init__(self, x: int, y: int, curve: EllipticCurve):
  261. if not isinstance(x, int) or not isinstance(y, int):
  262. raise TypeError("x and y must be integers.")
  263. if not isinstance(curve, EllipticCurve):
  264. raise TypeError("curve must provide the EllipticCurve interface.")
  265. self._y = y
  266. self._x = x
  267. self._curve = curve
  268. def public_key(self, backend: typing.Any = None) -> EllipticCurvePublicKey:
  269. from cryptography.hazmat.backends.openssl.backend import (
  270. backend as ossl,
  271. )
  272. return ossl.load_elliptic_curve_public_numbers(self)
  273. def encode_point(self) -> bytes:
  274. warnings.warn(
  275. "encode_point has been deprecated on EllipticCurvePublicNumbers"
  276. " and will be removed in a future version. Please use "
  277. "EllipticCurvePublicKey.public_bytes to obtain both "
  278. "compressed and uncompressed point encoding.",
  279. utils.PersistentlyDeprecated2019,
  280. stacklevel=2,
  281. )
  282. # key_size is in bits. Convert to bytes and round up
  283. byte_length = (self.curve.key_size + 7) // 8
  284. return (
  285. b"\x04"
  286. + utils.int_to_bytes(self.x, byte_length)
  287. + utils.int_to_bytes(self.y, byte_length)
  288. )
  289. @classmethod
  290. def from_encoded_point(
  291. cls, curve: EllipticCurve, data: bytes
  292. ) -> "EllipticCurvePublicNumbers":
  293. if not isinstance(curve, EllipticCurve):
  294. raise TypeError("curve must be an EllipticCurve instance")
  295. warnings.warn(
  296. "Support for unsafe construction of public numbers from "
  297. "encoded data will be removed in a future version. "
  298. "Please use EllipticCurvePublicKey.from_encoded_point",
  299. utils.PersistentlyDeprecated2019,
  300. stacklevel=2,
  301. )
  302. if data.startswith(b"\x04"):
  303. # key_size is in bits. Convert to bytes and round up
  304. byte_length = (curve.key_size + 7) // 8
  305. if len(data) == 2 * byte_length + 1:
  306. x = int.from_bytes(data[1 : byte_length + 1], "big")
  307. y = int.from_bytes(data[byte_length + 1 :], "big")
  308. return cls(x, y, curve)
  309. else:
  310. raise ValueError("Invalid elliptic curve point data length")
  311. else:
  312. raise ValueError("Unsupported elliptic curve point type")
  313. @property
  314. def curve(self) -> EllipticCurve:
  315. return self._curve
  316. @property
  317. def x(self) -> int:
  318. return self._x
  319. @property
  320. def y(self) -> int:
  321. return self._y
  322. def __eq__(self, other: object) -> bool:
  323. if not isinstance(other, EllipticCurvePublicNumbers):
  324. return NotImplemented
  325. return (
  326. self.x == other.x
  327. and self.y == other.y
  328. and self.curve.name == other.curve.name
  329. and self.curve.key_size == other.curve.key_size
  330. )
  331. def __hash__(self) -> int:
  332. return hash((self.x, self.y, self.curve.name, self.curve.key_size))
  333. def __repr__(self) -> str:
  334. return (
  335. "<EllipticCurvePublicNumbers(curve={0.curve.name}, x={0.x}, "
  336. "y={0.y}>".format(self)
  337. )
  338. class EllipticCurvePrivateNumbers:
  339. def __init__(
  340. self, private_value: int, public_numbers: EllipticCurvePublicNumbers
  341. ):
  342. if not isinstance(private_value, int):
  343. raise TypeError("private_value must be an integer.")
  344. if not isinstance(public_numbers, EllipticCurvePublicNumbers):
  345. raise TypeError(
  346. "public_numbers must be an EllipticCurvePublicNumbers "
  347. "instance."
  348. )
  349. self._private_value = private_value
  350. self._public_numbers = public_numbers
  351. def private_key(
  352. self, backend: typing.Any = None
  353. ) -> EllipticCurvePrivateKey:
  354. from cryptography.hazmat.backends.openssl.backend import (
  355. backend as ossl,
  356. )
  357. return ossl.load_elliptic_curve_private_numbers(self)
  358. @property
  359. def private_value(self) -> int:
  360. return self._private_value
  361. @property
  362. def public_numbers(self) -> EllipticCurvePublicNumbers:
  363. return self._public_numbers
  364. def __eq__(self, other: object) -> bool:
  365. if not isinstance(other, EllipticCurvePrivateNumbers):
  366. return NotImplemented
  367. return (
  368. self.private_value == other.private_value
  369. and self.public_numbers == other.public_numbers
  370. )
  371. def __hash__(self) -> int:
  372. return hash((self.private_value, self.public_numbers))
  373. class ECDH:
  374. pass
  375. _OID_TO_CURVE = {
  376. EllipticCurveOID.SECP192R1: SECP192R1,
  377. EllipticCurveOID.SECP224R1: SECP224R1,
  378. EllipticCurveOID.SECP256K1: SECP256K1,
  379. EllipticCurveOID.SECP256R1: SECP256R1,
  380. EllipticCurveOID.SECP384R1: SECP384R1,
  381. EllipticCurveOID.SECP521R1: SECP521R1,
  382. EllipticCurveOID.BRAINPOOLP256R1: BrainpoolP256R1,
  383. EllipticCurveOID.BRAINPOOLP384R1: BrainpoolP384R1,
  384. EllipticCurveOID.BRAINPOOLP512R1: BrainpoolP512R1,
  385. EllipticCurveOID.SECT163K1: SECT163K1,
  386. EllipticCurveOID.SECT163R2: SECT163R2,
  387. EllipticCurveOID.SECT233K1: SECT233K1,
  388. EllipticCurveOID.SECT233R1: SECT233R1,
  389. EllipticCurveOID.SECT283K1: SECT283K1,
  390. EllipticCurveOID.SECT283R1: SECT283R1,
  391. EllipticCurveOID.SECT409K1: SECT409K1,
  392. EllipticCurveOID.SECT409R1: SECT409R1,
  393. EllipticCurveOID.SECT571K1: SECT571K1,
  394. EllipticCurveOID.SECT571R1: SECT571R1,
  395. }
  396. def get_curve_for_oid(oid: ObjectIdentifier) -> typing.Type[EllipticCurve]:
  397. try:
  398. return _OID_TO_CURVE[oid]
  399. except KeyError:
  400. raise LookupError(
  401. "The provided object identifier has no matching elliptic "
  402. "curve class"
  403. )