ec.py 15 KB

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