FixedPointUtilities.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier
  5. {
  6. public class FixedPointUtilities
  7. {
  8. public static readonly string PRECOMP_NAME = "bc_fixed_point";
  9. public static int GetCombSize(ECCurve c)
  10. {
  11. BigInteger order = c.Order;
  12. return order == null ? c.FieldSize + 1 : order.BitLength;
  13. }
  14. public static FixedPointPreCompInfo GetFixedPointPreCompInfo(PreCompInfo preCompInfo)
  15. {
  16. return preCompInfo as FixedPointPreCompInfo;
  17. }
  18. public static FixedPointPreCompInfo Precompute(ECPoint p)
  19. {
  20. return (FixedPointPreCompInfo)p.Curve.Precompute(p, PRECOMP_NAME, new FixedPointCallback(p));
  21. }
  22. private class FixedPointCallback
  23. : IPreCompCallback
  24. {
  25. private readonly ECPoint m_p;
  26. internal FixedPointCallback(ECPoint p)
  27. {
  28. this.m_p = p;
  29. }
  30. public PreCompInfo Precompute(PreCompInfo existing)
  31. {
  32. FixedPointPreCompInfo existingFP = (existing is FixedPointPreCompInfo) ? (FixedPointPreCompInfo)existing : null;
  33. ECCurve c = m_p.Curve;
  34. int bits = FixedPointUtilities.GetCombSize(c);
  35. int minWidth = bits > 250 ? 6 : 5;
  36. int n = 1 << minWidth;
  37. if (CheckExisting(existingFP, n))
  38. return existingFP;
  39. int d = (bits + minWidth - 1) / minWidth;
  40. ECPoint[] pow2Table = new ECPoint[minWidth + 1];
  41. pow2Table[0] = m_p;
  42. for (int i = 1; i < minWidth; ++i)
  43. {
  44. pow2Table[i] = pow2Table[i - 1].TimesPow2(d);
  45. }
  46. // This will be the 'offset' value
  47. pow2Table[minWidth] = pow2Table[0].Subtract(pow2Table[1]);
  48. c.NormalizeAll(pow2Table);
  49. ECPoint[] lookupTable = new ECPoint[n];
  50. lookupTable[0] = pow2Table[0];
  51. for (int bit = minWidth - 1; bit >= 0; --bit)
  52. {
  53. ECPoint pow2 = pow2Table[bit];
  54. int step = 1 << bit;
  55. for (int i = step; i < n; i += (step << 1))
  56. {
  57. lookupTable[i] = lookupTable[i - step].Add(pow2);
  58. }
  59. }
  60. c.NormalizeAll(lookupTable);
  61. FixedPointPreCompInfo result = new FixedPointPreCompInfo();
  62. result.LookupTable = c.CreateCacheSafeLookupTable(lookupTable, 0, lookupTable.Length);
  63. result.Offset = pow2Table[minWidth];
  64. result.Width = minWidth;
  65. return result;
  66. }
  67. private bool CheckExisting(FixedPointPreCompInfo existingFP, int n)
  68. {
  69. return existingFP != null && CheckTable(existingFP.LookupTable, n);
  70. }
  71. private bool CheckTable(ECLookupTable table, int n)
  72. {
  73. return table != null && table.Size >= n;
  74. }
  75. }
  76. }
  77. }
  78. #pragma warning restore
  79. #endif