ECC.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2015, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. from __future__ import print_function
  31. import struct
  32. import binascii
  33. from collections import namedtuple
  34. from Cryptodome.Util.py3compat import bord, tobytes, tostr, bchr, is_string
  35. from Cryptodome.Math.Numbers import Integer
  36. from Cryptodome.Random import get_random_bytes
  37. from Cryptodome.Util.asn1 import (DerObjectId, DerOctetString, DerSequence,
  38. DerBitString)
  39. from Cryptodome.IO import PKCS8, PEM
  40. from Cryptodome.PublicKey import (_expand_subject_public_key_info,
  41. _create_subject_public_key_info,
  42. _extract_subject_public_key_info)
  43. class UnsupportedEccFeature(ValueError):
  44. pass
  45. class EccPoint(object):
  46. """A class to abstract a point over an Elliptic Curve.
  47. :ivar x: The X-coordinate of the ECC point
  48. :vartype x: integer
  49. :ivar y: The Y-coordinate of the ECC point
  50. :vartype y: integer
  51. """
  52. def __init__(self, x, y):
  53. self._x = Integer(x)
  54. self._y = Integer(y)
  55. # Buffers
  56. self._common = Integer(0)
  57. self._tmp1 = Integer(0)
  58. self._x3 = Integer(0)
  59. self._y3 = Integer(0)
  60. def set(self, point):
  61. self._x = Integer(point._x)
  62. self._y = Integer(point._y)
  63. return self
  64. def __eq__(self, point):
  65. return self._x == point._x and self._y == point._y
  66. def __neg__(self):
  67. if self.is_point_at_infinity():
  68. return self.point_at_infinity()
  69. return EccPoint(self._x, _curve.p - self._y)
  70. def copy(self):
  71. return EccPoint(self._x, self._y)
  72. def is_point_at_infinity(self):
  73. return not (self._x or self._y)
  74. @staticmethod
  75. def point_at_infinity():
  76. return EccPoint(0, 0)
  77. @property
  78. def x(self):
  79. if self.is_point_at_infinity():
  80. raise ValueError("Point at infinity")
  81. return self._x
  82. @property
  83. def y(self):
  84. if self.is_point_at_infinity():
  85. raise ValueError("Point at infinity")
  86. return self._y
  87. def double(self):
  88. """Double this point (in-place operation).
  89. :Return:
  90. :class:`EccPoint` : this same object (to enable chaining)
  91. """
  92. if not self._y:
  93. return self.point_at_infinity()
  94. common = self._common
  95. tmp1 = self._tmp1
  96. x3 = self._x3
  97. y3 = self._y3
  98. # common = (pow(self._x, 2, _curve.p) * 3 - 3) * (self._y << 1).inverse(_curve.p) % _curve.p
  99. common.set(self._x)
  100. common.inplace_pow(2, _curve.p)
  101. common *= 3
  102. common -= 3
  103. tmp1.set(self._y)
  104. tmp1 <<= 1
  105. tmp1.inplace_inverse(_curve.p)
  106. common *= tmp1
  107. common %= _curve.p
  108. # x3 = (pow(common, 2, _curve.p) - 2 * self._x) % _curve.p
  109. x3.set(common)
  110. x3.inplace_pow(2, _curve.p)
  111. x3 -= self._x
  112. x3 -= self._x
  113. while x3.is_negative():
  114. x3 += _curve.p
  115. # y3 = ((self._x - x3) * common - self._y) % _curve.p
  116. y3.set(self._x)
  117. y3 -= x3
  118. y3 *= common
  119. y3 -= self._y
  120. y3 %= _curve.p
  121. self._x.set(x3)
  122. self._y.set(y3)
  123. return self
  124. def __iadd__(self, point):
  125. """Add a second point to this one"""
  126. if self.is_point_at_infinity():
  127. return self.set(point)
  128. if point.is_point_at_infinity():
  129. return self
  130. if self == point:
  131. return self.double()
  132. if self._x == point._x:
  133. return self.set(self.point_at_infinity())
  134. common = self._common
  135. tmp1 = self._tmp1
  136. x3 = self._x3
  137. y3 = self._y3
  138. # common = (point._y - self._y) * (point._x - self._x).inverse(_curve.p) % _curve.p
  139. common.set(point._y)
  140. common -= self._y
  141. tmp1.set(point._x)
  142. tmp1 -= self._x
  143. tmp1.inplace_inverse(_curve.p)
  144. common *= tmp1
  145. common %= _curve.p
  146. # x3 = (pow(common, 2, _curve.p) - self._x - point._x) % _curve.p
  147. x3.set(common)
  148. x3.inplace_pow(2, _curve.p)
  149. x3 -= self._x
  150. x3 -= point._x
  151. while x3.is_negative():
  152. x3 += _curve.p
  153. # y3 = ((self._x - x3) * common - self._y) % _curve.p
  154. y3.set(self._x)
  155. y3 -= x3
  156. y3 *= common
  157. y3 -= self._y
  158. y3 %= _curve.p
  159. self._x.set(x3)
  160. self._y.set(y3)
  161. return self
  162. def __add__(self, point):
  163. """Return a new point, the addition of this one and another"""
  164. result = self.copy()
  165. result += point
  166. return result
  167. def __mul__(self, scalar):
  168. """Return a new point, the scalar product of this one"""
  169. if scalar < 0:
  170. raise ValueError("Scalar multiplication only defined for non-negative integers")
  171. # Trivial results
  172. if scalar == 0 or self.is_point_at_infinity():
  173. return self.point_at_infinity()
  174. elif scalar == 1:
  175. return self.copy()
  176. # Scalar randomization
  177. scalar_blind = Integer.random(exact_bits=64) * _curve.order + scalar
  178. # Montgomery key ladder
  179. r = [self.point_at_infinity().copy(), self.copy()]
  180. bit_size = int(scalar_blind.size_in_bits())
  181. scalar_int = int(scalar_blind)
  182. for i in range(bit_size, -1, -1):
  183. di = scalar_int >> i & 1
  184. r[di ^ 1] += r[di]
  185. r[di].double()
  186. return r[0]
  187. _Curve = namedtuple("_Curve", "p b order Gx Gy G names oid")
  188. _curve_gx = Integer(0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296)
  189. _curve_gy = Integer(0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
  190. _curve = _Curve(
  191. Integer(0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff),
  192. Integer(0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b),
  193. Integer(0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551),
  194. _curve_gx,
  195. _curve_gy,
  196. EccPoint(_curve_gx, _curve_gy),
  197. ("P-256", "prime256v1", "secp256r1"),
  198. "1.2.840.10045.3.1.7",
  199. )
  200. del namedtuple
  201. class EccKey(object):
  202. r"""Class defining an ECC key.
  203. Do not instantiate directly.
  204. Use :func:`generate`, :func:`construct` or :func:`import_key` instead.
  205. :ivar curve: The name of the ECC curve
  206. :vartype curve: string
  207. :ivar pointQ: an ECC point representating the public component
  208. :vartype pointQ: :class:`EccPoint`
  209. :ivar d: A scalar representating the private component
  210. :vartype d: integer
  211. """
  212. def __init__(self, **kwargs):
  213. """Create a new ECC key
  214. Keywords:
  215. curve : string
  216. It must be *"P-256"*, *"prime256v1"* or *"secp256r1"*.
  217. d : integer
  218. Only for a private key. It must be in the range ``[1..order-1]``.
  219. point : EccPoint
  220. Mandatory for a public key. If provided for a private key,
  221. the implementation will NOT check whether it matches ``d``.
  222. """
  223. kwargs_ = dict(kwargs)
  224. self.curve = kwargs_.pop("curve", None)
  225. self._d = kwargs_.pop("d", None)
  226. self._point = kwargs_.pop("point", None)
  227. if kwargs_:
  228. raise TypeError("Unknown parameters: " + str(kwargs_))
  229. if self.curve not in _curve.names:
  230. raise ValueError("Unsupported curve (%s)", self.curve)
  231. if self._d is None:
  232. if self._point is None:
  233. raise ValueError("Either private or public ECC component must be specified")
  234. else:
  235. self._d = Integer(self._d)
  236. if not 1 <= self._d < _curve.order:
  237. raise ValueError("Invalid ECC private component")
  238. def __eq__(self, other):
  239. if other.has_private() != self.has_private():
  240. return False
  241. return (other.pointQ.x == self.pointQ.x) and (other.pointQ.y == self.pointQ.y)
  242. def __repr__(self):
  243. if self.has_private():
  244. extra = ", d=%d" % int(self._d)
  245. else:
  246. extra = ""
  247. return "EccKey(curve='P-256', x=%d, y=%d%s)" %\
  248. (self.pointQ.x, self.pointQ.y, extra)
  249. def has_private(self):
  250. """``True`` if this key can be used for making signatures or decrypting data."""
  251. return self._d is not None
  252. def _sign(self, z, k):
  253. assert 0 < k < _curve.order
  254. blind = Integer.random_range(min_inclusive=1,
  255. max_exclusive=_curve.order)
  256. blind_d = self._d * blind
  257. inv_blind_k = (blind * k).inverse(_curve.order)
  258. r = (_curve.G * k).x % _curve.order
  259. s = inv_blind_k * (blind * z + blind_d * r) % _curve.order
  260. return (r, s)
  261. def _verify(self, z, rs):
  262. sinv = rs[1].inverse(_curve.order)
  263. point1 = _curve.G * ((sinv * z) % _curve.order)
  264. point2 = self.pointQ * ((sinv * rs[0]) % _curve.order)
  265. return (point1 + point2).x == rs[0]
  266. @property
  267. def d(self):
  268. if not self.has_private():
  269. raise ValueError("This is not a private ECC key")
  270. return self._d
  271. @property
  272. def pointQ(self):
  273. if self._point is None:
  274. self._point = _curve.G * self._d
  275. return self._point
  276. def public_key(self):
  277. """A matching ECC public key.
  278. Returns:
  279. a new :class:`EccKey` object
  280. """
  281. return EccKey(curve="P-256", point=self.pointQ)
  282. def _export_subjectPublicKeyInfo(self, compress):
  283. # See 2.2 in RFC5480 and 2.3.3 in SEC1
  284. # The first byte is:
  285. # - 0x02: compressed, only X-coordinate, Y-coordinate is even
  286. # - 0x03: compressed, only X-coordinate, Y-coordinate is odd
  287. # - 0x04: uncompressed, X-coordinate is followed by Y-coordinate
  288. #
  289. # PAI is in theory encoded as 0x00.
  290. order_bytes = _curve.order.size_in_bytes()
  291. if compress:
  292. first_byte = 2 + self.pointQ.y.is_odd()
  293. public_key = (bchr(first_byte) +
  294. self.pointQ.x.to_bytes(order_bytes))
  295. else:
  296. public_key = (b'\x04' +
  297. self.pointQ.x.to_bytes(order_bytes) +
  298. self.pointQ.y.to_bytes(order_bytes))
  299. unrestricted_oid = "1.2.840.10045.2.1"
  300. return _create_subject_public_key_info(unrestricted_oid,
  301. public_key,
  302. DerObjectId(_curve.oid))
  303. def _export_private_der(self, include_ec_params=True):
  304. assert self.has_private()
  305. # ECPrivateKey ::= SEQUENCE {
  306. # version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
  307. # privateKey OCTET STRING,
  308. # parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
  309. # publicKey [1] BIT STRING OPTIONAL
  310. # }
  311. # Public key - uncompressed form
  312. order_bytes = _curve.order.size_in_bytes()
  313. public_key = (b'\x04' +
  314. self.pointQ.x.to_bytes(order_bytes) +
  315. self.pointQ.y.to_bytes(order_bytes))
  316. seq = [1,
  317. DerOctetString(self.d.to_bytes(order_bytes)),
  318. DerObjectId(_curve.oid, explicit=0),
  319. DerBitString(public_key, explicit=1)]
  320. if not include_ec_params:
  321. del seq[2]
  322. return DerSequence(seq).encode()
  323. def _export_pkcs8(self, **kwargs):
  324. if kwargs.get('passphrase', None) is not None and 'protection' not in kwargs:
  325. raise ValueError("At least the 'protection' parameter should be present")
  326. unrestricted_oid = "1.2.840.10045.2.1"
  327. private_key = self._export_private_der(include_ec_params=False)
  328. result = PKCS8.wrap(private_key,
  329. unrestricted_oid,
  330. key_params=DerObjectId(_curve.oid),
  331. **kwargs)
  332. return result
  333. def _export_public_pem(self, compress):
  334. encoded_der = self._export_subjectPublicKeyInfo(compress)
  335. return PEM.encode(encoded_der, "PUBLIC KEY")
  336. def _export_private_pem(self, passphrase, **kwargs):
  337. encoded_der = self._export_private_der()
  338. return PEM.encode(encoded_der, "EC PRIVATE KEY", passphrase, **kwargs)
  339. def _export_private_clear_pkcs8_in_clear_pem(self):
  340. encoded_der = self._export_pkcs8()
  341. return PEM.encode(encoded_der, "PRIVATE KEY")
  342. def _export_private_encrypted_pkcs8_in_clear_pem(self, passphrase, **kwargs):
  343. assert passphrase
  344. if 'protection' not in kwargs:
  345. raise ValueError("At least the 'protection' parameter should be present")
  346. encoded_der = self._export_pkcs8(passphrase=passphrase, **kwargs)
  347. return PEM.encode(encoded_der, "ENCRYPTED PRIVATE KEY")
  348. def _export_openssh(self, compress):
  349. if self.has_private():
  350. raise ValueError("Cannot export OpenSSH private keys")
  351. desc = "ecdsa-sha2-nistp256"
  352. order_bytes = _curve.order.size_in_bytes()
  353. if compress:
  354. first_byte = 2 + self.pointQ.y.is_odd()
  355. public_key = (bchr(first_byte) +
  356. self.pointQ.x.to_bytes(order_bytes))
  357. else:
  358. public_key = (b'\x04' +
  359. self.pointQ.x.to_bytes(order_bytes) +
  360. self.pointQ.y.to_bytes(order_bytes))
  361. comps = (tobytes(desc), b"nistp256", public_key)
  362. blob = b"".join([ struct.pack(">I", len(x)) + x for x in comps])
  363. return desc + " " + tostr(binascii.b2a_base64(blob))
  364. def export_key(self, **kwargs):
  365. """Export this ECC key.
  366. Args:
  367. format (string):
  368. The format to use for encoding the key:
  369. - *'DER'*. The key will be encoded in ASN.1 DER format (binary).
  370. For a public key, the ASN.1 ``subjectPublicKeyInfo`` structure
  371. defined in `RFC5480`_ will be used.
  372. For a private key, the ASN.1 ``ECPrivateKey`` structure defined
  373. in `RFC5915`_ is used instead (possibly within a PKCS#8 envelope,
  374. see the ``use_pkcs8`` flag below).
  375. - *'PEM'*. The key will be encoded in a PEM_ envelope (ASCII).
  376. - *'OpenSSH'*. The key will be encoded in the OpenSSH_ format
  377. (ASCII, public keys only).
  378. passphrase (byte string or string):
  379. The passphrase to use for protecting the private key.
  380. use_pkcs8 (boolean):
  381. If ``True`` (default and recommended), the `PKCS#8`_ representation
  382. will be used.
  383. If ``False``, the much weaker `PEM encryption`_ mechanism will be used.
  384. protection (string):
  385. When a private key is exported with password-protection
  386. and PKCS#8 (both ``DER`` and ``PEM`` formats), this parameter MUST be
  387. present and be a valid algorithm supported by :mod:`Cryptodome.IO.PKCS8`.
  388. It is recommended to use ``PBKDF2WithHMAC-SHA1AndAES128-CBC``.
  389. compress (boolean):
  390. If ``True``, a more compact representation of the public key
  391. (X-coordinate only) is used.
  392. If ``False`` (default), the full public key (in both its
  393. coordinates) will be exported.
  394. .. warning::
  395. If you don't provide a passphrase, the private key will be
  396. exported in the clear!
  397. .. note::
  398. When exporting a private key with password-protection and `PKCS#8`_
  399. (both ``DER`` and ``PEM`` formats), any extra parameters
  400. is passed to :mod:`Cryptodome.IO.PKCS8`.
  401. .. _PEM: http://www.ietf.org/rfc/rfc1421.txt
  402. .. _`PEM encryption`: http://www.ietf.org/rfc/rfc1423.txt
  403. .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
  404. .. _OpenSSH: http://www.openssh.com/txt/rfc5656.txt
  405. .. _RFC5480: https://tools.ietf.org/html/rfc5480
  406. .. _RFC5915: http://www.ietf.org/rfc/rfc5915.txt
  407. Returns:
  408. A multi-line string (for PEM and OpenSSH) or bytes (for DER) with the encoded key.
  409. """
  410. args = kwargs.copy()
  411. ext_format = args.pop("format")
  412. if ext_format not in ("PEM", "DER", "OpenSSH"):
  413. raise ValueError("Unknown format '%s'" % ext_format)
  414. compress = args.pop("compress", False)
  415. if self.has_private():
  416. passphrase = args.pop("passphrase", None)
  417. if is_string(passphrase):
  418. passphrase = tobytes(passphrase)
  419. if not passphrase:
  420. raise ValueError("Empty passphrase")
  421. use_pkcs8 = args.pop("use_pkcs8", True)
  422. if ext_format == "PEM":
  423. if use_pkcs8:
  424. if passphrase:
  425. return self._export_private_encrypted_pkcs8_in_clear_pem(passphrase, **args)
  426. else:
  427. return self._export_private_clear_pkcs8_in_clear_pem()
  428. else:
  429. return self._export_private_pem(passphrase, **args)
  430. elif ext_format == "DER":
  431. # DER
  432. if passphrase and not use_pkcs8:
  433. raise ValueError("Private keys can only be encrpyted with DER using PKCS#8")
  434. if use_pkcs8:
  435. return self._export_pkcs8(passphrase=passphrase, **args)
  436. else:
  437. return self._export_private_der()
  438. else:
  439. raise ValueError("Private keys cannot be exported in OpenSSH format")
  440. else: # Public key
  441. if args:
  442. raise ValueError("Unexpected parameters: '%s'" % args)
  443. if ext_format == "PEM":
  444. return self._export_public_pem(compress)
  445. elif ext_format == "DER":
  446. return self._export_subjectPublicKeyInfo(compress)
  447. else:
  448. return self._export_openssh(compress)
  449. def generate(**kwargs):
  450. """Generate a new private key on the given curve.
  451. Args:
  452. curve (string):
  453. Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
  454. randfunc (callable):
  455. Optional. The RNG to read randomness from.
  456. If ``None``, :func:`Cryptodome.Random.get_random_bytes` is used.
  457. """
  458. curve = kwargs.pop("curve")
  459. randfunc = kwargs.pop("randfunc", get_random_bytes)
  460. if kwargs:
  461. raise TypeError("Unknown parameters: " + str(kwargs))
  462. d = Integer.random_range(min_inclusive=1,
  463. max_exclusive=_curve.order,
  464. randfunc=randfunc)
  465. return EccKey(curve=curve, d=d)
  466. def construct(**kwargs):
  467. """Build a new ECC key (private or public) starting
  468. from some base components.
  469. Args:
  470. curve (string):
  471. Mandatory. It must be "P-256", "prime256v1" or "secp256r1".
  472. d (integer):
  473. Only for a private key. It must be in the range ``[1..order-1]``.
  474. point_x (integer):
  475. Mandatory for a public key. X coordinate (affine) of the ECC point.
  476. point_y (integer):
  477. Mandatory for a public key. Y coordinate (affine) of the ECC point.
  478. Returns:
  479. :class:`EccKey` : a new ECC key object
  480. """
  481. point_x = kwargs.pop("point_x", None)
  482. point_y = kwargs.pop("point_y", None)
  483. if "point" in kwargs:
  484. raise TypeError("Unknown keyword: point")
  485. if None not in (point_x, point_y):
  486. kwargs["point"] = EccPoint(point_x, point_y)
  487. # Validate that the point is on the P-256 curve
  488. eq1 = pow(Integer(point_y), 2, _curve.p)
  489. x = Integer(point_x)
  490. eq2 = pow(x, 3, _curve.p)
  491. x *= -3
  492. eq2 += x
  493. eq2 += _curve.b
  494. eq2 %= _curve.p
  495. if eq1 != eq2:
  496. raise ValueError("The point is not on the curve")
  497. # Validate that the private key matches the public one
  498. d = kwargs.get("d", None)
  499. if d is not None and "point" in kwargs:
  500. pub_key = _curve.G * d
  501. if pub_key.x != point_x or pub_key.y != point_y:
  502. raise ValueError("Private and public ECC keys do not match")
  503. return EccKey(**kwargs)
  504. def _import_public_der(curve_oid, ec_point):
  505. """Convert an encoded EC point into an EccKey object
  506. curve_name: string with the OID of the curve
  507. ec_point: byte string with the EC point (not DER encoded)
  508. """
  509. # We only support P-256 named curves for now
  510. if curve_oid != _curve.oid:
  511. raise UnsupportedEccFeature("Unsupported ECC curve (OID: %s)" % curve_oid)
  512. # See 2.2 in RFC5480 and 2.3.3 in SEC1
  513. # The first byte is:
  514. # - 0x02: compressed, only X-coordinate, Y-coordinate is even
  515. # - 0x03: compressed, only X-coordinate, Y-coordinate is odd
  516. # - 0x04: uncompressed, X-coordinate is followed by Y-coordinate
  517. #
  518. # PAI is in theory encoded as 0x00.
  519. order_bytes = _curve.order.size_in_bytes()
  520. point_type = bord(ec_point[0])
  521. # Uncompressed point
  522. if point_type == 0x04:
  523. if len(ec_point) != (1 + 2 * order_bytes):
  524. raise ValueError("Incorrect EC point length")
  525. x = Integer.from_bytes(ec_point[1:order_bytes+1])
  526. y = Integer.from_bytes(ec_point[order_bytes+1:])
  527. # Compressed point
  528. elif point_type in (0x02, 0x3):
  529. if len(ec_point) != (1 + order_bytes):
  530. raise ValueError("Incorrect EC point length")
  531. x = Integer.from_bytes(ec_point[1:])
  532. y = (x**3 - x*3 + _curve.b).sqrt(_curve.p) # Short Weierstrass
  533. if point_type == 0x02 and y.is_odd():
  534. y = _curve.p - y
  535. if point_type == 0x03 and y.is_even():
  536. y = _curve.p - y
  537. else:
  538. raise ValueError("Incorrect EC point encoding")
  539. return construct(curve="P-256", point_x=x, point_y=y)
  540. def _import_subjectPublicKeyInfo(encoded, *kwargs):
  541. """Convert a subjectPublicKeyInfo into an EccKey object"""
  542. # See RFC5480
  543. # Parse the generic subjectPublicKeyInfo structure
  544. oid, ec_point, params = _expand_subject_public_key_info(encoded)
  545. # ec_point must be an encoded OCTET STRING
  546. # params is encoded ECParameters
  547. # We accept id-ecPublicKey, id-ecDH, id-ecMQV without making any
  548. # distiction for now.
  549. unrestricted_oid = "1.2.840.10045.2.1" # Restrictions can be captured
  550. # in the key usage certificate
  551. # extension
  552. ecdh_oid = "1.3.132.1.12"
  553. ecmqv_oid = "1.3.132.1.13"
  554. if oid not in (unrestricted_oid, ecdh_oid, ecmqv_oid):
  555. raise UnsupportedEccFeature("Unsupported ECC purpose (OID: %s)" % oid)
  556. # Parameters are mandatory for all three types
  557. if not params:
  558. raise ValueError("Missing ECC parameters")
  559. # ECParameters ::= CHOICE {
  560. # namedCurve OBJECT IDENTIFIER
  561. # -- implicitCurve NULL
  562. # -- specifiedCurve SpecifiedECDomain
  563. # }
  564. #
  565. # implicitCurve and specifiedCurve are not supported (as per RFC)
  566. curve_oid = DerObjectId().decode(params).value
  567. return _import_public_der(curve_oid, ec_point)
  568. def _import_private_der(encoded, passphrase, curve_name=None):
  569. # ECPrivateKey ::= SEQUENCE {
  570. # version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
  571. # privateKey OCTET STRING,
  572. # parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
  573. # publicKey [1] BIT STRING OPTIONAL
  574. # }
  575. private_key = DerSequence().decode(encoded, nr_elements=(3, 4))
  576. if private_key[0] != 1:
  577. raise ValueError("Incorrect ECC private key version")
  578. try:
  579. curve_name = DerObjectId(explicit=0).decode(private_key[2]).value
  580. except ValueError:
  581. pass
  582. if curve_name != _curve.oid:
  583. raise UnsupportedEccFeature("Unsupported ECC curve (OID: %s)" % curve_name)
  584. scalar_bytes = DerOctetString().decode(private_key[1]).payload
  585. order_bytes = _curve.order.size_in_bytes()
  586. if len(scalar_bytes) != order_bytes:
  587. raise ValueError("Private key is too small")
  588. d = Integer.from_bytes(scalar_bytes)
  589. # Decode public key (if any, it must be P-256)
  590. if len(private_key) == 4:
  591. public_key_enc = DerBitString(explicit=1).decode(private_key[3]).value
  592. public_key = _import_public_der(curve_name, public_key_enc)
  593. point_x = public_key.pointQ.x
  594. point_y = public_key.pointQ.y
  595. else:
  596. point_x = point_y = None
  597. return construct(curve="P-256", d=d, point_x=point_x, point_y=point_y)
  598. def _import_pkcs8(encoded, passphrase):
  599. # From RFC5915, Section 1:
  600. #
  601. # Distributing an EC private key with PKCS#8 [RFC5208] involves including:
  602. # a) id-ecPublicKey, id-ecDH, or id-ecMQV (from [RFC5480]) with the
  603. # namedCurve as the parameters in the privateKeyAlgorithm field; and
  604. # b) ECPrivateKey in the PrivateKey field, which is an OCTET STRING.
  605. algo_oid, private_key, params = PKCS8.unwrap(encoded, passphrase)
  606. # We accept id-ecPublicKey, id-ecDH, id-ecMQV without making any
  607. # distiction for now.
  608. unrestricted_oid = "1.2.840.10045.2.1"
  609. ecdh_oid = "1.3.132.1.12"
  610. ecmqv_oid = "1.3.132.1.13"
  611. if algo_oid not in (unrestricted_oid, ecdh_oid, ecmqv_oid):
  612. raise UnsupportedEccFeature("Unsupported ECC purpose (OID: %s)" % oid)
  613. curve_name = DerObjectId().decode(params).value
  614. return _import_private_der(private_key, passphrase, curve_name)
  615. def _import_x509_cert(encoded, *kwargs):
  616. sp_info = _extract_subject_public_key_info(encoded)
  617. return _import_subjectPublicKeyInfo(sp_info)
  618. def _import_der(encoded, passphrase):
  619. try:
  620. return _import_subjectPublicKeyInfo(encoded, passphrase)
  621. except UnsupportedEccFeature as err:
  622. raise err
  623. except (ValueError, TypeError, IndexError):
  624. pass
  625. try:
  626. return _import_x509_cert(encoded, passphrase)
  627. except UnsupportedEccFeature as err:
  628. raise err
  629. except (ValueError, TypeError, IndexError):
  630. pass
  631. try:
  632. return _import_private_der(encoded, passphrase)
  633. except UnsupportedEccFeature as err:
  634. raise err
  635. except (ValueError, TypeError, IndexError):
  636. pass
  637. try:
  638. return _import_pkcs8(encoded, passphrase)
  639. except UnsupportedEccFeature as err:
  640. raise err
  641. except (ValueError, TypeError, IndexError):
  642. pass
  643. raise ValueError("Not an ECC DER key")
  644. def _import_openssh(encoded):
  645. keystring = binascii.a2b_base64(encoded.split(b' ')[1])
  646. keyparts = []
  647. while len(keystring) > 4:
  648. l = struct.unpack(">I", keystring[:4])[0]
  649. keyparts.append(keystring[4:4 + l])
  650. keystring = keystring[4 + l:]
  651. if keyparts[1] != b"nistp256":
  652. raise ValueError("Unsupported ECC curve")
  653. return _import_public_der(_curve.oid, keyparts[2])
  654. def import_key(encoded, passphrase=None):
  655. """Import an ECC key (public or private).
  656. Args:
  657. encoded (bytes or multi-line string):
  658. The ECC key to import.
  659. An ECC **public** key can be:
  660. - An X.509 certificate, binary (DER) or ASCII (PEM)
  661. - An X.509 ``subjectPublicKeyInfo``, binary (DER) or ASCII (PEM)
  662. - An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII)
  663. An ECC **private** key can be:
  664. - In binary format (DER, see section 3 of `RFC5915`_ or `PKCS#8`_)
  665. - In ASCII format (PEM or OpenSSH)
  666. Private keys can be in the clear or password-protected.
  667. For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
  668. passphrase (byte string):
  669. The passphrase to use for decrypting a private key.
  670. Encryption may be applied protected at the PEM level or at the PKCS#8 level.
  671. This parameter is ignored if the key in input is not encrypted.
  672. Returns:
  673. :class:`EccKey` : a new ECC key object
  674. Raises:
  675. ValueError: when the given key cannot be parsed (possibly because
  676. the pass phrase is wrong).
  677. .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
  678. .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
  679. .. _RFC5915: http://www.ietf.org/rfc/rfc5915.txt
  680. .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
  681. """
  682. encoded = tobytes(encoded)
  683. if passphrase is not None:
  684. passphrase = tobytes(passphrase)
  685. # PEM
  686. if encoded.startswith(b'-----'):
  687. der_encoded, marker, enc_flag = PEM.decode(tostr(encoded), passphrase)
  688. if enc_flag:
  689. passphrase = None
  690. try:
  691. result = _import_der(der_encoded, passphrase)
  692. except UnsupportedEccFeature as uef:
  693. raise uef
  694. except ValueError:
  695. raise ValueError("Invalid DER encoding inside the PEM file")
  696. return result
  697. # OpenSSH
  698. if encoded.startswith(b'ecdsa-sha2-'):
  699. return _import_openssh(encoded)
  700. # DER
  701. if bord(encoded[0]) == 0x30:
  702. return _import_der(encoded, passphrase)
  703. raise ValueError("ECC key format is not supported")
  704. if __name__ == "__main__":
  705. import time
  706. d = 0xc51e4753afdec1e6b6c6a5b992f43f8dd0c7a8933072708b6522468b2ffb06fd
  707. point = generate(curve="P-256").pointQ
  708. start = time.time()
  709. count = 30
  710. for x in range(count):
  711. _ = point * d
  712. print((time.time() - start) / count * 1000, "ms")