EndoUtilities.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
  5. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Endo
  6. {
  7. public abstract class EndoUtilities
  8. {
  9. public static readonly string PRECOMP_NAME = "bc_endo";
  10. public static BigInteger[] DecomposeScalar(ScalarSplitParameters p, BigInteger k)
  11. {
  12. int bits = p.Bits;
  13. BigInteger b1 = CalculateB(k, p.G1, bits);
  14. BigInteger b2 = CalculateB(k, p.G2, bits);
  15. BigInteger a = k.Subtract((b1.Multiply(p.V1A)).Add(b2.Multiply(p.V2A)));
  16. BigInteger b = (b1.Multiply(p.V1B)).Add(b2.Multiply(p.V2B)).Negate();
  17. return new BigInteger[]{ a, b };
  18. }
  19. public static ECPoint MapPoint(ECEndomorphism endomorphism, ECPoint p)
  20. {
  21. EndoPreCompInfo precomp = (EndoPreCompInfo)p.Curve.Precompute(p, PRECOMP_NAME,
  22. new MapPointCallback(endomorphism, p));
  23. return precomp.MappedPoint;
  24. }
  25. private static BigInteger CalculateB(BigInteger k, BigInteger g, int t)
  26. {
  27. bool negative = (g.SignValue < 0);
  28. BigInteger b = k.Multiply(g.Abs());
  29. bool extra = b.TestBit(t - 1);
  30. b = b.ShiftRight(t);
  31. if (extra)
  32. {
  33. b = b.Add(BigInteger.One);
  34. }
  35. return negative ? b.Negate() : b;
  36. }
  37. private class MapPointCallback
  38. : IPreCompCallback
  39. {
  40. private readonly ECEndomorphism m_endomorphism;
  41. private readonly ECPoint m_point;
  42. internal MapPointCallback(ECEndomorphism endomorphism, ECPoint point)
  43. {
  44. this.m_endomorphism = endomorphism;
  45. this.m_point = point;
  46. }
  47. public PreCompInfo Precompute(PreCompInfo existing)
  48. {
  49. EndoPreCompInfo existingEndo = existing as EndoPreCompInfo;
  50. if (CheckExisting(existingEndo, m_endomorphism))
  51. return existingEndo;
  52. ECPoint mappedPoint = m_endomorphism.PointMap.Map(m_point);
  53. EndoPreCompInfo result = new EndoPreCompInfo();
  54. result.Endomorphism = m_endomorphism;
  55. result.MappedPoint = mappedPoint;
  56. return result;
  57. }
  58. private bool CheckExisting(EndoPreCompInfo existingEndo, ECEndomorphism endomorphism)
  59. {
  60. return null != existingEndo
  61. && existingEndo.Endomorphism == endomorphism
  62. && existingEndo.MappedPoint != null;
  63. }
  64. }
  65. }
  66. }
  67. #pragma warning restore
  68. #endif