ec.py 14 KB

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