ECPoint.cs 73 KB

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