ECAlgorithms.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using System;
  2. using Renci.SshNet.Security.Org.BouncyCastle.Math.EC.Endo;
  3. using Renci.SshNet.Security.Org.BouncyCastle.Math.EC.Multiplier;
  4. using Renci.SshNet.Security.Org.BouncyCastle.Math.Field;
  5. namespace Renci.SshNet.Security.Org.BouncyCastle.Math.EC
  6. {
  7. internal class ECAlgorithms
  8. {
  9. public static bool IsF2mCurve(ECCurve c)
  10. {
  11. return IsF2mField(c.Field);
  12. }
  13. public static bool IsF2mField(IFiniteField field)
  14. {
  15. return field.Dimension > 1 && field.Characteristic.Equals(BigInteger.Two)
  16. && field is IPolynomialExtensionField;
  17. }
  18. public static bool IsFpCurve(ECCurve c)
  19. {
  20. return IsFpField(c.Field);
  21. }
  22. public static bool IsFpField(IFiniteField field)
  23. {
  24. return field.Dimension == 1;
  25. }
  26. public static ECPoint SumOfMultiplies(ECPoint[] ps, BigInteger[] ks)
  27. {
  28. if (ps == null || ks == null || ps.Length != ks.Length || ps.Length < 1)
  29. throw new ArgumentException("point and scalar arrays should be non-null, and of equal, non-zero, length");
  30. int count = ps.Length;
  31. switch (count)
  32. {
  33. case 1:
  34. return ps[0].Multiply(ks[0]);
  35. case 2:
  36. return SumOfTwoMultiplies(ps[0], ks[0], ps[1], ks[1]);
  37. default:
  38. break;
  39. }
  40. ECPoint p = ps[0];
  41. ECCurve c = p.Curve;
  42. ECPoint[] imported = new ECPoint[count];
  43. imported[0] = p;
  44. for (int i = 1; i < count; ++i)
  45. {
  46. imported[i] = ImportPoint(c, ps[i]);
  47. }
  48. GlvEndomorphism glvEndomorphism = c.GetEndomorphism() as GlvEndomorphism;
  49. if (glvEndomorphism != null)
  50. {
  51. return ImplCheckResult(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism));
  52. }
  53. return ImplCheckResult(ImplSumOfMultiplies(imported, ks));
  54. }
  55. public static ECPoint SumOfTwoMultiplies(ECPoint P, BigInteger a, ECPoint Q, BigInteger b)
  56. {
  57. ECCurve cp = P.Curve;
  58. Q = ImportPoint(cp, Q);
  59. // Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick
  60. {
  61. AbstractF2mCurve f2mCurve = cp as AbstractF2mCurve;
  62. if (f2mCurve != null && f2mCurve.IsKoblitz)
  63. {
  64. return ImplCheckResult(P.Multiply(a).Add(Q.Multiply(b)));
  65. }
  66. }
  67. GlvEndomorphism glvEndomorphism = cp.GetEndomorphism() as GlvEndomorphism;
  68. if (glvEndomorphism != null)
  69. {
  70. return ImplCheckResult(
  71. ImplSumOfMultipliesGlv(new ECPoint[] { P, Q }, new BigInteger[] { a, b }, glvEndomorphism));
  72. }
  73. return ImplCheckResult(ImplShamirsTrickWNaf(P, a, Q, b));
  74. }
  75. /*
  76. * "Shamir's Trick", originally due to E. G. Straus
  77. * (Addition chains of vectors. American Mathematical Monthly,
  78. * 71(7):806-808, Aug./Sept. 1964)
  79. *
  80. * Input: The points P, Q, scalar k = (km?, ... , k1, k0)
  81. * and scalar l = (lm?, ... , l1, l0).
  82. * Output: R = k * P + l * Q.
  83. * 1: Z <- P + Q
  84. * 2: R <- O
  85. * 3: for i from m-1 down to 0 do
  86. * 4: R <- R + R {point doubling}
  87. * 5: if (ki = 1) and (li = 0) then R <- R + P end if
  88. * 6: if (ki = 0) and (li = 1) then R <- R + Q end if
  89. * 7: if (ki = 1) and (li = 1) then R <- R + Z end if
  90. * 8: end for
  91. * 9: return R
  92. */
  93. public static ECPoint ShamirsTrick(ECPoint P, BigInteger k, ECPoint Q, BigInteger l)
  94. {
  95. ECCurve cp = P.Curve;
  96. Q = ImportPoint(cp, Q);
  97. return ImplCheckResult(ImplShamirsTrickJsf(P, k, Q, l));
  98. }
  99. public static ECPoint ImportPoint(ECCurve c, ECPoint p)
  100. {
  101. ECCurve cp = p.Curve;
  102. if (!c.Equals(cp))
  103. throw new ArgumentException("Point must be on the same curve");
  104. return c.ImportPoint(p);
  105. }
  106. public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len)
  107. {
  108. MontgomeryTrick(zs, off, len, null);
  109. }
  110. public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len, ECFieldElement scale)
  111. {
  112. /*
  113. * Uses the "Montgomery Trick" to invert many field elements, with only a single actual
  114. * field inversion. See e.g. the paper:
  115. * "Fast Multi-scalar Multiplication Methods on Elliptic Curves with Precomputation Strategy Using Montgomery Trick"
  116. * by Katsuyuki Okeya, Kouichi Sakurai.
  117. */
  118. ECFieldElement[] c = new ECFieldElement[len];
  119. c[0] = zs[off];
  120. int i = 0;
  121. while (++i < len)
  122. {
  123. c[i] = c[i - 1].Multiply(zs[off + i]);
  124. }
  125. --i;
  126. if (scale != null)
  127. {
  128. c[i] = c[i].Multiply(scale);
  129. }
  130. ECFieldElement u = c[i].Invert();
  131. while (i > 0)
  132. {
  133. int j = off + i--;
  134. ECFieldElement tmp = zs[j];
  135. zs[j] = c[i].Multiply(u);
  136. u = u.Multiply(tmp);
  137. }
  138. zs[off] = u;
  139. }
  140. /**
  141. * Simple shift-and-add multiplication. Serves as reference implementation
  142. * to verify (possibly faster) implementations, and for very small scalars.
  143. *
  144. * @param p
  145. * The point to multiply.
  146. * @param k
  147. * The multiplier.
  148. * @return The result of the point multiplication <code>kP</code>.
  149. */
  150. public static ECPoint ReferenceMultiply(ECPoint p, BigInteger k)
  151. {
  152. BigInteger x = k.Abs();
  153. ECPoint q = p.Curve.Infinity;
  154. int t = x.BitLength;
  155. if (t > 0)
  156. {
  157. if (x.TestBit(0))
  158. {
  159. q = p;
  160. }
  161. for (int i = 1; i < t; i++)
  162. {
  163. p = p.Twice();
  164. if (x.TestBit(i))
  165. {
  166. q = q.Add(p);
  167. }
  168. }
  169. }
  170. return k.SignValue < 0 ? q.Negate() : q;
  171. }
  172. public static ECPoint ValidatePoint(ECPoint p)
  173. {
  174. if (!p.IsValid())
  175. throw new InvalidOperationException("Invalid point");
  176. return p;
  177. }
  178. public static ECPoint CleanPoint(ECCurve c, ECPoint p)
  179. {
  180. ECCurve cp = p.Curve;
  181. if (!c.Equals(cp))
  182. throw new ArgumentException("Point must be on the same curve", "p");
  183. return c.DecodePoint(p.GetEncoded(false));
  184. }
  185. internal static ECPoint ImplCheckResult(ECPoint p)
  186. {
  187. if (!p.IsValidPartial())
  188. throw new InvalidOperationException("Invalid result");
  189. return p;
  190. }
  191. internal static ECPoint ImplShamirsTrickJsf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l)
  192. {
  193. ECCurve curve = P.Curve;
  194. ECPoint infinity = curve.Infinity;
  195. // TODO conjugate co-Z addition (ZADDC) can return both of these
  196. ECPoint PaddQ = P.Add(Q);
  197. ECPoint PsubQ = P.Subtract(Q);
  198. ECPoint[] points = new ECPoint[] { Q, PsubQ, P, PaddQ };
  199. curve.NormalizeAll(points);
  200. ECPoint[] table = new ECPoint[] {
  201. points[3].Negate(), points[2].Negate(), points[1].Negate(),
  202. points[0].Negate(), infinity, points[0],
  203. points[1], points[2], points[3] };
  204. byte[] jsf = WNafUtilities.GenerateJsf(k, l);
  205. ECPoint R = infinity;
  206. int i = jsf.Length;
  207. while (--i >= 0)
  208. {
  209. int jsfi = jsf[i];
  210. // NOTE: The shifting ensures the sign is extended correctly
  211. int kDigit = ((jsfi << 24) >> 28), lDigit = ((jsfi << 28) >> 28);
  212. int index = 4 + (kDigit * 3) + lDigit;
  213. R = R.TwicePlus(table[index]);
  214. }
  215. return R;
  216. }
  217. internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k,
  218. ECPoint Q, BigInteger l)
  219. {
  220. bool negK = k.SignValue < 0, negL = l.SignValue < 0;
  221. k = k.Abs();
  222. l = l.Abs();
  223. int widthP = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(k.BitLength)));
  224. int widthQ = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(l.BitLength)));
  225. WNafPreCompInfo infoP = WNafUtilities.Precompute(P, widthP, true);
  226. WNafPreCompInfo infoQ = WNafUtilities.Precompute(Q, widthQ, true);
  227. ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp;
  228. ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp;
  229. ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg;
  230. ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg;
  231. byte[] wnafP = WNafUtilities.GenerateWindowNaf(widthP, k);
  232. byte[] wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, l);
  233. return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ);
  234. }
  235. internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPointMap pointMapQ, BigInteger l)
  236. {
  237. bool negK = k.SignValue < 0, negL = l.SignValue < 0;
  238. k = k.Abs();
  239. l = l.Abs();
  240. int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(k.BitLength, l.BitLength))));
  241. ECPoint Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMapQ);
  242. WNafPreCompInfo infoP = WNafUtilities.GetWNafPreCompInfo(P);
  243. WNafPreCompInfo infoQ = WNafUtilities.GetWNafPreCompInfo(Q);
  244. ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp;
  245. ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp;
  246. ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg;
  247. ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg;
  248. byte[] wnafP = WNafUtilities.GenerateWindowNaf(width, k);
  249. byte[] wnafQ = WNafUtilities.GenerateWindowNaf(width, l);
  250. return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ);
  251. }
  252. private static ECPoint ImplShamirsTrickWNaf(ECPoint[] preCompP, ECPoint[] preCompNegP, byte[] wnafP,
  253. ECPoint[] preCompQ, ECPoint[] preCompNegQ, byte[] wnafQ)
  254. {
  255. int len = System.Math.Max(wnafP.Length, wnafQ.Length);
  256. ECCurve curve = preCompP[0].Curve;
  257. ECPoint infinity = curve.Infinity;
  258. ECPoint R = infinity;
  259. int zeroes = 0;
  260. for (int i = len - 1; i >= 0; --i)
  261. {
  262. int wiP = i < wnafP.Length ? (int)(sbyte)wnafP[i] : 0;
  263. int wiQ = i < wnafQ.Length ? (int)(sbyte)wnafQ[i] : 0;
  264. if ((wiP | wiQ) == 0)
  265. {
  266. ++zeroes;
  267. continue;
  268. }
  269. ECPoint r = infinity;
  270. if (wiP != 0)
  271. {
  272. int nP = System.Math.Abs(wiP);
  273. ECPoint[] tableP = wiP < 0 ? preCompNegP : preCompP;
  274. r = r.Add(tableP[nP >> 1]);
  275. }
  276. if (wiQ != 0)
  277. {
  278. int nQ = System.Math.Abs(wiQ);
  279. ECPoint[] tableQ = wiQ < 0 ? preCompNegQ : preCompQ;
  280. r = r.Add(tableQ[nQ >> 1]);
  281. }
  282. if (zeroes > 0)
  283. {
  284. R = R.TimesPow2(zeroes);
  285. zeroes = 0;
  286. }
  287. R = R.TwicePlus(r);
  288. }
  289. if (zeroes > 0)
  290. {
  291. R = R.TimesPow2(zeroes);
  292. }
  293. return R;
  294. }
  295. internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, BigInteger[] ks)
  296. {
  297. int count = ps.Length;
  298. bool[] negs = new bool[count];
  299. WNafPreCompInfo[] infos = new WNafPreCompInfo[count];
  300. byte[][] wnafs = new byte[count][];
  301. for (int i = 0; i < count; ++i)
  302. {
  303. BigInteger ki = ks[i]; negs[i] = ki.SignValue < 0; ki = ki.Abs();
  304. int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(ki.BitLength)));
  305. infos[i] = WNafUtilities.Precompute(ps[i], width, true);
  306. wnafs[i] = WNafUtilities.GenerateWindowNaf(width, ki);
  307. }
  308. return ImplSumOfMultiplies(negs, infos, wnafs);
  309. }
  310. internal static ECPoint ImplSumOfMultipliesGlv(ECPoint[] ps, BigInteger[] ks, GlvEndomorphism glvEndomorphism)
  311. {
  312. BigInteger n = ps[0].Curve.Order;
  313. int len = ps.Length;
  314. BigInteger[] abs = new BigInteger[len << 1];
  315. for (int i = 0, j = 0; i < len; ++i)
  316. {
  317. BigInteger[] ab = glvEndomorphism.DecomposeScalar(ks[i].Mod(n));
  318. abs[j++] = ab[0];
  319. abs[j++] = ab[1];
  320. }
  321. ECPointMap pointMap = glvEndomorphism.PointMap;
  322. if (glvEndomorphism.HasEfficientPointMap)
  323. {
  324. return ECAlgorithms.ImplSumOfMultiplies(ps, pointMap, abs);
  325. }
  326. ECPoint[] pqs = new ECPoint[len << 1];
  327. for (int i = 0, j = 0; i < len; ++i)
  328. {
  329. ECPoint p = ps[i], q = pointMap.Map(p);
  330. pqs[j++] = p;
  331. pqs[j++] = q;
  332. }
  333. return ECAlgorithms.ImplSumOfMultiplies(pqs, abs);
  334. }
  335. internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, ECPointMap pointMap, BigInteger[] ks)
  336. {
  337. int halfCount = ps.Length, fullCount = halfCount << 1;
  338. bool[] negs = new bool[fullCount];
  339. WNafPreCompInfo[] infos = new WNafPreCompInfo[fullCount];
  340. byte[][] wnafs = new byte[fullCount][];
  341. for (int i = 0; i < halfCount; ++i)
  342. {
  343. int j0 = i << 1, j1 = j0 + 1;
  344. BigInteger kj0 = ks[j0]; negs[j0] = kj0.SignValue < 0; kj0 = kj0.Abs();
  345. BigInteger kj1 = ks[j1]; negs[j1] = kj1.SignValue < 0; kj1 = kj1.Abs();
  346. int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(kj0.BitLength, kj1.BitLength))));
  347. ECPoint P = ps[i], Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMap);
  348. infos[j0] = WNafUtilities.GetWNafPreCompInfo(P);
  349. infos[j1] = WNafUtilities.GetWNafPreCompInfo(Q);
  350. wnafs[j0] = WNafUtilities.GenerateWindowNaf(width, kj0);
  351. wnafs[j1] = WNafUtilities.GenerateWindowNaf(width, kj1);
  352. }
  353. return ImplSumOfMultiplies(negs, infos, wnafs);
  354. }
  355. private static ECPoint ImplSumOfMultiplies(bool[] negs, WNafPreCompInfo[] infos, byte[][] wnafs)
  356. {
  357. int len = 0, count = wnafs.Length;
  358. for (int i = 0; i < count; ++i)
  359. {
  360. len = System.Math.Max(len, wnafs[i].Length);
  361. }
  362. ECCurve curve = infos[0].PreComp[0].Curve;
  363. ECPoint infinity = curve.Infinity;
  364. ECPoint R = infinity;
  365. int zeroes = 0;
  366. for (int i = len - 1; i >= 0; --i)
  367. {
  368. ECPoint r = infinity;
  369. for (int j = 0; j < count; ++j)
  370. {
  371. byte[] wnaf = wnafs[j];
  372. int wi = i < wnaf.Length ? (int)(sbyte)wnaf[i] : 0;
  373. if (wi != 0)
  374. {
  375. int n = System.Math.Abs(wi);
  376. WNafPreCompInfo info = infos[j];
  377. ECPoint[] table = (wi < 0 == negs[j]) ? info.PreComp : info.PreCompNeg;
  378. r = r.Add(table[n >> 1]);
  379. }
  380. }
  381. if (r == infinity)
  382. {
  383. ++zeroes;
  384. continue;
  385. }
  386. if (zeroes > 0)
  387. {
  388. R = R.TimesPow2(zeroes);
  389. zeroes = 0;
  390. }
  391. R = R.TwicePlus(r);
  392. }
  393. if (zeroes > 0)
  394. {
  395. R = R.TimesPow2(zeroes);
  396. }
  397. return R;
  398. }
  399. }
  400. }