You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1610 line
53 KiB

  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Implementation of elliptic curves, for cryptographic applications.
  5. #
  6. # This module doesn't provide any way to choose a random elliptic
  7. # curve, nor to verify that an elliptic curve was chosen randomly,
  8. # because one can simply use NIST's standard curves.
  9. #
  10. # Notes from X9.62-1998 (draft):
  11. # Nomenclature:
  12. # - Q is a public key.
  13. # The "Elliptic Curve Domain Parameters" include:
  14. # - q is the "field size", which in our case equals p.
  15. # - p is a big prime.
  16. # - G is a point of prime order (5.1.1.1).
  17. # - n is the order of G (5.1.1.1).
  18. # Public-key validation (5.2.2):
  19. # - Verify that Q is not the point at infinity.
  20. # - Verify that X_Q and Y_Q are in [0,p-1].
  21. # - Verify that Q is on the curve.
  22. # - Verify that nQ is the point at infinity.
  23. # Signature generation (5.3):
  24. # - Pick random k from [1,n-1].
  25. # Signature checking (5.4.2):
  26. # - Verify that r and s are in [1,n-1].
  27. #
  28. # Revision history:
  29. # 2005.12.31 - Initial version.
  30. # 2008.11.25 - Change CurveFp.is_on to contains_point.
  31. #
  32. # Written in 2005 by Peter Pearson and placed in the public domain.
  33. # Modified extensively as part of python-ecdsa.
  34. from __future__ import division
  35. try:
  36. from gmpy2 import mpz
  37. GMPY = True
  38. except ImportError: # pragma: no branch
  39. try:
  40. from gmpy import mpz
  41. GMPY = True
  42. except ImportError:
  43. GMPY = False
  44. from six import python_2_unicode_compatible
  45. from . import numbertheory
  46. from ._compat import normalise_bytes, int_to_bytes, bit_length, bytes_to_int
  47. from .errors import MalformedPointError
  48. from .util import orderlen, string_to_number, number_to_string
  49. @python_2_unicode_compatible
  50. class CurveFp(object):
  51. """
  52. :term:`Short Weierstrass Elliptic Curve <short Weierstrass curve>` over a
  53. prime field.
  54. """
  55. if GMPY: # pragma: no branch
  56. def __init__(self, p, a, b, h=None):
  57. """
  58. The curve of points satisfying y^2 = x^3 + a*x + b (mod p).
  59. h is an integer that is the cofactor of the elliptic curve domain
  60. parameters; it is the number of points satisfying the elliptic
  61. curve equation divided by the order of the base point. It is used
  62. for selection of efficient algorithm for public point verification.
  63. """
  64. self.__p = mpz(p)
  65. self.__a = mpz(a)
  66. self.__b = mpz(b)
  67. # h is not used in calculations and it can be None, so don't use
  68. # gmpy with it
  69. self.__h = h
  70. else: # pragma: no branch
  71. def __init__(self, p, a, b, h=None):
  72. """
  73. The curve of points satisfying y^2 = x^3 + a*x + b (mod p).
  74. h is an integer that is the cofactor of the elliptic curve domain
  75. parameters; it is the number of points satisfying the elliptic
  76. curve equation divided by the order of the base point. It is used
  77. for selection of efficient algorithm for public point verification.
  78. """
  79. self.__p = p
  80. self.__a = a
  81. self.__b = b
  82. self.__h = h
  83. def __eq__(self, other):
  84. """Return True if other is an identical curve, False otherwise.
  85. Note: the value of the cofactor of the curve is not taken into account
  86. when comparing curves, as it's derived from the base point and
  87. intrinsic curve characteristic (but it's complex to compute),
  88. only the prime and curve parameters are considered.
  89. """
  90. if isinstance(other, CurveFp):
  91. p = self.__p
  92. return (
  93. self.__p == other.__p
  94. and self.__a % p == other.__a % p
  95. and self.__b % p == other.__b % p
  96. )
  97. return NotImplemented
  98. def __ne__(self, other):
  99. """Return False if other is an identical curve, True otherwise."""
  100. return not self == other
  101. def __hash__(self):
  102. return hash((self.__p, self.__a, self.__b))
  103. def p(self):
  104. return self.__p
  105. def a(self):
  106. return self.__a
  107. def b(self):
  108. return self.__b
  109. def cofactor(self):
  110. return self.__h
  111. def contains_point(self, x, y):
  112. """Is the point (x,y) on this curve?"""
  113. return (y * y - ((x * x + self.__a) * x + self.__b)) % self.__p == 0
  114. def __str__(self):
  115. if self.__h is not None:
  116. return "CurveFp(p={0}, a={1}, b={2}, h={3})".format(
  117. self.__p,
  118. self.__a,
  119. self.__b,
  120. self.__h,
  121. )
  122. return "CurveFp(p={0}, a={1}, b={2})".format(
  123. self.__p,
  124. self.__a,
  125. self.__b,
  126. )
  127. class CurveEdTw(object):
  128. """Parameters for a Twisted Edwards Elliptic Curve"""
  129. if GMPY: # pragma: no branch
  130. def __init__(self, p, a, d, h=None, hash_func=None):
  131. """
  132. The curve of points satisfying a*x^2 + y^2 = 1 + d*x^2*y^2 (mod p).
  133. h is the cofactor of the curve.
  134. hash_func is the hash function associated with the curve
  135. (like SHA-512 for Ed25519)
  136. """
  137. self.__p = mpz(p)
  138. self.__a = mpz(a)
  139. self.__d = mpz(d)
  140. self.__h = h
  141. self.__hash_func = hash_func
  142. else:
  143. def __init__(self, p, a, d, h=None, hash_func=None):
  144. """
  145. The curve of points satisfying a*x^2 + y^2 = 1 + d*x^2*y^2 (mod p).
  146. h is the cofactor of the curve.
  147. hash_func is the hash function associated with the curve
  148. (like SHA-512 for Ed25519)
  149. """
  150. self.__p = p
  151. self.__a = a
  152. self.__d = d
  153. self.__h = h
  154. self.__hash_func = hash_func
  155. def __eq__(self, other):
  156. """Returns True if other is an identical curve."""
  157. if isinstance(other, CurveEdTw):
  158. p = self.__p
  159. return (
  160. self.__p == other.__p
  161. and self.__a % p == other.__a % p
  162. and self.__d % p == other.__d % p
  163. )
  164. return NotImplemented
  165. def __ne__(self, other):
  166. """Return False if the other is an identical curve, True otherwise."""
  167. return not self == other
  168. def __hash__(self):
  169. return hash((self.__p, self.__a, self.__d))
  170. def contains_point(self, x, y):
  171. """Is the point (x, y) on this curve?"""
  172. return (
  173. self.__a * x * x + y * y - 1 - self.__d * x * x * y * y
  174. ) % self.__p == 0
  175. def p(self):
  176. return self.__p
  177. def a(self):
  178. return self.__a
  179. def d(self):
  180. return self.__d
  181. def hash_func(self, data):
  182. return self.__hash_func(data)
  183. def cofactor(self):
  184. return self.__h
  185. def __str__(self):
  186. if self.__h is not None:
  187. return "CurveEdTw(p={0}, a={1}, d={2}, h={3})".format(
  188. self.__p,
  189. self.__a,
  190. self.__d,
  191. self.__h,
  192. )
  193. return "CurveEdTw(p={0}, a={1}, d={2})".format(
  194. self.__p,
  195. self.__a,
  196. self.__d,
  197. )
  198. class AbstractPoint(object):
  199. """Class for common methods of elliptic curve points."""
  200. @staticmethod
  201. def _from_raw_encoding(data, raw_encoding_length):
  202. """
  203. Decode public point from :term:`raw encoding`.
  204. :term:`raw encoding` is the same as the :term:`uncompressed` encoding,
  205. but without the 0x04 byte at the beginning.
  206. """
  207. # real assert, from_bytes() should not call us with different length
  208. assert len(data) == raw_encoding_length
  209. xs = data[: raw_encoding_length // 2]
  210. ys = data[raw_encoding_length // 2 :]
  211. # real assert, raw_encoding_length is calculated by multiplying an
  212. # integer by two so it will always be even
  213. assert len(xs) == raw_encoding_length // 2
  214. assert len(ys) == raw_encoding_length // 2
  215. coord_x = string_to_number(xs)
  216. coord_y = string_to_number(ys)
  217. return coord_x, coord_y
  218. @staticmethod
  219. def _from_compressed(data, curve):
  220. """Decode public point from compressed encoding."""
  221. if data[:1] not in (b"\x02", b"\x03"):
  222. raise MalformedPointError("Malformed compressed point encoding")
  223. is_even = data[:1] == b"\x02"
  224. x = string_to_number(data[1:])
  225. p = curve.p()
  226. alpha = (pow(x, 3, p) + (curve.a() * x) + curve.b()) % p
  227. try:
  228. beta = numbertheory.square_root_mod_prime(alpha, p)
  229. except numbertheory.Error as e:
  230. raise MalformedPointError(
  231. "Encoding does not correspond to a point on curve", e
  232. )
  233. if is_even == bool(beta & 1):
  234. y = p - beta
  235. else:
  236. y = beta
  237. return x, y
  238. @classmethod
  239. def _from_hybrid(cls, data, raw_encoding_length, validate_encoding):
  240. """Decode public point from hybrid encoding."""
  241. # real assert, from_bytes() should not call us with different types
  242. assert data[:1] in (b"\x06", b"\x07")
  243. # primarily use the uncompressed as it's easiest to handle
  244. x, y = cls._from_raw_encoding(data[1:], raw_encoding_length)
  245. # but validate if it's self-consistent if we're asked to do that
  246. if validate_encoding and (
  247. y & 1
  248. and data[:1] != b"\x07"
  249. or (not y & 1)
  250. and data[:1] != b"\x06"
  251. ):
  252. raise MalformedPointError("Inconsistent hybrid point encoding")
  253. return x, y
  254. @classmethod
  255. def _from_edwards(cls, curve, data):
  256. """Decode a point on an Edwards curve."""
  257. data = bytearray(data)
  258. p = curve.p()
  259. # add 1 for the sign bit and then round up
  260. exp_len = (bit_length(p) + 1 + 7) // 8
  261. if len(data) != exp_len:
  262. raise MalformedPointError("Point length doesn't match the curve.")
  263. x_0 = (data[-1] & 0x80) >> 7
  264. data[-1] &= 0x80 - 1
  265. y = bytes_to_int(data, "little")
  266. if GMPY:
  267. y = mpz(y)
  268. x2 = (
  269. (y * y - 1)
  270. * numbertheory.inverse_mod(curve.d() * y * y - curve.a(), p)
  271. % p
  272. )
  273. try:
  274. x = numbertheory.square_root_mod_prime(x2, p)
  275. except numbertheory.Error as e:
  276. raise MalformedPointError(
  277. "Encoding does not correspond to a point on curve", e
  278. )
  279. if x % 2 != x_0:
  280. x = -x % p
  281. return x, y
  282. @classmethod
  283. def from_bytes(
  284. cls, curve, data, validate_encoding=True, valid_encodings=None
  285. ):
  286. """
  287. Initialise the object from byte encoding of a point.
  288. The method does accept and automatically detect the type of point
  289. encoding used. It supports the :term:`raw encoding`,
  290. :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings.
  291. Note: generally you will want to call the ``from_bytes()`` method of
  292. either a child class, PointJacobi or Point.
  293. :param data: single point encoding of the public key
  294. :type data: :term:`bytes-like object`
  295. :param curve: the curve on which the public key is expected to lay
  296. :type curve: ~ecdsa.ellipticcurve.CurveFp
  297. :param validate_encoding: whether to verify that the encoding of the
  298. point is self-consistent, defaults to True, has effect only
  299. on ``hybrid`` encoding
  300. :type validate_encoding: bool
  301. :param valid_encodings: list of acceptable point encoding formats,
  302. supported ones are: :term:`uncompressed`, :term:`compressed`,
  303. :term:`hybrid`, and :term:`raw encoding` (specified with ``raw``
  304. name). All formats by default (specified with ``None``).
  305. :type valid_encodings: :term:`set-like object`
  306. :raises `~ecdsa.errors.MalformedPointError`: if the public point does
  307. not lay on the curve or the encoding is invalid
  308. :return: x and y coordinates of the encoded point
  309. :rtype: tuple(int, int)
  310. """
  311. if not valid_encodings:
  312. valid_encodings = set(
  313. ["uncompressed", "compressed", "hybrid", "raw"]
  314. )
  315. if not all(
  316. i in set(("uncompressed", "compressed", "hybrid", "raw"))
  317. for i in valid_encodings
  318. ):
  319. raise ValueError(
  320. "Only uncompressed, compressed, hybrid or raw encoding "
  321. "supported."
  322. )
  323. data = normalise_bytes(data)
  324. if isinstance(curve, CurveEdTw):
  325. return cls._from_edwards(curve, data)
  326. key_len = len(data)
  327. raw_encoding_length = 2 * orderlen(curve.p())
  328. if key_len == raw_encoding_length and "raw" in valid_encodings:
  329. coord_x, coord_y = cls._from_raw_encoding(
  330. data, raw_encoding_length
  331. )
  332. elif key_len == raw_encoding_length + 1 and (
  333. "hybrid" in valid_encodings or "uncompressed" in valid_encodings
  334. ):
  335. if data[:1] in (b"\x06", b"\x07") and "hybrid" in valid_encodings:
  336. coord_x, coord_y = cls._from_hybrid(
  337. data, raw_encoding_length, validate_encoding
  338. )
  339. elif data[:1] == b"\x04" and "uncompressed" in valid_encodings:
  340. coord_x, coord_y = cls._from_raw_encoding(
  341. data[1:], raw_encoding_length
  342. )
  343. else:
  344. raise MalformedPointError(
  345. "Invalid X9.62 encoding of the public point"
  346. )
  347. elif (
  348. key_len == raw_encoding_length // 2 + 1
  349. and "compressed" in valid_encodings
  350. ):
  351. coord_x, coord_y = cls._from_compressed(data, curve)
  352. else:
  353. raise MalformedPointError(
  354. "Length of string does not match lengths of "
  355. "any of the enabled ({0}) encodings of the "
  356. "curve.".format(", ".join(valid_encodings))
  357. )
  358. return coord_x, coord_y
  359. def _raw_encode(self):
  360. """Convert the point to the :term:`raw encoding`."""
  361. prime = self.curve().p()
  362. x_str = number_to_string(self.x(), prime)
  363. y_str = number_to_string(self.y(), prime)
  364. return x_str + y_str
  365. def _compressed_encode(self):
  366. """Encode the point into the compressed form."""
  367. prime = self.curve().p()
  368. x_str = number_to_string(self.x(), prime)
  369. if self.y() & 1:
  370. return b"\x03" + x_str
  371. return b"\x02" + x_str
  372. def _hybrid_encode(self):
  373. """Encode the point into the hybrid form."""
  374. raw_enc = self._raw_encode()
  375. if self.y() & 1:
  376. return b"\x07" + raw_enc
  377. return b"\x06" + raw_enc
  378. def _edwards_encode(self):
  379. """Encode the point according to RFC8032 encoding."""
  380. self.scale()
  381. x, y, p = self.x(), self.y(), self.curve().p()
  382. # add 1 for the sign bit and then round up
  383. enc_len = (bit_length(p) + 1 + 7) // 8
  384. y_str = int_to_bytes(y, enc_len, "little")
  385. if x % 2:
  386. y_str[-1] |= 0x80
  387. return y_str
  388. def to_bytes(self, encoding="raw"):
  389. """
  390. Convert the point to a byte string.
  391. The method by default uses the :term:`raw encoding` (specified
  392. by `encoding="raw"`. It can also output points in :term:`uncompressed`,
  393. :term:`compressed`, and :term:`hybrid` formats.
  394. For points on Edwards curves `encoding` is ignored and only the
  395. encoding defined in RFC 8032 is supported.
  396. :return: :term:`raw encoding` of a public on the curve
  397. :rtype: bytes
  398. """
  399. assert encoding in ("raw", "uncompressed", "compressed", "hybrid")
  400. curve = self.curve()
  401. if isinstance(curve, CurveEdTw):
  402. return self._edwards_encode()
  403. elif encoding == "raw":
  404. return self._raw_encode()
  405. elif encoding == "uncompressed":
  406. return b"\x04" + self._raw_encode()
  407. elif encoding == "hybrid":
  408. return self._hybrid_encode()
  409. else:
  410. return self._compressed_encode()
  411. @staticmethod
  412. def _naf(mult):
  413. """Calculate non-adjacent form of number."""
  414. ret = []
  415. while mult:
  416. if mult % 2:
  417. nd = mult % 4
  418. if nd >= 2:
  419. nd -= 4
  420. ret.append(nd)
  421. mult -= nd
  422. else:
  423. ret.append(0)
  424. mult //= 2
  425. return ret
  426. class PointJacobi(AbstractPoint):
  427. """
  428. Point on a short Weierstrass elliptic curve. Uses Jacobi coordinates.
  429. In Jacobian coordinates, there are three parameters, X, Y and Z.
  430. They correspond to affine parameters 'x' and 'y' like so:
  431. x = X / Z²
  432. y = Y / Z³
  433. """
  434. def __init__(self, curve, x, y, z, order=None, generator=False):
  435. """
  436. Initialise a point that uses Jacobi representation internally.
  437. :param CurveFp curve: curve on which the point resides
  438. :param int x: the X parameter of Jacobi representation (equal to x when
  439. converting from affine coordinates
  440. :param int y: the Y parameter of Jacobi representation (equal to y when
  441. converting from affine coordinates
  442. :param int z: the Z parameter of Jacobi representation (equal to 1 when
  443. converting from affine coordinates
  444. :param int order: the point order, must be non zero when using
  445. generator=True
  446. :param bool generator: the point provided is a curve generator, as
  447. such, it will be commonly used with scalar multiplication. This will
  448. cause to precompute multiplication table generation for it
  449. """
  450. super(PointJacobi, self).__init__()
  451. self.__curve = curve
  452. if GMPY: # pragma: no branch
  453. self.__coords = (mpz(x), mpz(y), mpz(z))
  454. self.__order = order and mpz(order)
  455. else: # pragma: no branch
  456. self.__coords = (x, y, z)
  457. self.__order = order
  458. self.__generator = generator
  459. self.__precompute = []
  460. @classmethod
  461. def from_bytes(
  462. cls,
  463. curve,
  464. data,
  465. validate_encoding=True,
  466. valid_encodings=None,
  467. order=None,
  468. generator=False,
  469. ):
  470. """
  471. Initialise the object from byte encoding of a point.
  472. The method does accept and automatically detect the type of point
  473. encoding used. It supports the :term:`raw encoding`,
  474. :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings.
  475. :param data: single point encoding of the public key
  476. :type data: :term:`bytes-like object`
  477. :param curve: the curve on which the public key is expected to lay
  478. :type curve: ~ecdsa.ellipticcurve.CurveFp
  479. :param validate_encoding: whether to verify that the encoding of the
  480. point is self-consistent, defaults to True, has effect only
  481. on ``hybrid`` encoding
  482. :type validate_encoding: bool
  483. :param valid_encodings: list of acceptable point encoding formats,
  484. supported ones are: :term:`uncompressed`, :term:`compressed`,
  485. :term:`hybrid`, and :term:`raw encoding` (specified with ``raw``
  486. name). All formats by default (specified with ``None``).
  487. :type valid_encodings: :term:`set-like object`
  488. :param int order: the point order, must be non zero when using
  489. generator=True
  490. :param bool generator: the point provided is a curve generator, as
  491. such, it will be commonly used with scalar multiplication. This
  492. will cause to precompute multiplication table generation for it
  493. :raises `~ecdsa.errors.MalformedPointError`: if the public point does
  494. not lay on the curve or the encoding is invalid
  495. :return: Point on curve
  496. :rtype: PointJacobi
  497. """
  498. coord_x, coord_y = super(PointJacobi, cls).from_bytes(
  499. curve, data, validate_encoding, valid_encodings
  500. )
  501. return PointJacobi(curve, coord_x, coord_y, 1, order, generator)
  502. def _maybe_precompute(self):
  503. if not self.__generator or self.__precompute:
  504. return
  505. # since this code will execute just once, and it's fully deterministic,
  506. # depend on atomicity of the last assignment to switch from empty
  507. # self.__precompute to filled one and just ignore the unlikely
  508. # situation when two threads execute it at the same time (as it won't
  509. # lead to inconsistent __precompute)
  510. order = self.__order
  511. assert order
  512. precompute = []
  513. i = 1
  514. order *= 2
  515. coord_x, coord_y, coord_z = self.__coords
  516. doubler = PointJacobi(self.__curve, coord_x, coord_y, coord_z, order)
  517. order *= 2
  518. precompute.append((doubler.x(), doubler.y()))
  519. while i < order:
  520. i *= 2
  521. doubler = doubler.double().scale()
  522. precompute.append((doubler.x(), doubler.y()))
  523. self.__precompute = precompute
  524. def __getstate__(self):
  525. # while this code can execute at the same time as _maybe_precompute()
  526. # is updating the __precompute or scale() is updating the __coords,
  527. # there is no requirement for consistency between __coords and
  528. # __precompute
  529. state = self.__dict__.copy()
  530. return state
  531. def __setstate__(self, state):
  532. self.__dict__.update(state)
  533. def __eq__(self, other):
  534. """Compare for equality two points with each-other.
  535. Note: only points that lay on the same curve can be equal.
  536. """
  537. x1, y1, z1 = self.__coords
  538. if other is INFINITY:
  539. return not z1
  540. if isinstance(other, Point):
  541. x2, y2, z2 = other.x(), other.y(), 1
  542. elif isinstance(other, PointJacobi):
  543. x2, y2, z2 = other.__coords
  544. else:
  545. return NotImplemented
  546. if self.__curve != other.curve():
  547. return False
  548. p = self.__curve.p()
  549. zz1 = z1 * z1 % p
  550. zz2 = z2 * z2 % p
  551. # compare the fractions by bringing them to the same denominator
  552. # depend on short-circuit to save 4 multiplications in case of
  553. # inequality
  554. return (x1 * zz2 - x2 * zz1) % p == 0 and (
  555. y1 * zz2 * z2 - y2 * zz1 * z1
  556. ) % p == 0
  557. def __ne__(self, other):
  558. """Compare for inequality two points with each-other."""
  559. return not self == other
  560. def order(self):
  561. """Return the order of the point.
  562. None if it is undefined.
  563. """
  564. return self.__order
  565. def curve(self):
  566. """Return curve over which the point is defined."""
  567. return self.__curve
  568. def x(self):
  569. """
  570. Return affine x coordinate.
  571. This method should be used only when the 'y' coordinate is not needed.
  572. It's computationally more efficient to use `to_affine()` and then
  573. call x() and y() on the returned instance. Or call `scale()`
  574. and then x() and y() on the returned instance.
  575. """
  576. x, _, z = self.__coords
  577. if z == 1:
  578. return x
  579. p = self.__curve.p()
  580. z = numbertheory.inverse_mod(z, p)
  581. return x * z**2 % p
  582. def y(self):
  583. """
  584. Return affine y coordinate.
  585. This method should be used only when the 'x' coordinate is not needed.
  586. It's computationally more efficient to use `to_affine()` and then
  587. call x() and y() on the returned instance. Or call `scale()`
  588. and then x() and y() on the returned instance.
  589. """
  590. _, y, z = self.__coords
  591. if z == 1:
  592. return y
  593. p = self.__curve.p()
  594. z = numbertheory.inverse_mod(z, p)
  595. return y * z**3 % p
  596. def scale(self):
  597. """
  598. Return point scaled so that z == 1.
  599. Modifies point in place, returns self.
  600. """
  601. x, y, z = self.__coords
  602. if z == 1:
  603. return self
  604. # scaling is deterministic, so even if two threads execute the below
  605. # code at the same time, they will set __coords to the same value
  606. p = self.__curve.p()
  607. z_inv = numbertheory.inverse_mod(z, p)
  608. zz_inv = z_inv * z_inv % p
  609. x = x * zz_inv % p
  610. y = y * zz_inv * z_inv % p
  611. self.__coords = (x, y, 1)
  612. return self
  613. def to_affine(self):
  614. """Return point in affine form."""
  615. _, _, z = self.__coords
  616. p = self.__curve.p()
  617. if not (z % p):
  618. return INFINITY
  619. self.scale()
  620. x, y, z = self.__coords
  621. assert z == 1
  622. return Point(self.__curve, x, y, self.__order)
  623. @staticmethod
  624. def from_affine(point, generator=False):
  625. """Create from an affine point.
  626. :param bool generator: set to True to make the point to precalculate
  627. multiplication table - useful for public point when verifying many
  628. signatures (around 100 or so) or for generator points of a curve.
  629. """
  630. return PointJacobi(
  631. point.curve(), point.x(), point.y(), 1, point.order(), generator
  632. )
  633. # please note that all the methods that use the equations from
  634. # hyperelliptic
  635. # are formatted in a way to maximise performance.
  636. # Things that make code faster: multiplying instead of taking to the power
  637. # (`xx = x * x; xxxx = xx * xx % p` is faster than `xxxx = x**4 % p` and
  638. # `pow(x, 4, p)`),
  639. # multiple assignments at the same time (`x1, x2 = self.x1, self.x2` is
  640. # faster than `x1 = self.x1; x2 = self.x2`),
  641. # similarly, sometimes the `% p` is skipped if it makes the calculation
  642. # faster and the result of calculation is later reduced modulo `p`
  643. def _double_with_z_1(self, X1, Y1, p, a):
  644. """Add a point to itself with z == 1."""
  645. # after:
  646. # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-mdbl-2007-bl
  647. XX, YY = X1 * X1 % p, Y1 * Y1 % p
  648. if not YY:
  649. return 0, 0, 0
  650. YYYY = YY * YY % p
  651. S = 2 * ((X1 + YY) ** 2 - XX - YYYY) % p
  652. M = 3 * XX + a
  653. T = (M * M - 2 * S) % p
  654. # X3 = T
  655. Y3 = (M * (S - T) - 8 * YYYY) % p
  656. Z3 = 2 * Y1 % p
  657. return T, Y3, Z3
  658. def _double(self, X1, Y1, Z1, p, a):
  659. """Add a point to itself, arbitrary z."""
  660. if Z1 == 1:
  661. return self._double_with_z_1(X1, Y1, p, a)
  662. if not Z1:
  663. return 0, 0, 0
  664. # after:
  665. # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-2007-bl
  666. XX, YY = X1 * X1 % p, Y1 * Y1 % p
  667. if not YY:
  668. return 0, 0, 0
  669. YYYY = YY * YY % p
  670. ZZ = Z1 * Z1 % p
  671. S = 2 * ((X1 + YY) ** 2 - XX - YYYY) % p
  672. M = (3 * XX + a * ZZ * ZZ) % p
  673. T = (M * M - 2 * S) % p
  674. # X3 = T
  675. Y3 = (M * (S - T) - 8 * YYYY) % p
  676. Z3 = ((Y1 + Z1) ** 2 - YY - ZZ) % p
  677. return T, Y3, Z3
  678. def double(self):
  679. """Add a point to itself."""
  680. X1, Y1, Z1 = self.__coords
  681. if not Z1:
  682. return INFINITY
  683. p, a = self.__curve.p(), self.__curve.a()
  684. X3, Y3, Z3 = self._double(X1, Y1, Z1, p, a)
  685. if not Z3:
  686. return INFINITY
  687. return PointJacobi(self.__curve, X3, Y3, Z3, self.__order)
  688. def _add_with_z_1(self, X1, Y1, X2, Y2, p):
  689. """add points when both Z1 and Z2 equal 1"""
  690. # after:
  691. # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-mmadd-2007-bl
  692. H = X2 - X1
  693. HH = H * H
  694. I = 4 * HH % p
  695. J = H * I
  696. r = 2 * (Y2 - Y1)
  697. if not H and not r:
  698. return self._double_with_z_1(X1, Y1, p, self.__curve.a())
  699. V = X1 * I
  700. X3 = (r**2 - J - 2 * V) % p
  701. Y3 = (r * (V - X3) - 2 * Y1 * J) % p
  702. Z3 = 2 * H % p
  703. return X3, Y3, Z3
  704. def _add_with_z_eq(self, X1, Y1, Z1, X2, Y2, p):
  705. """add points when Z1 == Z2"""
  706. # after:
  707. # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-zadd-2007-m
  708. A = (X2 - X1) ** 2 % p
  709. B = X1 * A % p
  710. C = X2 * A
  711. D = (Y2 - Y1) ** 2 % p
  712. if not A and not D:
  713. return self._double(X1, Y1, Z1, p, self.__curve.a())
  714. X3 = (D - B - C) % p
  715. Y3 = ((Y2 - Y1) * (B - X3) - Y1 * (C - B)) % p
  716. Z3 = Z1 * (X2 - X1) % p
  717. return X3, Y3, Z3
  718. def _add_with_z2_1(self, X1, Y1, Z1, X2, Y2, p):
  719. """add points when Z2 == 1"""
  720. # after:
  721. # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-madd-2007-bl
  722. Z1Z1 = Z1 * Z1 % p
  723. U2, S2 = X2 * Z1Z1 % p, Y2 * Z1 * Z1Z1 % p
  724. H = (U2 - X1) % p
  725. HH = H * H % p
  726. I = 4 * HH % p
  727. J = H * I
  728. r = 2 * (S2 - Y1) % p
  729. if not r and not H:
  730. return self._double_with_z_1(X2, Y2, p, self.__curve.a())
  731. V = X1 * I
  732. X3 = (r * r - J - 2 * V) % p
  733. Y3 = (r * (V - X3) - 2 * Y1 * J) % p
  734. Z3 = ((Z1 + H) ** 2 - Z1Z1 - HH) % p
  735. return X3, Y3, Z3
  736. def _add_with_z_ne(self, X1, Y1, Z1, X2, Y2, Z2, p):
  737. """add points with arbitrary z"""
  738. # after:
  739. # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-2007-bl
  740. Z1Z1 = Z1 * Z1 % p
  741. Z2Z2 = Z2 * Z2 % p
  742. U1 = X1 * Z2Z2 % p
  743. U2 = X2 * Z1Z1 % p
  744. S1 = Y1 * Z2 * Z2Z2 % p
  745. S2 = Y2 * Z1 * Z1Z1 % p
  746. H = U2 - U1
  747. I = 4 * H * H % p
  748. J = H * I % p
  749. r = 2 * (S2 - S1) % p
  750. if not H and not r:
  751. return self._double(X1, Y1, Z1, p, self.__curve.a())
  752. V = U1 * I
  753. X3 = (r * r - J - 2 * V) % p
  754. Y3 = (r * (V - X3) - 2 * S1 * J) % p
  755. Z3 = ((Z1 + Z2) ** 2 - Z1Z1 - Z2Z2) * H % p
  756. return X3, Y3, Z3
  757. def __radd__(self, other):
  758. """Add other to self."""
  759. return self + other
  760. def _add(self, X1, Y1, Z1, X2, Y2, Z2, p):
  761. """add two points, select fastest method."""
  762. if not Z1:
  763. return X2 % p, Y2 % p, Z2 % p
  764. if not Z2:
  765. return X1 % p, Y1 % p, Z1 % p
  766. if Z1 == Z2:
  767. if Z1 == 1:
  768. return self._add_with_z_1(X1, Y1, X2, Y2, p)
  769. return self._add_with_z_eq(X1, Y1, Z1, X2, Y2, p)
  770. if Z1 == 1:
  771. return self._add_with_z2_1(X2, Y2, Z2, X1, Y1, p)
  772. if Z2 == 1:
  773. return self._add_with_z2_1(X1, Y1, Z1, X2, Y2, p)
  774. return self._add_with_z_ne(X1, Y1, Z1, X2, Y2, Z2, p)
  775. def __add__(self, other):
  776. """Add two points on elliptic curve."""
  777. if self == INFINITY:
  778. return other
  779. if other == INFINITY:
  780. return self
  781. if isinstance(other, Point):
  782. other = PointJacobi.from_affine(other)
  783. if self.__curve != other.__curve:
  784. raise ValueError("The other point is on different curve")
  785. p = self.__curve.p()
  786. X1, Y1, Z1 = self.__coords
  787. X2, Y2, Z2 = other.__coords
  788. X3, Y3, Z3 = self._add(X1, Y1, Z1, X2, Y2, Z2, p)
  789. if not Z3:
  790. return INFINITY
  791. return PointJacobi(self.__curve, X3, Y3, Z3, self.__order)
  792. def __rmul__(self, other):
  793. """Multiply point by an integer."""
  794. return self * other
  795. def _mul_precompute(self, other):
  796. """Multiply point by integer with precomputation table."""
  797. X3, Y3, Z3, p = 0, 0, 0, self.__curve.p()
  798. _add = self._add
  799. for X2, Y2 in self.__precompute:
  800. if other % 2:
  801. if other % 4 >= 2:
  802. other = (other + 1) // 2
  803. X3, Y3, Z3 = _add(X3, Y3, Z3, X2, -Y2, 1, p)
  804. else:
  805. other = (other - 1) // 2
  806. X3, Y3, Z3 = _add(X3, Y3, Z3, X2, Y2, 1, p)
  807. else:
  808. other //= 2
  809. if not Z3:
  810. return INFINITY
  811. return PointJacobi(self.__curve, X3, Y3, Z3, self.__order)
  812. def __mul__(self, other):
  813. """Multiply point by an integer."""
  814. if not self.__coords[1] or not other:
  815. return INFINITY
  816. if other == 1:
  817. return self
  818. if self.__order:
  819. # order*2 as a protection for Minerva
  820. other = other % (self.__order * 2)
  821. self._maybe_precompute()
  822. if self.__precompute:
  823. return self._mul_precompute(other)
  824. self = self.scale()
  825. X2, Y2, _ = self.__coords
  826. X3, Y3, Z3 = 0, 0, 0
  827. p, a = self.__curve.p(), self.__curve.a()
  828. _double = self._double
  829. _add = self._add
  830. # since adding points when at least one of them is scaled
  831. # is quicker, reverse the NAF order
  832. for i in reversed(self._naf(other)):
  833. X3, Y3, Z3 = _double(X3, Y3, Z3, p, a)
  834. if i < 0:
  835. X3, Y3, Z3 = _add(X3, Y3, Z3, X2, -Y2, 1, p)
  836. elif i > 0:
  837. X3, Y3, Z3 = _add(X3, Y3, Z3, X2, Y2, 1, p)
  838. if not Z3:
  839. return INFINITY
  840. return PointJacobi(self.__curve, X3, Y3, Z3, self.__order)
  841. def mul_add(self, self_mul, other, other_mul):
  842. """
  843. Do two multiplications at the same time, add results.
  844. calculates self*self_mul + other*other_mul
  845. """
  846. if other == INFINITY or other_mul == 0:
  847. return self * self_mul
  848. if self_mul == 0:
  849. return other * other_mul
  850. if not isinstance(other, PointJacobi):
  851. other = PointJacobi.from_affine(other)
  852. # when the points have precomputed answers, then multiplying them alone
  853. # is faster (as it uses NAF and no point doublings)
  854. self._maybe_precompute()
  855. other._maybe_precompute()
  856. if self.__precompute and other.__precompute:
  857. return self * self_mul + other * other_mul
  858. if self.__order:
  859. self_mul = self_mul % self.__order
  860. other_mul = other_mul % self.__order
  861. # (X3, Y3, Z3) is the accumulator
  862. X3, Y3, Z3 = 0, 0, 0
  863. p, a = self.__curve.p(), self.__curve.a()
  864. # as we have 6 unique points to work with, we can't scale all of them,
  865. # but do scale the ones that are used most often
  866. self.scale()
  867. X1, Y1, Z1 = self.__coords
  868. other.scale()
  869. X2, Y2, Z2 = other.__coords
  870. _double = self._double
  871. _add = self._add
  872. # with NAF we have 3 options: no add, subtract, add
  873. # so with 2 points, we have 9 combinations:
  874. # 0, -A, +A, -B, -A-B, +A-B, +B, -A+B, +A+B
  875. # so we need 4 combined points:
  876. mAmB_X, mAmB_Y, mAmB_Z = _add(X1, -Y1, Z1, X2, -Y2, Z2, p)
  877. pAmB_X, pAmB_Y, pAmB_Z = _add(X1, Y1, Z1, X2, -Y2, Z2, p)
  878. mApB_X, mApB_Y, mApB_Z = pAmB_X, -pAmB_Y, pAmB_Z
  879. pApB_X, pApB_Y, pApB_Z = mAmB_X, -mAmB_Y, mAmB_Z
  880. # when the self and other sum to infinity, we need to add them
  881. # one by one to get correct result but as that's very unlikely to
  882. # happen in regular operation, we don't need to optimise this case
  883. if not pApB_Z:
  884. return self * self_mul + other * other_mul
  885. # gmp object creation has cumulatively higher overhead than the
  886. # speedup we get from calculating the NAF using gmp so ensure use
  887. # of int()
  888. self_naf = list(reversed(self._naf(int(self_mul))))
  889. other_naf = list(reversed(self._naf(int(other_mul))))
  890. # ensure that the lists are the same length (zip() will truncate
  891. # longer one otherwise)
  892. if len(self_naf) < len(other_naf):
  893. self_naf = [0] * (len(other_naf) - len(self_naf)) + self_naf
  894. elif len(self_naf) > len(other_naf):
  895. other_naf = [0] * (len(self_naf) - len(other_naf)) + other_naf
  896. for A, B in zip(self_naf, other_naf):
  897. X3, Y3, Z3 = _double(X3, Y3, Z3, p, a)
  898. # conditions ordered from most to least likely
  899. if A == 0:
  900. if B == 0:
  901. pass
  902. elif B < 0:
  903. X3, Y3, Z3 = _add(X3, Y3, Z3, X2, -Y2, Z2, p)
  904. else:
  905. assert B > 0
  906. X3, Y3, Z3 = _add(X3, Y3, Z3, X2, Y2, Z2, p)
  907. elif A < 0:
  908. if B == 0:
  909. X3, Y3, Z3 = _add(X3, Y3, Z3, X1, -Y1, Z1, p)
  910. elif B < 0:
  911. X3, Y3, Z3 = _add(X3, Y3, Z3, mAmB_X, mAmB_Y, mAmB_Z, p)
  912. else:
  913. assert B > 0
  914. X3, Y3, Z3 = _add(X3, Y3, Z3, mApB_X, mApB_Y, mApB_Z, p)
  915. else:
  916. assert A > 0
  917. if B == 0:
  918. X3, Y3, Z3 = _add(X3, Y3, Z3, X1, Y1, Z1, p)
  919. elif B < 0:
  920. X3, Y3, Z3 = _add(X3, Y3, Z3, pAmB_X, pAmB_Y, pAmB_Z, p)
  921. else:
  922. assert B > 0
  923. X3, Y3, Z3 = _add(X3, Y3, Z3, pApB_X, pApB_Y, pApB_Z, p)
  924. if not Z3:
  925. return INFINITY
  926. return PointJacobi(self.__curve, X3, Y3, Z3, self.__order)
  927. def __neg__(self):
  928. """Return negated point."""
  929. x, y, z = self.__coords
  930. return PointJacobi(self.__curve, x, -y, z, self.__order)
  931. class Point(AbstractPoint):
  932. """A point on a short Weierstrass elliptic curve. Altering x and y is
  933. forbidden, but they can be read by the x() and y() methods."""
  934. def __init__(self, curve, x, y, order=None):
  935. """curve, x, y, order; order (optional) is the order of this point."""
  936. super(Point, self).__init__()
  937. self.__curve = curve
  938. if GMPY:
  939. self.__x = x and mpz(x)
  940. self.__y = y and mpz(y)
  941. self.__order = order and mpz(order)
  942. else:
  943. self.__x = x
  944. self.__y = y
  945. self.__order = order
  946. # self.curve is allowed to be None only for INFINITY:
  947. if self.__curve:
  948. assert self.__curve.contains_point(x, y)
  949. # for curves with cofactor 1, all points that are on the curve are
  950. # scalar multiples of the base point, so performing multiplication is
  951. # not necessary to verify that. See Section 3.2.2.1 of SEC 1 v2
  952. if curve and curve.cofactor() != 1 and order:
  953. assert self * order == INFINITY
  954. @classmethod
  955. def from_bytes(
  956. cls,
  957. curve,
  958. data,
  959. validate_encoding=True,
  960. valid_encodings=None,
  961. order=None,
  962. ):
  963. """
  964. Initialise the object from byte encoding of a point.
  965. The method does accept and automatically detect the type of point
  966. encoding used. It supports the :term:`raw encoding`,
  967. :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings.
  968. :param data: single point encoding of the public key
  969. :type data: :term:`bytes-like object`
  970. :param curve: the curve on which the public key is expected to lay
  971. :type curve: ~ecdsa.ellipticcurve.CurveFp
  972. :param validate_encoding: whether to verify that the encoding of the
  973. point is self-consistent, defaults to True, has effect only
  974. on ``hybrid`` encoding
  975. :type validate_encoding: bool
  976. :param valid_encodings: list of acceptable point encoding formats,
  977. supported ones are: :term:`uncompressed`, :term:`compressed`,
  978. :term:`hybrid`, and :term:`raw encoding` (specified with ``raw``
  979. name). All formats by default (specified with ``None``).
  980. :type valid_encodings: :term:`set-like object`
  981. :param int order: the point order, must be non zero when using
  982. generator=True
  983. :raises `~ecdsa.errors.MalformedPointError`: if the public point does
  984. not lay on the curve or the encoding is invalid
  985. :return: Point on curve
  986. :rtype: Point
  987. """
  988. coord_x, coord_y = super(Point, cls).from_bytes(
  989. curve, data, validate_encoding, valid_encodings
  990. )
  991. return Point(curve, coord_x, coord_y, order)
  992. def __eq__(self, other):
  993. """Return True if the points are identical, False otherwise.
  994. Note: only points that lay on the same curve can be equal.
  995. """
  996. if other is INFINITY:
  997. return self.__x is None or self.__y is None
  998. if isinstance(other, Point):
  999. return (
  1000. self.__curve == other.__curve
  1001. and self.__x == other.__x
  1002. and self.__y == other.__y
  1003. )
  1004. return NotImplemented
  1005. def __ne__(self, other):
  1006. """Returns False if points are identical, True otherwise."""
  1007. return not self == other
  1008. def __neg__(self):
  1009. return Point(self.__curve, self.__x, self.__curve.p() - self.__y)
  1010. def __add__(self, other):
  1011. """Add one point to another point."""
  1012. # X9.62 B.3:
  1013. if not isinstance(other, Point):
  1014. return NotImplemented
  1015. if other == INFINITY:
  1016. return self
  1017. if self == INFINITY:
  1018. return other
  1019. assert self.__curve == other.__curve
  1020. if self.__x == other.__x:
  1021. if (self.__y + other.__y) % self.__curve.p() == 0:
  1022. return INFINITY
  1023. else:
  1024. return self.double()
  1025. p = self.__curve.p()
  1026. l = (
  1027. (other.__y - self.__y)
  1028. * numbertheory.inverse_mod(other.__x - self.__x, p)
  1029. ) % p
  1030. x3 = (l * l - self.__x - other.__x) % p
  1031. y3 = (l * (self.__x - x3) - self.__y) % p
  1032. return Point(self.__curve, x3, y3)
  1033. def __mul__(self, other):
  1034. """Multiply a point by an integer."""
  1035. def leftmost_bit(x):
  1036. assert x > 0
  1037. result = 1
  1038. while result <= x:
  1039. result = 2 * result
  1040. return result // 2
  1041. e = other
  1042. if e == 0 or (self.__order and e % self.__order == 0):
  1043. return INFINITY
  1044. if self == INFINITY:
  1045. return INFINITY
  1046. if e < 0:
  1047. return (-self) * (-e)
  1048. # From X9.62 D.3.2:
  1049. e3 = 3 * e
  1050. negative_self = Point(
  1051. self.__curve,
  1052. self.__x,
  1053. (-self.__y) % self.__curve.p(),
  1054. self.__order,
  1055. )
  1056. i = leftmost_bit(e3) // 2
  1057. result = self
  1058. # print("Multiplying %s by %d (e3 = %d):" % (self, other, e3))
  1059. while i > 1:
  1060. result = result.double()
  1061. if (e3 & i) != 0 and (e & i) == 0:
  1062. result = result + self
  1063. if (e3 & i) == 0 and (e & i) != 0:
  1064. result = result + negative_self
  1065. # print(". . . i = %d, result = %s" % ( i, result ))
  1066. i = i // 2
  1067. return result
  1068. def __rmul__(self, other):
  1069. """Multiply a point by an integer."""
  1070. return self * other
  1071. def __str__(self):
  1072. if self == INFINITY:
  1073. return "infinity"
  1074. return "(%d,%d)" % (self.__x, self.__y)
  1075. def double(self):
  1076. """Return a new point that is twice the old."""
  1077. if self == INFINITY:
  1078. return INFINITY
  1079. # X9.62 B.3:
  1080. p = self.__curve.p()
  1081. a = self.__curve.a()
  1082. l = (
  1083. (3 * self.__x * self.__x + a)
  1084. * numbertheory.inverse_mod(2 * self.__y, p)
  1085. ) % p
  1086. if not l:
  1087. return INFINITY
  1088. x3 = (l * l - 2 * self.__x) % p
  1089. y3 = (l * (self.__x - x3) - self.__y) % p
  1090. return Point(self.__curve, x3, y3)
  1091. def x(self):
  1092. return self.__x
  1093. def y(self):
  1094. return self.__y
  1095. def curve(self):
  1096. return self.__curve
  1097. def order(self):
  1098. return self.__order
  1099. class PointEdwards(AbstractPoint):
  1100. """Point on Twisted Edwards curve.
  1101. Internally represents the coordinates on the curve using four parameters,
  1102. X, Y, Z, T. They correspond to affine parameters 'x' and 'y' like so:
  1103. x = X / Z
  1104. y = Y / Z
  1105. x*y = T / Z
  1106. """
  1107. def __init__(self, curve, x, y, z, t, order=None, generator=False):
  1108. """
  1109. Initialise a point that uses the extended coordinates internally.
  1110. """
  1111. super(PointEdwards, self).__init__()
  1112. self.__curve = curve
  1113. if GMPY: # pragma: no branch
  1114. self.__coords = (mpz(x), mpz(y), mpz(z), mpz(t))
  1115. self.__order = order and mpz(order)
  1116. else: # pragma: no branch
  1117. self.__coords = (x, y, z, t)
  1118. self.__order = order
  1119. self.__generator = generator
  1120. self.__precompute = []
  1121. @classmethod
  1122. def from_bytes(
  1123. cls,
  1124. curve,
  1125. data,
  1126. validate_encoding=None,
  1127. valid_encodings=None,
  1128. order=None,
  1129. generator=False,
  1130. ):
  1131. """
  1132. Initialise the object from byte encoding of a point.
  1133. `validate_encoding` and `valid_encodings` are provided for
  1134. compatibility with Weierstrass curves, they are ignored for Edwards
  1135. points.
  1136. :param data: single point encoding of the public key
  1137. :type data: :term:`bytes-like object`
  1138. :param curve: the curve on which the public key is expected to lay
  1139. :type curve: ecdsa.ellipticcurve.CurveEdTw
  1140. :param None validate_encoding: Ignored, encoding is always validated
  1141. :param None valid_encodings: Ignored, there is just one encoding
  1142. supported
  1143. :param int order: the point order, must be non zero when using
  1144. generator=True
  1145. :param bool generator: Flag to mark the point as a curve generator,
  1146. this will cause the library to pre-compute some values to
  1147. make repeated usages of the point much faster
  1148. :raises `~ecdsa.errors.MalformedPointError`: if the public point does
  1149. not lay on the curve or the encoding is invalid
  1150. :return: Initialised point on an Edwards curve
  1151. :rtype: PointEdwards
  1152. """
  1153. coord_x, coord_y = super(PointEdwards, cls).from_bytes(
  1154. curve, data, validate_encoding, valid_encodings
  1155. )
  1156. return PointEdwards(
  1157. curve, coord_x, coord_y, 1, coord_x * coord_y, order, generator
  1158. )
  1159. def _maybe_precompute(self):
  1160. if not self.__generator or self.__precompute:
  1161. return self.__precompute
  1162. # since this code will execute just once, and it's fully deterministic,
  1163. # depend on atomicity of the last assignment to switch from empty
  1164. # self.__precompute to filled one and just ignore the unlikely
  1165. # situation when two threads execute it at the same time (as it won't
  1166. # lead to inconsistent __precompute)
  1167. order = self.__order
  1168. assert order
  1169. precompute = []
  1170. i = 1
  1171. order *= 2
  1172. coord_x, coord_y, coord_z, coord_t = self.__coords
  1173. prime = self.__curve.p()
  1174. doubler = PointEdwards(
  1175. self.__curve, coord_x, coord_y, coord_z, coord_t, order
  1176. )
  1177. # for "protection" against Minerva we need 1 or 2 more bits depending
  1178. # on order bit size, but it's easier to just calculate one
  1179. # point more always
  1180. order *= 4
  1181. while i < order:
  1182. doubler = doubler.scale()
  1183. coord_x, coord_y = doubler.x(), doubler.y()
  1184. coord_t = coord_x * coord_y % prime
  1185. precompute.append((coord_x, coord_y, coord_t))
  1186. i *= 2
  1187. doubler = doubler.double()
  1188. self.__precompute = precompute
  1189. return self.__precompute
  1190. def x(self):
  1191. """Return affine x coordinate."""
  1192. X1, _, Z1, _ = self.__coords
  1193. if Z1 == 1:
  1194. return X1
  1195. p = self.__curve.p()
  1196. z_inv = numbertheory.inverse_mod(Z1, p)
  1197. return X1 * z_inv % p
  1198. def y(self):
  1199. """Return affine y coordinate."""
  1200. _, Y1, Z1, _ = self.__coords
  1201. if Z1 == 1:
  1202. return Y1
  1203. p = self.__curve.p()
  1204. z_inv = numbertheory.inverse_mod(Z1, p)
  1205. return Y1 * z_inv % p
  1206. def curve(self):
  1207. """Return the curve of the point."""
  1208. return self.__curve
  1209. def order(self):
  1210. return self.__order
  1211. def scale(self):
  1212. """
  1213. Return point scaled so that z == 1.
  1214. Modifies point in place, returns self.
  1215. """
  1216. X1, Y1, Z1, _ = self.__coords
  1217. if Z1 == 1:
  1218. return self
  1219. p = self.__curve.p()
  1220. z_inv = numbertheory.inverse_mod(Z1, p)
  1221. x = X1 * z_inv % p
  1222. y = Y1 * z_inv % p
  1223. t = x * y % p
  1224. self.__coords = (x, y, 1, t)
  1225. return self
  1226. def __eq__(self, other):
  1227. """Compare for equality two points with each-other.
  1228. Note: only points on the same curve can be equal.
  1229. """
  1230. x1, y1, z1, t1 = self.__coords
  1231. if other is INFINITY:
  1232. return not x1 or not t1
  1233. if isinstance(other, PointEdwards):
  1234. x2, y2, z2, t2 = other.__coords
  1235. else:
  1236. return NotImplemented
  1237. if self.__curve != other.curve():
  1238. return False
  1239. p = self.__curve.p()
  1240. # cross multiply to eliminate divisions
  1241. xn1 = x1 * z2 % p
  1242. xn2 = x2 * z1 % p
  1243. yn1 = y1 * z2 % p
  1244. yn2 = y2 * z1 % p
  1245. return xn1 == xn2 and yn1 == yn2
  1246. def __ne__(self, other):
  1247. """Compare for inequality two points with each-other."""
  1248. return not self == other
  1249. def _add(self, X1, Y1, Z1, T1, X2, Y2, Z2, T2, p, a):
  1250. """add two points, assume sane parameters."""
  1251. # after add-2008-hwcd-2
  1252. # from https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html
  1253. # NOTE: there are more efficient formulas for Z1 or Z2 == 1
  1254. A = X1 * X2 % p
  1255. B = Y1 * Y2 % p
  1256. C = Z1 * T2 % p
  1257. D = T1 * Z2 % p
  1258. E = D + C
  1259. F = ((X1 - Y1) * (X2 + Y2) + B - A) % p
  1260. G = B + a * A
  1261. H = D - C
  1262. if not H:
  1263. return self._double(X1, Y1, Z1, T1, p, a)
  1264. X3 = E * F % p
  1265. Y3 = G * H % p
  1266. T3 = E * H % p
  1267. Z3 = F * G % p
  1268. return X3, Y3, Z3, T3
  1269. def __add__(self, other):
  1270. """Add point to another."""
  1271. if other == INFINITY:
  1272. return self
  1273. if (
  1274. not isinstance(other, PointEdwards)
  1275. or self.__curve != other.__curve
  1276. ):
  1277. raise ValueError("The other point is on a different curve.")
  1278. p, a = self.__curve.p(), self.__curve.a()
  1279. X1, Y1, Z1, T1 = self.__coords
  1280. X2, Y2, Z2, T2 = other.__coords
  1281. X3, Y3, Z3, T3 = self._add(X1, Y1, Z1, T1, X2, Y2, Z2, T2, p, a)
  1282. if not X3 or not T3:
  1283. return INFINITY
  1284. return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order)
  1285. def __radd__(self, other):
  1286. """Add other to self."""
  1287. return self + other
  1288. def _double(self, X1, Y1, Z1, T1, p, a):
  1289. """Double the point, assume sane parameters."""
  1290. # after "dbl-2008-hwcd"
  1291. # from https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html
  1292. # NOTE: there are more efficient formulas for Z1 == 1
  1293. A = X1 * X1 % p
  1294. B = Y1 * Y1 % p
  1295. C = 2 * Z1 * Z1 % p
  1296. D = a * A % p
  1297. E = ((X1 + Y1) * (X1 + Y1) - A - B) % p
  1298. G = D + B
  1299. F = G - C
  1300. H = D - B
  1301. X3 = E * F % p
  1302. Y3 = G * H % p
  1303. T3 = E * H % p
  1304. Z3 = F * G % p
  1305. return X3, Y3, Z3, T3
  1306. def double(self):
  1307. """Return point added to itself."""
  1308. X1, Y1, Z1, T1 = self.__coords
  1309. if not X1 or not T1:
  1310. return INFINITY
  1311. p, a = self.__curve.p(), self.__curve.a()
  1312. X3, Y3, Z3, T3 = self._double(X1, Y1, Z1, T1, p, a)
  1313. # both Ed25519 and Ed448 have prime order, so no point added to
  1314. # itself will equal zero
  1315. if not X3 or not T3: # pragma: no branch
  1316. return INFINITY
  1317. return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order)
  1318. def __rmul__(self, other):
  1319. """Multiply point by an integer."""
  1320. return self * other
  1321. def _mul_precompute(self, other):
  1322. """Multiply point by integer with precomputation table."""
  1323. X3, Y3, Z3, T3, p, a = 0, 1, 1, 0, self.__curve.p(), self.__curve.a()
  1324. _add = self._add
  1325. for X2, Y2, T2 in self.__precompute:
  1326. rem = other % 4
  1327. if rem == 0 or rem == 2:
  1328. other //= 2
  1329. elif rem == 3:
  1330. other = (other + 1) // 2
  1331. X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, -X2, Y2, 1, -T2, p, a)
  1332. else:
  1333. assert rem == 1
  1334. other = (other - 1) // 2
  1335. X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, X2, Y2, 1, T2, p, a)
  1336. if not X3 or not T3:
  1337. return INFINITY
  1338. return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order)
  1339. def __mul__(self, other):
  1340. """Multiply point by an integer."""
  1341. X2, Y2, Z2, T2 = self.__coords
  1342. if not X2 or not T2 or not other:
  1343. return INFINITY
  1344. if other == 1:
  1345. return self
  1346. if self.__order:
  1347. # order*2 as a "protection" for Minerva
  1348. other = other % (self.__order * 2)
  1349. if self._maybe_precompute():
  1350. return self._mul_precompute(other)
  1351. X3, Y3, Z3, T3 = 0, 1, 1, 0 # INFINITY in extended coordinates
  1352. p, a = self.__curve.p(), self.__curve.a()
  1353. _double = self._double
  1354. _add = self._add
  1355. for i in reversed(self._naf(other)):
  1356. X3, Y3, Z3, T3 = _double(X3, Y3, Z3, T3, p, a)
  1357. if i < 0:
  1358. X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, -X2, Y2, Z2, -T2, p, a)
  1359. elif i > 0:
  1360. X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, X2, Y2, Z2, T2, p, a)
  1361. if not X3 or not T3:
  1362. return INFINITY
  1363. return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order)
  1364. # This one point is the Point At Infinity for all purposes:
  1365. INFINITY = Point(None, None, None)