ECAlgorithms.cs 16 KB

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