ECPoint.cs 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.Diagnostics;
  6. using System.Text;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC
  9. {
  10. /**
  11. * base class for points on elliptic curves.
  12. */
  13. public abstract class ECPoint
  14. {
  15. protected static ECFieldElement[] EMPTY_ZS = new ECFieldElement[0];
  16. protected static ECFieldElement[] GetInitialZCoords(ECCurve curve)
  17. {
  18. // Cope with null curve, most commonly used by implicitlyCa
  19. int coord = null == curve ? ECCurve.COORD_AFFINE : curve.CoordinateSystem;
  20. switch (coord)
  21. {
  22. case ECCurve.COORD_AFFINE:
  23. case ECCurve.COORD_LAMBDA_AFFINE:
  24. return EMPTY_ZS;
  25. default:
  26. break;
  27. }
  28. ECFieldElement one = curve.FromBigInteger(BigInteger.One);
  29. switch (coord)
  30. {
  31. case ECCurve.COORD_HOMOGENEOUS:
  32. case ECCurve.COORD_JACOBIAN:
  33. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  34. return new ECFieldElement[] { one };
  35. case ECCurve.COORD_JACOBIAN_CHUDNOVSKY:
  36. return new ECFieldElement[] { one, one, one };
  37. case ECCurve.COORD_JACOBIAN_MODIFIED:
  38. return new ECFieldElement[] { one, curve.A };
  39. default:
  40. throw new ArgumentException("unknown coordinate system");
  41. }
  42. }
  43. protected internal readonly ECCurve m_curve;
  44. protected internal readonly ECFieldElement m_x, m_y;
  45. protected internal readonly ECFieldElement[] m_zs;
  46. protected internal readonly bool m_withCompression;
  47. // Dictionary is (string -> PreCompInfo)
  48. protected internal IDictionary m_preCompTable = null;
  49. protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
  50. : this(curve, x, y, GetInitialZCoords(curve), withCompression)
  51. {
  52. }
  53. internal ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
  54. {
  55. this.m_curve = curve;
  56. this.m_x = x;
  57. this.m_y = y;
  58. this.m_zs = zs;
  59. this.m_withCompression = withCompression;
  60. }
  61. protected abstract bool SatisfiesCurveEquation();
  62. protected virtual bool SatisfiesOrder()
  63. {
  64. if (BigInteger.One.Equals(Curve.Cofactor))
  65. return true;
  66. BigInteger n = Curve.Order;
  67. // TODO Require order to be available for all curves
  68. return n == null || ECAlgorithms.ReferenceMultiply(this, n).IsInfinity;
  69. }
  70. public ECPoint GetDetachedPoint()
  71. {
  72. return Normalize().Detach();
  73. }
  74. public virtual ECCurve Curve
  75. {
  76. get { return m_curve; }
  77. }
  78. protected abstract ECPoint Detach();
  79. protected virtual int CurveCoordinateSystem
  80. {
  81. get
  82. {
  83. // Cope with null curve, most commonly used by implicitlyCa
  84. return null == m_curve ? ECCurve.COORD_AFFINE : m_curve.CoordinateSystem;
  85. }
  86. }
  87. /**
  88. * Returns the affine x-coordinate after checking that this point is normalized.
  89. *
  90. * @return The affine x-coordinate of this point
  91. * @throws IllegalStateException if the point is not normalized
  92. */
  93. public virtual ECFieldElement AffineXCoord
  94. {
  95. get
  96. {
  97. CheckNormalized();
  98. return XCoord;
  99. }
  100. }
  101. /**
  102. * Returns the affine y-coordinate after checking that this point is normalized
  103. *
  104. * @return The affine y-coordinate of this point
  105. * @throws IllegalStateException if the point is not normalized
  106. */
  107. public virtual ECFieldElement AffineYCoord
  108. {
  109. get
  110. {
  111. CheckNormalized();
  112. return YCoord;
  113. }
  114. }
  115. /**
  116. * Returns the x-coordinate.
  117. *
  118. * Caution: depending on the curve's coordinate system, this may not be the same value as in an
  119. * affine coordinate system; use Normalize() to get a point where the coordinates have their
  120. * affine values, or use AffineXCoord if you expect the point to already have been normalized.
  121. *
  122. * @return the x-coordinate of this point
  123. */
  124. public virtual ECFieldElement XCoord
  125. {
  126. get { return m_x; }
  127. }
  128. /**
  129. * Returns the y-coordinate.
  130. *
  131. * Caution: depending on the curve's coordinate system, this may not be the same value as in an
  132. * affine coordinate system; use Normalize() to get a point where the coordinates have their
  133. * affine values, or use AffineYCoord if you expect the point to already have been normalized.
  134. *
  135. * @return the y-coordinate of this point
  136. */
  137. public virtual ECFieldElement YCoord
  138. {
  139. get { return m_y; }
  140. }
  141. public virtual ECFieldElement GetZCoord(int index)
  142. {
  143. return (index < 0 || index >= m_zs.Length) ? null : m_zs[index];
  144. }
  145. public virtual ECFieldElement[] GetZCoords()
  146. {
  147. int zsLen = m_zs.Length;
  148. if (zsLen == 0)
  149. {
  150. return m_zs;
  151. }
  152. ECFieldElement[] copy = new ECFieldElement[zsLen];
  153. Array.Copy(m_zs, 0, copy, 0, zsLen);
  154. return copy;
  155. }
  156. protected internal ECFieldElement RawXCoord
  157. {
  158. get { return m_x; }
  159. }
  160. protected internal ECFieldElement RawYCoord
  161. {
  162. get { return m_y; }
  163. }
  164. protected internal ECFieldElement[] RawZCoords
  165. {
  166. get { return m_zs; }
  167. }
  168. protected virtual void CheckNormalized()
  169. {
  170. if (!IsNormalized())
  171. throw new InvalidOperationException("point not in normal form");
  172. }
  173. public virtual bool IsNormalized()
  174. {
  175. int coord = this.CurveCoordinateSystem;
  176. return coord == ECCurve.COORD_AFFINE
  177. || coord == ECCurve.COORD_LAMBDA_AFFINE
  178. || IsInfinity
  179. || RawZCoords[0].IsOne;
  180. }
  181. /**
  182. * Normalization ensures that any projective coordinate is 1, and therefore that the x, y
  183. * coordinates reflect those of the equivalent point in an affine coordinate system.
  184. *
  185. * @return a new ECPoint instance representing the same point, but with normalized coordinates
  186. */
  187. public virtual ECPoint Normalize()
  188. {
  189. if (this.IsInfinity)
  190. {
  191. return this;
  192. }
  193. switch (this.CurveCoordinateSystem)
  194. {
  195. case ECCurve.COORD_AFFINE:
  196. case ECCurve.COORD_LAMBDA_AFFINE:
  197. {
  198. return this;
  199. }
  200. default:
  201. {
  202. ECFieldElement Z1 = RawZCoords[0];
  203. if (Z1.IsOne)
  204. {
  205. return this;
  206. }
  207. return Normalize(Z1.Invert());
  208. }
  209. }
  210. }
  211. internal virtual ECPoint Normalize(ECFieldElement zInv)
  212. {
  213. switch (this.CurveCoordinateSystem)
  214. {
  215. case ECCurve.COORD_HOMOGENEOUS:
  216. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  217. {
  218. return CreateScaledPoint(zInv, zInv);
  219. }
  220. case ECCurve.COORD_JACOBIAN:
  221. case ECCurve.COORD_JACOBIAN_CHUDNOVSKY:
  222. case ECCurve.COORD_JACOBIAN_MODIFIED:
  223. {
  224. ECFieldElement zInv2 = zInv.Square(), zInv3 = zInv2.Multiply(zInv);
  225. return CreateScaledPoint(zInv2, zInv3);
  226. }
  227. default:
  228. {
  229. throw new InvalidOperationException("not a projective coordinate system");
  230. }
  231. }
  232. }
  233. protected virtual ECPoint CreateScaledPoint(ECFieldElement sx, ECFieldElement sy)
  234. {
  235. return Curve.CreateRawPoint(RawXCoord.Multiply(sx), RawYCoord.Multiply(sy), IsCompressed);
  236. }
  237. public bool IsInfinity
  238. {
  239. get { return m_x == null && m_y == null; }
  240. }
  241. public bool IsCompressed
  242. {
  243. get { return m_withCompression; }
  244. }
  245. public bool IsValid()
  246. {
  247. return ImplIsValid(false, true);
  248. }
  249. internal bool IsValidPartial()
  250. {
  251. return ImplIsValid(false, false);
  252. }
  253. internal bool ImplIsValid(bool decompressed, bool checkOrder)
  254. {
  255. if (IsInfinity)
  256. return true;
  257. ValidityCallback callback = new ValidityCallback(this, decompressed, checkOrder);
  258. ValidityPreCompInfo validity = (ValidityPreCompInfo)Curve.Precompute(this, ValidityPreCompInfo.PRECOMP_NAME, callback);
  259. return !validity.HasFailed();
  260. }
  261. public virtual ECPoint ScaleX(ECFieldElement scale)
  262. {
  263. return IsInfinity
  264. ? this
  265. : Curve.CreateRawPoint(RawXCoord.Multiply(scale), RawYCoord, RawZCoords, IsCompressed);
  266. }
  267. public virtual ECPoint ScaleY(ECFieldElement scale)
  268. {
  269. return IsInfinity
  270. ? this
  271. : Curve.CreateRawPoint(RawXCoord, RawYCoord.Multiply(scale), RawZCoords, IsCompressed);
  272. }
  273. public override bool Equals(object obj)
  274. {
  275. return Equals(obj as ECPoint);
  276. }
  277. public virtual bool Equals(ECPoint other)
  278. {
  279. if (this == other)
  280. return true;
  281. if (null == other)
  282. return false;
  283. ECCurve c1 = this.Curve, c2 = other.Curve;
  284. bool n1 = (null == c1), n2 = (null == c2);
  285. bool i1 = IsInfinity, i2 = other.IsInfinity;
  286. if (i1 || i2)
  287. {
  288. return (i1 && i2) && (n1 || n2 || c1.Equals(c2));
  289. }
  290. ECPoint p1 = this, p2 = other;
  291. if (n1 && n2)
  292. {
  293. // Points with null curve are in affine form, so already normalized
  294. }
  295. else if (n1)
  296. {
  297. p2 = p2.Normalize();
  298. }
  299. else if (n2)
  300. {
  301. p1 = p1.Normalize();
  302. }
  303. else if (!c1.Equals(c2))
  304. {
  305. return false;
  306. }
  307. else
  308. {
  309. // TODO Consider just requiring already normalized, to avoid silent performance degradation
  310. ECPoint[] points = new ECPoint[] { this, c1.ImportPoint(p2) };
  311. // TODO This is a little strong, really only requires coZNormalizeAll to get Zs equal
  312. c1.NormalizeAll(points);
  313. p1 = points[0];
  314. p2 = points[1];
  315. }
  316. return p1.XCoord.Equals(p2.XCoord) && p1.YCoord.Equals(p2.YCoord);
  317. }
  318. public override int GetHashCode()
  319. {
  320. ECCurve c = this.Curve;
  321. int hc = (null == c) ? 0 : ~c.GetHashCode();
  322. if (!this.IsInfinity)
  323. {
  324. // TODO Consider just requiring already normalized, to avoid silent performance degradation
  325. ECPoint p = Normalize();
  326. hc ^= p.XCoord.GetHashCode() * 17;
  327. hc ^= p.YCoord.GetHashCode() * 257;
  328. }
  329. return hc;
  330. }
  331. public override string ToString()
  332. {
  333. if (this.IsInfinity)
  334. {
  335. return "INF";
  336. }
  337. StringBuilder sb = new StringBuilder();
  338. sb.Append('(');
  339. sb.Append(RawXCoord);
  340. sb.Append(',');
  341. sb.Append(RawYCoord);
  342. for (int i = 0; i < m_zs.Length; ++i)
  343. {
  344. sb.Append(',');
  345. sb.Append(m_zs[i]);
  346. }
  347. sb.Append(')');
  348. return sb.ToString();
  349. }
  350. public virtual byte[] GetEncoded()
  351. {
  352. return GetEncoded(m_withCompression);
  353. }
  354. public abstract byte[] GetEncoded(bool compressed);
  355. protected internal abstract bool CompressionYTilde { get; }
  356. public abstract ECPoint Add(ECPoint b);
  357. public abstract ECPoint Subtract(ECPoint b);
  358. public abstract ECPoint Negate();
  359. public virtual ECPoint TimesPow2(int e)
  360. {
  361. if (e < 0)
  362. throw new ArgumentException("cannot be negative", "e");
  363. ECPoint p = this;
  364. while (--e >= 0)
  365. {
  366. p = p.Twice();
  367. }
  368. return p;
  369. }
  370. public abstract ECPoint Twice();
  371. public abstract ECPoint Multiply(BigInteger b);
  372. public virtual ECPoint TwicePlus(ECPoint b)
  373. {
  374. return Twice().Add(b);
  375. }
  376. public virtual ECPoint ThreeTimes()
  377. {
  378. return TwicePlus(this);
  379. }
  380. private class ValidityCallback
  381. : IPreCompCallback
  382. {
  383. private readonly ECPoint m_outer;
  384. private readonly bool m_decompressed, m_checkOrder;
  385. internal ValidityCallback(ECPoint outer, bool decompressed, bool checkOrder)
  386. {
  387. this.m_outer = outer;
  388. this.m_decompressed = decompressed;
  389. this.m_checkOrder = checkOrder;
  390. }
  391. public PreCompInfo Precompute(PreCompInfo existing)
  392. {
  393. ValidityPreCompInfo info = existing as ValidityPreCompInfo;
  394. if (info == null)
  395. {
  396. info = new ValidityPreCompInfo();
  397. }
  398. if (info.HasFailed())
  399. return info;
  400. if (!info.HasCurveEquationPassed())
  401. {
  402. if (!m_decompressed && !m_outer.SatisfiesCurveEquation())
  403. {
  404. info.ReportFailed();
  405. return info;
  406. }
  407. info.ReportCurveEquationPassed();
  408. }
  409. if (m_checkOrder && !info.HasOrderPassed())
  410. {
  411. if (!m_outer.SatisfiesOrder())
  412. {
  413. info.ReportFailed();
  414. return info;
  415. }
  416. info.ReportOrderPassed();
  417. }
  418. return info;
  419. }
  420. }
  421. }
  422. public abstract class ECPointBase
  423. : ECPoint
  424. {
  425. protected internal ECPointBase(
  426. ECCurve curve,
  427. ECFieldElement x,
  428. ECFieldElement y,
  429. bool withCompression)
  430. : base(curve, x, y, withCompression)
  431. {
  432. }
  433. protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
  434. : base(curve, x, y, zs, withCompression)
  435. {
  436. }
  437. /**
  438. * return the field element encoded with point compression. (S 4.3.6)
  439. */
  440. public override byte[] GetEncoded(bool compressed)
  441. {
  442. if (this.IsInfinity)
  443. {
  444. return new byte[1];
  445. }
  446. ECPoint normed = Normalize();
  447. byte[] X = normed.XCoord.GetEncoded();
  448. if (compressed)
  449. {
  450. byte[] PO = new byte[X.Length + 1];
  451. PO[0] = (byte)(normed.CompressionYTilde ? 0x03 : 0x02);
  452. Array.Copy(X, 0, PO, 1, X.Length);
  453. return PO;
  454. }
  455. byte[] Y = normed.YCoord.GetEncoded();
  456. {
  457. byte[] PO = new byte[X.Length + Y.Length + 1];
  458. PO[0] = 0x04;
  459. Array.Copy(X, 0, PO, 1, X.Length);
  460. Array.Copy(Y, 0, PO, X.Length + 1, Y.Length);
  461. return PO;
  462. }
  463. }
  464. /**
  465. * Multiplies this <code>ECPoint</code> by the given number.
  466. * @param k The multiplicator.
  467. * @return <code>k * this</code>.
  468. */
  469. public override ECPoint Multiply(BigInteger k)
  470. {
  471. return this.Curve.GetMultiplier().Multiply(this, k);
  472. }
  473. }
  474. public abstract class AbstractFpPoint
  475. : ECPointBase
  476. {
  477. protected AbstractFpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
  478. : base(curve, x, y, withCompression)
  479. {
  480. }
  481. protected AbstractFpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
  482. : base(curve, x, y, zs, withCompression)
  483. {
  484. }
  485. protected internal override bool CompressionYTilde
  486. {
  487. get { return this.AffineYCoord.TestBitZero(); }
  488. }
  489. protected override bool SatisfiesCurveEquation()
  490. {
  491. ECFieldElement X = this.RawXCoord, Y = this.RawYCoord, A = Curve.A, B = Curve.B;
  492. ECFieldElement lhs = Y.Square();
  493. switch (CurveCoordinateSystem)
  494. {
  495. case ECCurve.COORD_AFFINE:
  496. break;
  497. case ECCurve.COORD_HOMOGENEOUS:
  498. {
  499. ECFieldElement Z = this.RawZCoords[0];
  500. if (!Z.IsOne)
  501. {
  502. ECFieldElement Z2 = Z.Square(), Z3 = Z.Multiply(Z2);
  503. lhs = lhs.Multiply(Z);
  504. A = A.Multiply(Z2);
  505. B = B.Multiply(Z3);
  506. }
  507. break;
  508. }
  509. case ECCurve.COORD_JACOBIAN:
  510. case ECCurve.COORD_JACOBIAN_CHUDNOVSKY:
  511. case ECCurve.COORD_JACOBIAN_MODIFIED:
  512. {
  513. ECFieldElement Z = this.RawZCoords[0];
  514. if (!Z.IsOne)
  515. {
  516. ECFieldElement Z2 = Z.Square(), Z4 = Z2.Square(), Z6 = Z2.Multiply(Z4);
  517. A = A.Multiply(Z4);
  518. B = B.Multiply(Z6);
  519. }
  520. break;
  521. }
  522. default:
  523. throw new InvalidOperationException("unsupported coordinate system");
  524. }
  525. ECFieldElement rhs = X.Square().Add(A).Multiply(X).Add(B);
  526. return lhs.Equals(rhs);
  527. }
  528. public override ECPoint Subtract(ECPoint b)
  529. {
  530. if (b.IsInfinity)
  531. return this;
  532. // Add -b
  533. return Add(b.Negate());
  534. }
  535. }
  536. /**
  537. * Elliptic curve points over Fp
  538. */
  539. public class FpPoint
  540. : AbstractFpPoint
  541. {
  542. /**
  543. * Create a point which encodes without point compression.
  544. *
  545. * @param curve the curve to use
  546. * @param x affine x co-ordinate
  547. * @param y affine y co-ordinate
  548. */
  549. [Obsolete("Use ECCurve.CreatePoint to construct points")]
  550. public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y)
  551. : this(curve, x, y, false)
  552. {
  553. }
  554. /**
  555. * Create a point that encodes with or without point compression.
  556. *
  557. * @param curve the curve to use
  558. * @param x affine x co-ordinate
  559. * @param y affine y co-ordinate
  560. * @param withCompression if true encode with point compression
  561. */
  562. [Obsolete("Per-point compression property will be removed, see GetEncoded(bool)")]
  563. public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
  564. : base(curve, x, y, withCompression)
  565. {
  566. if ((x == null) != (y == null))
  567. throw new ArgumentException("Exactly one of the field elements is null");
  568. }
  569. internal FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
  570. : base(curve, x, y, zs, withCompression)
  571. {
  572. }
  573. protected override ECPoint Detach()
  574. {
  575. return new FpPoint(null, AffineXCoord, AffineYCoord, false);
  576. }
  577. public override ECFieldElement GetZCoord(int index)
  578. {
  579. if (index == 1 && ECCurve.COORD_JACOBIAN_MODIFIED == this.CurveCoordinateSystem)
  580. {
  581. return GetJacobianModifiedW();
  582. }
  583. return base.GetZCoord(index);
  584. }
  585. // B.3 pg 62
  586. public override ECPoint Add(ECPoint b)
  587. {
  588. if (this.IsInfinity)
  589. return b;
  590. if (b.IsInfinity)
  591. return this;
  592. if (this == b)
  593. return Twice();
  594. ECCurve curve = this.Curve;
  595. int coord = curve.CoordinateSystem;
  596. ECFieldElement X1 = this.RawXCoord, Y1 = this.RawYCoord;
  597. ECFieldElement X2 = b.RawXCoord, Y2 = b.RawYCoord;
  598. switch (coord)
  599. {
  600. case ECCurve.COORD_AFFINE:
  601. {
  602. ECFieldElement dx = X2.Subtract(X1), dy = Y2.Subtract(Y1);
  603. if (dx.IsZero)
  604. {
  605. if (dy.IsZero)
  606. {
  607. // this == b, i.e. this must be doubled
  608. return Twice();
  609. }
  610. // this == -b, i.e. the result is the point at infinity
  611. return Curve.Infinity;
  612. }
  613. ECFieldElement gamma = dy.Divide(dx);
  614. ECFieldElement X3 = gamma.Square().Subtract(X1).Subtract(X2);
  615. ECFieldElement Y3 = gamma.Multiply(X1.Subtract(X3)).Subtract(Y1);
  616. return new FpPoint(Curve, X3, Y3, IsCompressed);
  617. }
  618. case ECCurve.COORD_HOMOGENEOUS:
  619. {
  620. ECFieldElement Z1 = this.RawZCoords[0];
  621. ECFieldElement Z2 = b.RawZCoords[0];
  622. bool Z1IsOne = Z1.IsOne;
  623. bool Z2IsOne = Z2.IsOne;
  624. ECFieldElement u1 = Z1IsOne ? Y2 : Y2.Multiply(Z1);
  625. ECFieldElement u2 = Z2IsOne ? Y1 : Y1.Multiply(Z2);
  626. ECFieldElement u = u1.Subtract(u2);
  627. ECFieldElement v1 = Z1IsOne ? X2 : X2.Multiply(Z1);
  628. ECFieldElement v2 = Z2IsOne ? X1 : X1.Multiply(Z2);
  629. ECFieldElement v = v1.Subtract(v2);
  630. // Check if b == this or b == -this
  631. if (v.IsZero)
  632. {
  633. if (u.IsZero)
  634. {
  635. // this == b, i.e. this must be doubled
  636. return this.Twice();
  637. }
  638. // this == -b, i.e. the result is the point at infinity
  639. return curve.Infinity;
  640. }
  641. // TODO Optimize for when w == 1
  642. ECFieldElement w = Z1IsOne ? Z2 : Z2IsOne ? Z1 : Z1.Multiply(Z2);
  643. ECFieldElement vSquared = v.Square();
  644. ECFieldElement vCubed = vSquared.Multiply(v);
  645. ECFieldElement vSquaredV2 = vSquared.Multiply(v2);
  646. ECFieldElement A = u.Square().Multiply(w).Subtract(vCubed).Subtract(Two(vSquaredV2));
  647. ECFieldElement X3 = v.Multiply(A);
  648. ECFieldElement Y3 = vSquaredV2.Subtract(A).MultiplyMinusProduct(u, u2, vCubed);
  649. ECFieldElement Z3 = vCubed.Multiply(w);
  650. return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
  651. }
  652. case ECCurve.COORD_JACOBIAN:
  653. case ECCurve.COORD_JACOBIAN_MODIFIED:
  654. {
  655. ECFieldElement Z1 = this.RawZCoords[0];
  656. ECFieldElement Z2 = b.RawZCoords[0];
  657. bool Z1IsOne = Z1.IsOne;
  658. ECFieldElement X3, Y3, Z3, Z3Squared = null;
  659. if (!Z1IsOne && Z1.Equals(Z2))
  660. {
  661. // TODO Make this available as public method coZAdd?
  662. ECFieldElement dx = X1.Subtract(X2), dy = Y1.Subtract(Y2);
  663. if (dx.IsZero)
  664. {
  665. if (dy.IsZero)
  666. {
  667. return Twice();
  668. }
  669. return curve.Infinity;
  670. }
  671. ECFieldElement C = dx.Square();
  672. ECFieldElement W1 = X1.Multiply(C), W2 = X2.Multiply(C);
  673. ECFieldElement A1 = W1.Subtract(W2).Multiply(Y1);
  674. X3 = dy.Square().Subtract(W1).Subtract(W2);
  675. Y3 = W1.Subtract(X3).Multiply(dy).Subtract(A1);
  676. Z3 = dx;
  677. if (Z1IsOne)
  678. {
  679. Z3Squared = C;
  680. }
  681. else
  682. {
  683. Z3 = Z3.Multiply(Z1);
  684. }
  685. }
  686. else
  687. {
  688. ECFieldElement Z1Squared, U2, S2;
  689. if (Z1IsOne)
  690. {
  691. Z1Squared = Z1; U2 = X2; S2 = Y2;
  692. }
  693. else
  694. {
  695. Z1Squared = Z1.Square();
  696. U2 = Z1Squared.Multiply(X2);
  697. ECFieldElement Z1Cubed = Z1Squared.Multiply(Z1);
  698. S2 = Z1Cubed.Multiply(Y2);
  699. }
  700. bool Z2IsOne = Z2.IsOne;
  701. ECFieldElement Z2Squared, U1, S1;
  702. if (Z2IsOne)
  703. {
  704. Z2Squared = Z2; U1 = X1; S1 = Y1;
  705. }
  706. else
  707. {
  708. Z2Squared = Z2.Square();
  709. U1 = Z2Squared.Multiply(X1);
  710. ECFieldElement Z2Cubed = Z2Squared.Multiply(Z2);
  711. S1 = Z2Cubed.Multiply(Y1);
  712. }
  713. ECFieldElement H = U1.Subtract(U2);
  714. ECFieldElement R = S1.Subtract(S2);
  715. // Check if b == this or b == -this
  716. if (H.IsZero)
  717. {
  718. if (R.IsZero)
  719. {
  720. // this == b, i.e. this must be doubled
  721. return this.Twice();
  722. }
  723. // this == -b, i.e. the result is the point at infinity
  724. return curve.Infinity;
  725. }
  726. ECFieldElement HSquared = H.Square();
  727. ECFieldElement G = HSquared.Multiply(H);
  728. ECFieldElement V = HSquared.Multiply(U1);
  729. X3 = R.Square().Add(G).Subtract(Two(V));
  730. Y3 = V.Subtract(X3).MultiplyMinusProduct(R, G, S1);
  731. Z3 = H;
  732. if (!Z1IsOne)
  733. {
  734. Z3 = Z3.Multiply(Z1);
  735. }
  736. if (!Z2IsOne)
  737. {
  738. Z3 = Z3.Multiply(Z2);
  739. }
  740. // Alternative calculation of Z3 using fast square
  741. //X3 = four(X3);
  742. //Y3 = eight(Y3);
  743. //Z3 = doubleProductFromSquares(Z1, Z2, Z1Squared, Z2Squared).Multiply(H);
  744. if (Z3 == H)
  745. {
  746. Z3Squared = HSquared;
  747. }
  748. }
  749. ECFieldElement[] zs;
  750. if (coord == ECCurve.COORD_JACOBIAN_MODIFIED)
  751. {
  752. // TODO If the result will only be used in a subsequent addition, we don't need W3
  753. ECFieldElement W3 = CalculateJacobianModifiedW(Z3, Z3Squared);
  754. zs = new ECFieldElement[] { Z3, W3 };
  755. }
  756. else
  757. {
  758. zs = new ECFieldElement[] { Z3 };
  759. }
  760. return new FpPoint(curve, X3, Y3, zs, IsCompressed);
  761. }
  762. default:
  763. {
  764. throw new InvalidOperationException("unsupported coordinate system");
  765. }
  766. }
  767. }
  768. // B.3 pg 62
  769. public override ECPoint Twice()
  770. {
  771. if (this.IsInfinity)
  772. return this;
  773. ECCurve curve = this.Curve;
  774. ECFieldElement Y1 = this.RawYCoord;
  775. if (Y1.IsZero)
  776. return curve.Infinity;
  777. int coord = curve.CoordinateSystem;
  778. ECFieldElement X1 = this.RawXCoord;
  779. switch (coord)
  780. {
  781. case ECCurve.COORD_AFFINE:
  782. {
  783. ECFieldElement X1Squared = X1.Square();
  784. ECFieldElement gamma = Three(X1Squared).Add(this.Curve.A).Divide(Two(Y1));
  785. ECFieldElement X3 = gamma.Square().Subtract(Two(X1));
  786. ECFieldElement Y3 = gamma.Multiply(X1.Subtract(X3)).Subtract(Y1);
  787. return new FpPoint(Curve, X3, Y3, IsCompressed);
  788. }
  789. case ECCurve.COORD_HOMOGENEOUS:
  790. {
  791. ECFieldElement Z1 = this.RawZCoords[0];
  792. bool Z1IsOne = Z1.IsOne;
  793. // TODO Optimize for small negative a4 and -3
  794. ECFieldElement w = curve.A;
  795. if (!w.IsZero && !Z1IsOne)
  796. {
  797. w = w.Multiply(Z1.Square());
  798. }
  799. w = w.Add(Three(X1.Square()));
  800. ECFieldElement s = Z1IsOne ? Y1 : Y1.Multiply(Z1);
  801. ECFieldElement t = Z1IsOne ? Y1.Square() : s.Multiply(Y1);
  802. ECFieldElement B = X1.Multiply(t);
  803. ECFieldElement _4B = Four(B);
  804. ECFieldElement h = w.Square().Subtract(Two(_4B));
  805. ECFieldElement _2s = Two(s);
  806. ECFieldElement X3 = h.Multiply(_2s);
  807. ECFieldElement _2t = Two(t);
  808. ECFieldElement Y3 = _4B.Subtract(h).Multiply(w).Subtract(Two(_2t.Square()));
  809. ECFieldElement _4sSquared = Z1IsOne ? Two(_2t) : _2s.Square();
  810. ECFieldElement Z3 = Two(_4sSquared).Multiply(s);
  811. return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
  812. }
  813. case ECCurve.COORD_JACOBIAN:
  814. {
  815. ECFieldElement Z1 = this.RawZCoords[0];
  816. bool Z1IsOne = Z1.IsOne;
  817. ECFieldElement Y1Squared = Y1.Square();
  818. ECFieldElement T = Y1Squared.Square();
  819. ECFieldElement a4 = curve.A;
  820. ECFieldElement a4Neg = a4.Negate();
  821. ECFieldElement M, S;
  822. if (a4Neg.ToBigInteger().Equals(BigInteger.ValueOf(3)))
  823. {
  824. ECFieldElement Z1Squared = Z1IsOne ? Z1 : Z1.Square();
  825. M = Three(X1.Add(Z1Squared).Multiply(X1.Subtract(Z1Squared)));
  826. S = Four(Y1Squared.Multiply(X1));
  827. }
  828. else
  829. {
  830. ECFieldElement X1Squared = X1.Square();
  831. M = Three(X1Squared);
  832. if (Z1IsOne)
  833. {
  834. M = M.Add(a4);
  835. }
  836. else if (!a4.IsZero)
  837. {
  838. ECFieldElement Z1Squared = Z1IsOne ? Z1 : Z1.Square();
  839. ECFieldElement Z1Pow4 = Z1Squared.Square();
  840. if (a4Neg.BitLength < a4.BitLength)
  841. {
  842. M = M.Subtract(Z1Pow4.Multiply(a4Neg));
  843. }
  844. else
  845. {
  846. M = M.Add(Z1Pow4.Multiply(a4));
  847. }
  848. }
  849. //S = two(doubleProductFromSquares(X1, Y1Squared, X1Squared, T));
  850. S = Four(X1.Multiply(Y1Squared));
  851. }
  852. ECFieldElement X3 = M.Square().Subtract(Two(S));
  853. ECFieldElement Y3 = S.Subtract(X3).Multiply(M).Subtract(Eight(T));
  854. ECFieldElement Z3 = Two(Y1);
  855. if (!Z1IsOne)
  856. {
  857. Z3 = Z3.Multiply(Z1);
  858. }
  859. // Alternative calculation of Z3 using fast square
  860. //ECFieldElement Z3 = doubleProductFromSquares(Y1, Z1, Y1Squared, Z1Squared);
  861. return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
  862. }
  863. case ECCurve.COORD_JACOBIAN_MODIFIED:
  864. {
  865. return TwiceJacobianModified(true);
  866. }
  867. default:
  868. {
  869. throw new InvalidOperationException("unsupported coordinate system");
  870. }
  871. }
  872. }
  873. public override ECPoint TwicePlus(ECPoint b)
  874. {
  875. if (this == b)
  876. return ThreeTimes();
  877. if (this.IsInfinity)
  878. return b;
  879. if (b.IsInfinity)
  880. return Twice();
  881. ECFieldElement Y1 = this.RawYCoord;
  882. if (Y1.IsZero)
  883. return b;
  884. ECCurve curve = this.Curve;
  885. int coord = curve.CoordinateSystem;
  886. switch (coord)
  887. {
  888. case ECCurve.COORD_AFFINE:
  889. {
  890. ECFieldElement X1 = this.RawXCoord;
  891. ECFieldElement X2 = b.RawXCoord, Y2 = b.RawYCoord;
  892. ECFieldElement dx = X2.Subtract(X1), dy = Y2.Subtract(Y1);
  893. if (dx.IsZero)
  894. {
  895. if (dy.IsZero)
  896. {
  897. // this == b i.e. the result is 3P
  898. return ThreeTimes();
  899. }
  900. // this == -b, i.e. the result is P
  901. return this;
  902. }
  903. /*
  904. * Optimized calculation of 2P + Q, as described in "Trading Inversions for
  905. * Multiplications in Elliptic Curve Cryptography", by Ciet, Joye, Lauter, Montgomery.
  906. */
  907. ECFieldElement X = dx.Square(), Y = dy.Square();
  908. ECFieldElement d = X.Multiply(Two(X1).Add(X2)).Subtract(Y);
  909. if (d.IsZero)
  910. {
  911. return Curve.Infinity;
  912. }
  913. ECFieldElement D = d.Multiply(dx);
  914. ECFieldElement I = D.Invert();
  915. ECFieldElement L1 = d.Multiply(I).Multiply(dy);
  916. ECFieldElement L2 = Two(Y1).Multiply(X).Multiply(dx).Multiply(I).Subtract(L1);
  917. ECFieldElement X4 = (L2.Subtract(L1)).Multiply(L1.Add(L2)).Add(X2);
  918. ECFieldElement Y4 = (X1.Subtract(X4)).Multiply(L2).Subtract(Y1);
  919. return new FpPoint(Curve, X4, Y4, IsCompressed);
  920. }
  921. case ECCurve.COORD_JACOBIAN_MODIFIED:
  922. {
  923. return TwiceJacobianModified(false).Add(b);
  924. }
  925. default:
  926. {
  927. return Twice().Add(b);
  928. }
  929. }
  930. }
  931. public override ECPoint ThreeTimes()
  932. {
  933. if (this.IsInfinity)
  934. return this;
  935. ECFieldElement Y1 = this.RawYCoord;
  936. if (Y1.IsZero)
  937. return this;
  938. ECCurve curve = this.Curve;
  939. int coord = curve.CoordinateSystem;
  940. switch (coord)
  941. {
  942. case ECCurve.COORD_AFFINE:
  943. {
  944. ECFieldElement X1 = this.RawXCoord;
  945. ECFieldElement _2Y1 = Two(Y1);
  946. ECFieldElement X = _2Y1.Square();
  947. ECFieldElement Z = Three(X1.Square()).Add(Curve.A);
  948. ECFieldElement Y = Z.Square();
  949. ECFieldElement d = Three(X1).Multiply(X).Subtract(Y);
  950. if (d.IsZero)
  951. {
  952. return Curve.Infinity;
  953. }
  954. ECFieldElement D = d.Multiply(_2Y1);
  955. ECFieldElement I = D.Invert();
  956. ECFieldElement L1 = d.Multiply(I).Multiply(Z);
  957. ECFieldElement L2 = X.Square().Multiply(I).Subtract(L1);
  958. ECFieldElement X4 = (L2.Subtract(L1)).Multiply(L1.Add(L2)).Add(X1);
  959. ECFieldElement Y4 = (X1.Subtract(X4)).Multiply(L2).Subtract(Y1);
  960. return new FpPoint(Curve, X4, Y4, IsCompressed);
  961. }
  962. case ECCurve.COORD_JACOBIAN_MODIFIED:
  963. {
  964. return TwiceJacobianModified(false).Add(this);
  965. }
  966. default:
  967. {
  968. // NOTE: Be careful about recursions between TwicePlus and ThreeTimes
  969. return Twice().Add(this);
  970. }
  971. }
  972. }
  973. public override ECPoint TimesPow2(int e)
  974. {
  975. if (e < 0)
  976. throw new ArgumentException("cannot be negative", "e");
  977. if (e == 0 || this.IsInfinity)
  978. return this;
  979. if (e == 1)
  980. return Twice();
  981. ECCurve curve = this.Curve;
  982. ECFieldElement Y1 = this.RawYCoord;
  983. if (Y1.IsZero)
  984. return curve.Infinity;
  985. int coord = curve.CoordinateSystem;
  986. ECFieldElement W1 = curve.A;
  987. ECFieldElement X1 = this.RawXCoord;
  988. ECFieldElement Z1 = this.RawZCoords.Length < 1 ? curve.FromBigInteger(BigInteger.One) : this.RawZCoords[0];
  989. if (!Z1.IsOne)
  990. {
  991. switch (coord)
  992. {
  993. case ECCurve.COORD_HOMOGENEOUS:
  994. ECFieldElement Z1Sq = Z1.Square();
  995. X1 = X1.Multiply(Z1);
  996. Y1 = Y1.Multiply(Z1Sq);
  997. W1 = CalculateJacobianModifiedW(Z1, Z1Sq);
  998. break;
  999. case ECCurve.COORD_JACOBIAN:
  1000. W1 = CalculateJacobianModifiedW(Z1, null);
  1001. break;
  1002. case ECCurve.COORD_JACOBIAN_MODIFIED:
  1003. W1 = GetJacobianModifiedW();
  1004. break;
  1005. }
  1006. }
  1007. for (int i = 0; i < e; ++i)
  1008. {
  1009. if (Y1.IsZero)
  1010. return curve.Infinity;
  1011. ECFieldElement X1Squared = X1.Square();
  1012. ECFieldElement M = Three(X1Squared);
  1013. ECFieldElement _2Y1 = Two(Y1);
  1014. ECFieldElement _2Y1Squared = _2Y1.Multiply(Y1);
  1015. ECFieldElement S = Two(X1.Multiply(_2Y1Squared));
  1016. ECFieldElement _4T = _2Y1Squared.Square();
  1017. ECFieldElement _8T = Two(_4T);
  1018. if (!W1.IsZero)
  1019. {
  1020. M = M.Add(W1);
  1021. W1 = Two(_8T.Multiply(W1));
  1022. }
  1023. X1 = M.Square().Subtract(Two(S));
  1024. Y1 = M.Multiply(S.Subtract(X1)).Subtract(_8T);
  1025. Z1 = Z1.IsOne ? _2Y1 : _2Y1.Multiply(Z1);
  1026. }
  1027. switch (coord)
  1028. {
  1029. case ECCurve.COORD_AFFINE:
  1030. ECFieldElement zInv = Z1.Invert(), zInv2 = zInv.Square(), zInv3 = zInv2.Multiply(zInv);
  1031. return new FpPoint(curve, X1.Multiply(zInv2), Y1.Multiply(zInv3), IsCompressed);
  1032. case ECCurve.COORD_HOMOGENEOUS:
  1033. X1 = X1.Multiply(Z1);
  1034. Z1 = Z1.Multiply(Z1.Square());
  1035. return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1 }, IsCompressed);
  1036. case ECCurve.COORD_JACOBIAN:
  1037. return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1 }, IsCompressed);
  1038. case ECCurve.COORD_JACOBIAN_MODIFIED:
  1039. return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1, W1 }, IsCompressed);
  1040. default:
  1041. throw new InvalidOperationException("unsupported coordinate system");
  1042. }
  1043. }
  1044. protected virtual ECFieldElement Two(ECFieldElement x)
  1045. {
  1046. return x.Add(x);
  1047. }
  1048. protected virtual ECFieldElement Three(ECFieldElement x)
  1049. {
  1050. return Two(x).Add(x);
  1051. }
  1052. protected virtual ECFieldElement Four(ECFieldElement x)
  1053. {
  1054. return Two(Two(x));
  1055. }
  1056. protected virtual ECFieldElement Eight(ECFieldElement x)
  1057. {
  1058. return Four(Two(x));
  1059. }
  1060. protected virtual ECFieldElement DoubleProductFromSquares(ECFieldElement a, ECFieldElement b,
  1061. ECFieldElement aSquared, ECFieldElement bSquared)
  1062. {
  1063. /*
  1064. * NOTE: If squaring in the field is faster than multiplication, then this is a quicker
  1065. * way to calculate 2.A.B, if A^2 and B^2 are already known.
  1066. */
  1067. return a.Add(b).Square().Subtract(aSquared).Subtract(bSquared);
  1068. }
  1069. public override ECPoint Negate()
  1070. {
  1071. if (IsInfinity)
  1072. return this;
  1073. ECCurve curve = Curve;
  1074. int coord = curve.CoordinateSystem;
  1075. if (ECCurve.COORD_AFFINE != coord)
  1076. {
  1077. return new FpPoint(curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed);
  1078. }
  1079. return new FpPoint(curve, RawXCoord, RawYCoord.Negate(), IsCompressed);
  1080. }
  1081. protected virtual ECFieldElement CalculateJacobianModifiedW(ECFieldElement Z, ECFieldElement ZSquared)
  1082. {
  1083. ECFieldElement a4 = this.Curve.A;
  1084. if (a4.IsZero || Z.IsOne)
  1085. return a4;
  1086. if (ZSquared == null)
  1087. {
  1088. ZSquared = Z.Square();
  1089. }
  1090. ECFieldElement W = ZSquared.Square();
  1091. ECFieldElement a4Neg = a4.Negate();
  1092. if (a4Neg.BitLength < a4.BitLength)
  1093. {
  1094. W = W.Multiply(a4Neg).Negate();
  1095. }
  1096. else
  1097. {
  1098. W = W.Multiply(a4);
  1099. }
  1100. return W;
  1101. }
  1102. protected virtual ECFieldElement GetJacobianModifiedW()
  1103. {
  1104. ECFieldElement[] ZZ = this.RawZCoords;
  1105. ECFieldElement W = ZZ[1];
  1106. if (W == null)
  1107. {
  1108. // NOTE: Rarely, TwicePlus will result in the need for a lazy W1 calculation here
  1109. ZZ[1] = W = CalculateJacobianModifiedW(ZZ[0], null);
  1110. }
  1111. return W;
  1112. }
  1113. protected virtual FpPoint TwiceJacobianModified(bool calculateW)
  1114. {
  1115. ECFieldElement X1 = this.RawXCoord, Y1 = this.RawYCoord, Z1 = this.RawZCoords[0], W1 = GetJacobianModifiedW();
  1116. ECFieldElement X1Squared = X1.Square();
  1117. ECFieldElement M = Three(X1Squared).Add(W1);
  1118. ECFieldElement _2Y1 = Two(Y1);
  1119. ECFieldElement _2Y1Squared = _2Y1.Multiply(Y1);
  1120. ECFieldElement S = Two(X1.Multiply(_2Y1Squared));
  1121. ECFieldElement X3 = M.Square().Subtract(Two(S));
  1122. ECFieldElement _4T = _2Y1Squared.Square();
  1123. ECFieldElement _8T = Two(_4T);
  1124. ECFieldElement Y3 = M.Multiply(S.Subtract(X3)).Subtract(_8T);
  1125. ECFieldElement W3 = calculateW ? Two(_8T.Multiply(W1)) : null;
  1126. ECFieldElement Z3 = Z1.IsOne ? _2Y1 : _2Y1.Multiply(Z1);
  1127. return new FpPoint(this.Curve, X3, Y3, new ECFieldElement[] { Z3, W3 }, IsCompressed);
  1128. }
  1129. }
  1130. public abstract class AbstractF2mPoint
  1131. : ECPointBase
  1132. {
  1133. protected AbstractF2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
  1134. : base(curve, x, y, withCompression)
  1135. {
  1136. }
  1137. protected AbstractF2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
  1138. : base(curve, x, y, zs, withCompression)
  1139. {
  1140. }
  1141. protected override bool SatisfiesCurveEquation()
  1142. {
  1143. ECCurve curve = Curve;
  1144. ECFieldElement X = this.RawXCoord, Y = this.RawYCoord, A = curve.A, B = curve.B;
  1145. ECFieldElement lhs, rhs;
  1146. int coord = curve.CoordinateSystem;
  1147. if (coord == ECCurve.COORD_LAMBDA_PROJECTIVE)
  1148. {
  1149. ECFieldElement Z = this.RawZCoords[0];
  1150. bool ZIsOne = Z.IsOne;
  1151. if (X.IsZero)
  1152. {
  1153. // NOTE: For x == 0, we expect the affine-y instead of the lambda-y
  1154. lhs = Y.Square();
  1155. rhs = B;
  1156. if (!ZIsOne)
  1157. {
  1158. ECFieldElement Z2 = Z.Square();
  1159. rhs = rhs.Multiply(Z2);
  1160. }
  1161. }
  1162. else
  1163. {
  1164. ECFieldElement L = Y, X2 = X.Square();
  1165. if (ZIsOne)
  1166. {
  1167. lhs = L.Square().Add(L).Add(A);
  1168. rhs = X2.Square().Add(B);
  1169. }
  1170. else
  1171. {
  1172. ECFieldElement Z2 = Z.Square(), Z4 = Z2.Square();
  1173. lhs = L.Add(Z).MultiplyPlusProduct(L, A, Z2);
  1174. // TODO If sqrt(b) is precomputed this can be simplified to a single square
  1175. rhs = X2.SquarePlusProduct(B, Z4);
  1176. }
  1177. lhs = lhs.Multiply(X2);
  1178. }
  1179. }
  1180. else
  1181. {
  1182. lhs = Y.Add(X).Multiply(Y);
  1183. switch (coord)
  1184. {
  1185. case ECCurve.COORD_AFFINE:
  1186. break;
  1187. case ECCurve.COORD_HOMOGENEOUS:
  1188. {
  1189. ECFieldElement Z = this.RawZCoords[0];
  1190. if (!Z.IsOne)
  1191. {
  1192. ECFieldElement Z2 = Z.Square(), Z3 = Z.Multiply(Z2);
  1193. lhs = lhs.Multiply(Z);
  1194. A = A.Multiply(Z);
  1195. B = B.Multiply(Z3);
  1196. }
  1197. break;
  1198. }
  1199. default:
  1200. throw new InvalidOperationException("unsupported coordinate system");
  1201. }
  1202. rhs = X.Add(A).Multiply(X.Square()).Add(B);
  1203. }
  1204. return lhs.Equals(rhs);
  1205. }
  1206. protected override bool SatisfiesOrder()
  1207. {
  1208. ECCurve curve = Curve;
  1209. BigInteger cofactor = curve.Cofactor;
  1210. if (BigInteger.Two.Equals(cofactor))
  1211. {
  1212. /*
  1213. * Check that the trace of (X + A) is 0, then there exists a solution to L^2 + L = X + A,
  1214. * and so a halving is possible, so this point is the double of another.
  1215. */
  1216. ECPoint N = this.Normalize();
  1217. ECFieldElement X = N.AffineXCoord;
  1218. ECFieldElement rhs = X.Add(curve.A);
  1219. return ((AbstractF2mFieldElement)rhs).Trace() == 0;
  1220. }
  1221. if (BigInteger.ValueOf(4).Equals(cofactor))
  1222. {
  1223. /*
  1224. * Solve L^2 + L = X + A to find the half of this point, if it exists (fail if not).
  1225. * Generate both possibilities for the square of the half-point's x-coordinate (w),
  1226. * and check if Tr(w + A) == 0 for at least one; then a second halving is possible
  1227. * (see comments for cofactor 2 above), so this point is four times another.
  1228. *
  1229. * Note: Tr(x^2) == Tr(x).
  1230. */
  1231. ECPoint N = this.Normalize();
  1232. ECFieldElement X = N.AffineXCoord;
  1233. ECFieldElement lambda = ((AbstractF2mCurve)curve).SolveQuadraticEquation(X.Add(curve.A));
  1234. if (lambda == null)
  1235. return false;
  1236. ECFieldElement w = X.Multiply(lambda).Add(N.AffineYCoord);
  1237. ECFieldElement t = w.Add(curve.A);
  1238. return ((AbstractF2mFieldElement)t).Trace() == 0
  1239. || ((AbstractF2mFieldElement)(t.Add(X))).Trace() == 0;
  1240. }
  1241. return base.SatisfiesOrder();
  1242. }
  1243. public override ECPoint ScaleX(ECFieldElement scale)
  1244. {
  1245. if (this.IsInfinity)
  1246. return this;
  1247. switch (CurveCoordinateSystem)
  1248. {
  1249. case ECCurve.COORD_LAMBDA_AFFINE:
  1250. {
  1251. // Y is actually Lambda (X + Y/X) here
  1252. ECFieldElement X = RawXCoord, L = RawYCoord;
  1253. ECFieldElement X2 = X.Multiply(scale);
  1254. ECFieldElement L2 = L.Add(X).Divide(scale).Add(X2);
  1255. return Curve.CreateRawPoint(X, L2, RawZCoords, IsCompressed);
  1256. }
  1257. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1258. {
  1259. // Y is actually Lambda (X + Y/X) here
  1260. ECFieldElement X = RawXCoord, L = RawYCoord, Z = RawZCoords[0];
  1261. // We scale the Z coordinate also, to avoid an inversion
  1262. ECFieldElement X2 = X.Multiply(scale.Square());
  1263. ECFieldElement L2 = L.Add(X).Add(X2);
  1264. ECFieldElement Z2 = Z.Multiply(scale);
  1265. return Curve.CreateRawPoint(X, L2, new ECFieldElement[] { Z2 }, IsCompressed);
  1266. }
  1267. default:
  1268. {
  1269. return base.ScaleX(scale);
  1270. }
  1271. }
  1272. }
  1273. public override ECPoint ScaleY(ECFieldElement scale)
  1274. {
  1275. if (this.IsInfinity)
  1276. return this;
  1277. switch (CurveCoordinateSystem)
  1278. {
  1279. case ECCurve.COORD_LAMBDA_AFFINE:
  1280. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1281. {
  1282. ECFieldElement X = RawXCoord, L = RawYCoord;
  1283. // Y is actually Lambda (X + Y/X) here
  1284. ECFieldElement L2 = L.Add(X).Multiply(scale).Add(X);
  1285. return Curve.CreateRawPoint(X, L2, RawZCoords, IsCompressed);
  1286. }
  1287. default:
  1288. {
  1289. return base.ScaleY(scale);
  1290. }
  1291. }
  1292. }
  1293. public override ECPoint Subtract(ECPoint b)
  1294. {
  1295. if (b.IsInfinity)
  1296. return this;
  1297. // Add -b
  1298. return Add(b.Negate());
  1299. }
  1300. public virtual AbstractF2mPoint Tau()
  1301. {
  1302. if (this.IsInfinity)
  1303. return this;
  1304. ECCurve curve = this.Curve;
  1305. int coord = curve.CoordinateSystem;
  1306. ECFieldElement X1 = this.RawXCoord;
  1307. switch (coord)
  1308. {
  1309. case ECCurve.COORD_AFFINE:
  1310. case ECCurve.COORD_LAMBDA_AFFINE:
  1311. {
  1312. ECFieldElement Y1 = this.RawYCoord;
  1313. return (AbstractF2mPoint)curve.CreateRawPoint(X1.Square(), Y1.Square(), IsCompressed);
  1314. }
  1315. case ECCurve.COORD_HOMOGENEOUS:
  1316. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1317. {
  1318. ECFieldElement Y1 = this.RawYCoord, Z1 = this.RawZCoords[0];
  1319. return (AbstractF2mPoint)curve.CreateRawPoint(X1.Square(), Y1.Square(),
  1320. new ECFieldElement[] { Z1.Square() }, IsCompressed);
  1321. }
  1322. default:
  1323. {
  1324. throw new InvalidOperationException("unsupported coordinate system");
  1325. }
  1326. }
  1327. }
  1328. public virtual AbstractF2mPoint TauPow(int pow)
  1329. {
  1330. if (this.IsInfinity)
  1331. return this;
  1332. ECCurve curve = this.Curve;
  1333. int coord = curve.CoordinateSystem;
  1334. ECFieldElement X1 = this.RawXCoord;
  1335. switch (coord)
  1336. {
  1337. case ECCurve.COORD_AFFINE:
  1338. case ECCurve.COORD_LAMBDA_AFFINE:
  1339. {
  1340. ECFieldElement Y1 = this.RawYCoord;
  1341. return (AbstractF2mPoint)curve.CreateRawPoint(X1.SquarePow(pow), Y1.SquarePow(pow), IsCompressed);
  1342. }
  1343. case ECCurve.COORD_HOMOGENEOUS:
  1344. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1345. {
  1346. ECFieldElement Y1 = this.RawYCoord, Z1 = this.RawZCoords[0];
  1347. return (AbstractF2mPoint)curve.CreateRawPoint(X1.SquarePow(pow), Y1.SquarePow(pow),
  1348. new ECFieldElement[] { Z1.SquarePow(pow) }, IsCompressed);
  1349. }
  1350. default:
  1351. {
  1352. throw new InvalidOperationException("unsupported coordinate system");
  1353. }
  1354. }
  1355. }
  1356. }
  1357. /**
  1358. * Elliptic curve points over F2m
  1359. */
  1360. public class F2mPoint
  1361. : AbstractF2mPoint
  1362. {
  1363. /**
  1364. * @param curve base curve
  1365. * @param x x point
  1366. * @param y y point
  1367. */
  1368. [Obsolete("Use ECCurve.CreatePoint to construct points")]
  1369. public F2mPoint(
  1370. ECCurve curve,
  1371. ECFieldElement x,
  1372. ECFieldElement y)
  1373. : this(curve, x, y, false)
  1374. {
  1375. }
  1376. /**
  1377. * @param curve base curve
  1378. * @param x x point
  1379. * @param y y point
  1380. * @param withCompression true if encode with point compression.
  1381. */
  1382. [Obsolete("Per-point compression property will be removed, see GetEncoded(bool)")]
  1383. public F2mPoint(
  1384. ECCurve curve,
  1385. ECFieldElement x,
  1386. ECFieldElement y,
  1387. bool withCompression)
  1388. : base(curve, x, y, withCompression)
  1389. {
  1390. if ((x == null) != (y == null))
  1391. {
  1392. throw new ArgumentException("Exactly one of the field elements is null");
  1393. }
  1394. if (x != null)
  1395. {
  1396. // Check if x and y are elements of the same field
  1397. F2mFieldElement.CheckFieldElements(x, y);
  1398. // Check if x and a are elements of the same field
  1399. if (curve != null)
  1400. {
  1401. F2mFieldElement.CheckFieldElements(x, curve.A);
  1402. }
  1403. }
  1404. }
  1405. internal F2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
  1406. : base(curve, x, y, zs, withCompression)
  1407. {
  1408. }
  1409. protected override ECPoint Detach()
  1410. {
  1411. return new F2mPoint(null, AffineXCoord, AffineYCoord, false);
  1412. }
  1413. public override ECFieldElement YCoord
  1414. {
  1415. get
  1416. {
  1417. int coord = this.CurveCoordinateSystem;
  1418. switch (coord)
  1419. {
  1420. case ECCurve.COORD_LAMBDA_AFFINE:
  1421. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1422. {
  1423. ECFieldElement X = RawXCoord, L = RawYCoord;
  1424. if (this.IsInfinity || X.IsZero)
  1425. return L;
  1426. // Y is actually Lambda (X + Y/X) here; convert to affine value on the fly
  1427. ECFieldElement Y = L.Add(X).Multiply(X);
  1428. if (ECCurve.COORD_LAMBDA_PROJECTIVE == coord)
  1429. {
  1430. ECFieldElement Z = RawZCoords[0];
  1431. if (!Z.IsOne)
  1432. {
  1433. Y = Y.Divide(Z);
  1434. }
  1435. }
  1436. return Y;
  1437. }
  1438. default:
  1439. {
  1440. return RawYCoord;
  1441. }
  1442. }
  1443. }
  1444. }
  1445. protected internal override bool CompressionYTilde
  1446. {
  1447. get
  1448. {
  1449. ECFieldElement X = this.RawXCoord;
  1450. if (X.IsZero)
  1451. {
  1452. return false;
  1453. }
  1454. ECFieldElement Y = this.RawYCoord;
  1455. switch (this.CurveCoordinateSystem)
  1456. {
  1457. case ECCurve.COORD_LAMBDA_AFFINE:
  1458. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1459. {
  1460. // Y is actually Lambda (X + Y/X) here
  1461. return Y.TestBitZero() != X.TestBitZero();
  1462. }
  1463. default:
  1464. {
  1465. return Y.Divide(X).TestBitZero();
  1466. }
  1467. }
  1468. }
  1469. }
  1470. public override ECPoint Add(ECPoint b)
  1471. {
  1472. if (this.IsInfinity)
  1473. return b;
  1474. if (b.IsInfinity)
  1475. return this;
  1476. ECCurve curve = this.Curve;
  1477. int coord = curve.CoordinateSystem;
  1478. ECFieldElement X1 = this.RawXCoord;
  1479. ECFieldElement X2 = b.RawXCoord;
  1480. switch (coord)
  1481. {
  1482. case ECCurve.COORD_AFFINE:
  1483. {
  1484. ECFieldElement Y1 = this.RawYCoord;
  1485. ECFieldElement Y2 = b.RawYCoord;
  1486. ECFieldElement dx = X1.Add(X2), dy = Y1.Add(Y2);
  1487. if (dx.IsZero)
  1488. {
  1489. if (dy.IsZero)
  1490. {
  1491. return Twice();
  1492. }
  1493. return curve.Infinity;
  1494. }
  1495. ECFieldElement L = dy.Divide(dx);
  1496. ECFieldElement X3 = L.Square().Add(L).Add(dx).Add(curve.A);
  1497. ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1);
  1498. return new F2mPoint(curve, X3, Y3, IsCompressed);
  1499. }
  1500. case ECCurve.COORD_HOMOGENEOUS:
  1501. {
  1502. ECFieldElement Y1 = this.RawYCoord, Z1 = this.RawZCoords[0];
  1503. ECFieldElement Y2 = b.RawYCoord, Z2 = b.RawZCoords[0];
  1504. bool Z1IsOne = Z1.IsOne;
  1505. ECFieldElement U1 = Y2, V1 = X2;
  1506. if (!Z1IsOne)
  1507. {
  1508. U1 = U1.Multiply(Z1);
  1509. V1 = V1.Multiply(Z1);
  1510. }
  1511. bool Z2IsOne = Z2.IsOne;
  1512. ECFieldElement U2 = Y1, V2 = X1;
  1513. if (!Z2IsOne)
  1514. {
  1515. U2 = U2.Multiply(Z2);
  1516. V2 = V2.Multiply(Z2);
  1517. }
  1518. ECFieldElement U = U1.Add(U2);
  1519. ECFieldElement V = V1.Add(V2);
  1520. if (V.IsZero)
  1521. {
  1522. if (U.IsZero)
  1523. {
  1524. return Twice();
  1525. }
  1526. return curve.Infinity;
  1527. }
  1528. ECFieldElement VSq = V.Square();
  1529. ECFieldElement VCu = VSq.Multiply(V);
  1530. ECFieldElement W = Z1IsOne ? Z2 : Z2IsOne ? Z1 : Z1.Multiply(Z2);
  1531. ECFieldElement uv = U.Add(V);
  1532. ECFieldElement A = uv.MultiplyPlusProduct(U, VSq, curve.A).Multiply(W).Add(VCu);
  1533. ECFieldElement X3 = V.Multiply(A);
  1534. ECFieldElement VSqZ2 = Z2IsOne ? VSq : VSq.Multiply(Z2);
  1535. ECFieldElement Y3 = U.MultiplyPlusProduct(X1, V, Y1).MultiplyPlusProduct(VSqZ2, uv, A);
  1536. ECFieldElement Z3 = VCu.Multiply(W);
  1537. return new F2mPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
  1538. }
  1539. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1540. {
  1541. if (X1.IsZero)
  1542. {
  1543. if (X2.IsZero)
  1544. return curve.Infinity;
  1545. return b.Add(this);
  1546. }
  1547. ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
  1548. ECFieldElement L2 = b.RawYCoord, Z2 = b.RawZCoords[0];
  1549. bool Z1IsOne = Z1.IsOne;
  1550. ECFieldElement U2 = X2, S2 = L2;
  1551. if (!Z1IsOne)
  1552. {
  1553. U2 = U2.Multiply(Z1);
  1554. S2 = S2.Multiply(Z1);
  1555. }
  1556. bool Z2IsOne = Z2.IsOne;
  1557. ECFieldElement U1 = X1, S1 = L1;
  1558. if (!Z2IsOne)
  1559. {
  1560. U1 = U1.Multiply(Z2);
  1561. S1 = S1.Multiply(Z2);
  1562. }
  1563. ECFieldElement A = S1.Add(S2);
  1564. ECFieldElement B = U1.Add(U2);
  1565. if (B.IsZero)
  1566. {
  1567. if (A.IsZero)
  1568. {
  1569. return Twice();
  1570. }
  1571. return curve.Infinity;
  1572. }
  1573. ECFieldElement X3, L3, Z3;
  1574. if (X2.IsZero)
  1575. {
  1576. // TODO This can probably be optimized quite a bit
  1577. ECPoint p = this.Normalize();
  1578. X1 = p.RawXCoord;
  1579. ECFieldElement Y1 = p.YCoord;
  1580. ECFieldElement Y2 = L2;
  1581. ECFieldElement L = Y1.Add(Y2).Divide(X1);
  1582. X3 = L.Square().Add(L).Add(X1).Add(curve.A);
  1583. if (X3.IsZero)
  1584. {
  1585. return new F2mPoint(curve, X3, curve.B.Sqrt(), IsCompressed);
  1586. }
  1587. ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1);
  1588. L3 = Y3.Divide(X3).Add(X3);
  1589. Z3 = curve.FromBigInteger(BigInteger.One);
  1590. }
  1591. else
  1592. {
  1593. B = B.Square();
  1594. ECFieldElement AU1 = A.Multiply(U1);
  1595. ECFieldElement AU2 = A.Multiply(U2);
  1596. X3 = AU1.Multiply(AU2);
  1597. if (X3.IsZero)
  1598. {
  1599. return new F2mPoint(curve, X3, curve.B.Sqrt(), IsCompressed);
  1600. }
  1601. ECFieldElement ABZ2 = A.Multiply(B);
  1602. if (!Z2IsOne)
  1603. {
  1604. ABZ2 = ABZ2.Multiply(Z2);
  1605. }
  1606. L3 = AU2.Add(B).SquarePlusProduct(ABZ2, L1.Add(Z1));
  1607. Z3 = ABZ2;
  1608. if (!Z1IsOne)
  1609. {
  1610. Z3 = Z3.Multiply(Z1);
  1611. }
  1612. }
  1613. return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed);
  1614. }
  1615. default:
  1616. {
  1617. throw new InvalidOperationException("unsupported coordinate system");
  1618. }
  1619. }
  1620. }
  1621. /* (non-Javadoc)
  1622. * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.ECPoint#twice()
  1623. */
  1624. public override ECPoint Twice()
  1625. {
  1626. if (this.IsInfinity)
  1627. return this;
  1628. ECCurve curve = this.Curve;
  1629. ECFieldElement X1 = this.RawXCoord;
  1630. if (X1.IsZero)
  1631. {
  1632. // A point with X == 0 is it's own additive inverse
  1633. return curve.Infinity;
  1634. }
  1635. int coord = curve.CoordinateSystem;
  1636. switch (coord)
  1637. {
  1638. case ECCurve.COORD_AFFINE:
  1639. {
  1640. ECFieldElement Y1 = this.RawYCoord;
  1641. ECFieldElement L1 = Y1.Divide(X1).Add(X1);
  1642. ECFieldElement X3 = L1.Square().Add(L1).Add(curve.A);
  1643. ECFieldElement Y3 = X1.SquarePlusProduct(X3, L1.AddOne());
  1644. return new F2mPoint(curve, X3, Y3, IsCompressed);
  1645. }
  1646. case ECCurve.COORD_HOMOGENEOUS:
  1647. {
  1648. ECFieldElement Y1 = this.RawYCoord, Z1 = this.RawZCoords[0];
  1649. bool Z1IsOne = Z1.IsOne;
  1650. ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1);
  1651. ECFieldElement Y1Z1 = Z1IsOne ? Y1 : Y1.Multiply(Z1);
  1652. ECFieldElement X1Sq = X1.Square();
  1653. ECFieldElement S = X1Sq.Add(Y1Z1);
  1654. ECFieldElement V = X1Z1;
  1655. ECFieldElement vSquared = V.Square();
  1656. ECFieldElement sv = S.Add(V);
  1657. ECFieldElement h = sv.MultiplyPlusProduct(S, vSquared, curve.A);
  1658. ECFieldElement X3 = V.Multiply(h);
  1659. ECFieldElement Y3 = X1Sq.Square().MultiplyPlusProduct(V, h, sv);
  1660. ECFieldElement Z3 = V.Multiply(vSquared);
  1661. return new F2mPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
  1662. }
  1663. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1664. {
  1665. ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
  1666. bool Z1IsOne = Z1.IsOne;
  1667. ECFieldElement L1Z1 = Z1IsOne ? L1 : L1.Multiply(Z1);
  1668. ECFieldElement Z1Sq = Z1IsOne ? Z1 : Z1.Square();
  1669. ECFieldElement a = curve.A;
  1670. ECFieldElement aZ1Sq = Z1IsOne ? a : a.Multiply(Z1Sq);
  1671. ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq);
  1672. if (T.IsZero)
  1673. {
  1674. return new F2mPoint(curve, T, curve.B.Sqrt(), IsCompressed);
  1675. }
  1676. ECFieldElement X3 = T.Square();
  1677. ECFieldElement Z3 = Z1IsOne ? T : T.Multiply(Z1Sq);
  1678. ECFieldElement b = curve.B;
  1679. ECFieldElement L3;
  1680. if (b.BitLength < (curve.FieldSize >> 1))
  1681. {
  1682. ECFieldElement t1 = L1.Add(X1).Square();
  1683. ECFieldElement t2;
  1684. if (b.IsOne)
  1685. {
  1686. t2 = aZ1Sq.Add(Z1Sq).Square();
  1687. }
  1688. else
  1689. {
  1690. // TODO Can be calculated with one square if we pre-compute sqrt(b)
  1691. t2 = aZ1Sq.SquarePlusProduct(b, Z1Sq.Square());
  1692. }
  1693. L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(t2).Add(X3);
  1694. if (a.IsZero)
  1695. {
  1696. L3 = L3.Add(Z3);
  1697. }
  1698. else if (!a.IsOne)
  1699. {
  1700. L3 = L3.Add(a.AddOne().Multiply(Z3));
  1701. }
  1702. }
  1703. else
  1704. {
  1705. ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1);
  1706. L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3);
  1707. }
  1708. return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed);
  1709. }
  1710. default:
  1711. {
  1712. throw new InvalidOperationException("unsupported coordinate system");
  1713. }
  1714. }
  1715. }
  1716. public override ECPoint TwicePlus(ECPoint b)
  1717. {
  1718. if (this.IsInfinity)
  1719. return b;
  1720. if (b.IsInfinity)
  1721. return Twice();
  1722. ECCurve curve = this.Curve;
  1723. ECFieldElement X1 = this.RawXCoord;
  1724. if (X1.IsZero)
  1725. {
  1726. // A point with X == 0 is it's own additive inverse
  1727. return b;
  1728. }
  1729. int coord = curve.CoordinateSystem;
  1730. switch (coord)
  1731. {
  1732. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1733. {
  1734. // NOTE: twicePlus() only optimized for lambda-affine argument
  1735. ECFieldElement X2 = b.RawXCoord, Z2 = b.RawZCoords[0];
  1736. if (X2.IsZero || !Z2.IsOne)
  1737. {
  1738. return Twice().Add(b);
  1739. }
  1740. ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
  1741. ECFieldElement L2 = b.RawYCoord;
  1742. ECFieldElement X1Sq = X1.Square();
  1743. ECFieldElement L1Sq = L1.Square();
  1744. ECFieldElement Z1Sq = Z1.Square();
  1745. ECFieldElement L1Z1 = L1.Multiply(Z1);
  1746. ECFieldElement T = curve.A.Multiply(Z1Sq).Add(L1Sq).Add(L1Z1);
  1747. ECFieldElement L2plus1 = L2.AddOne();
  1748. ECFieldElement A = curve.A.Add(L2plus1).Multiply(Z1Sq).Add(L1Sq).MultiplyPlusProduct(T, X1Sq, Z1Sq);
  1749. ECFieldElement X2Z1Sq = X2.Multiply(Z1Sq);
  1750. ECFieldElement B = X2Z1Sq.Add(T).Square();
  1751. if (B.IsZero)
  1752. {
  1753. if (A.IsZero)
  1754. {
  1755. return b.Twice();
  1756. }
  1757. return curve.Infinity;
  1758. }
  1759. if (A.IsZero)
  1760. {
  1761. return new F2mPoint(curve, A, curve.B.Sqrt(), IsCompressed);
  1762. }
  1763. ECFieldElement X3 = A.Square().Multiply(X2Z1Sq);
  1764. ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq);
  1765. ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3);
  1766. return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed);
  1767. }
  1768. default:
  1769. {
  1770. return Twice().Add(b);
  1771. }
  1772. }
  1773. }
  1774. public override ECPoint Negate()
  1775. {
  1776. if (this.IsInfinity)
  1777. return this;
  1778. ECFieldElement X = this.RawXCoord;
  1779. if (X.IsZero)
  1780. return this;
  1781. ECCurve curve = this.Curve;
  1782. int coord = curve.CoordinateSystem;
  1783. switch (coord)
  1784. {
  1785. case ECCurve.COORD_AFFINE:
  1786. {
  1787. ECFieldElement Y = this.RawYCoord;
  1788. return new F2mPoint(curve, X, Y.Add(X), IsCompressed);
  1789. }
  1790. case ECCurve.COORD_HOMOGENEOUS:
  1791. {
  1792. ECFieldElement Y = this.RawYCoord, Z = this.RawZCoords[0];
  1793. return new F2mPoint(curve, X, Y.Add(X), new ECFieldElement[] { Z }, IsCompressed);
  1794. }
  1795. case ECCurve.COORD_LAMBDA_AFFINE:
  1796. {
  1797. ECFieldElement L = this.RawYCoord;
  1798. return new F2mPoint(curve, X, L.AddOne(), IsCompressed);
  1799. }
  1800. case ECCurve.COORD_LAMBDA_PROJECTIVE:
  1801. {
  1802. // L is actually Lambda (X + Y/X) here
  1803. ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0];
  1804. return new F2mPoint(curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed);
  1805. }
  1806. default:
  1807. {
  1808. throw new InvalidOperationException("unsupported coordinate system");
  1809. }
  1810. }
  1811. }
  1812. }
  1813. }
  1814. #pragma warning restore
  1815. #endif