Tables1kGcmExponentiator.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections.Generic;
  5. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
  6. {
  7. public class Tables1kGcmExponentiator
  8. : IGcmExponentiator
  9. {
  10. // A lookup table of the power-of-two powers of 'x'
  11. // - lookupPowX2[i] = x^(2^i)
  12. private IList<GcmUtilities.FieldElement> lookupPowX2;
  13. public void Init(byte[] x)
  14. {
  15. GcmUtilities.FieldElement y;
  16. GcmUtilities.AsFieldElement(x, out y);
  17. if (lookupPowX2 != null && y.Equals(lookupPowX2[0]))
  18. return;
  19. lookupPowX2 = new List<GcmUtilities.FieldElement>(8);
  20. lookupPowX2.Add(y);
  21. }
  22. public void ExponentiateX(long pow, byte[] output)
  23. {
  24. GcmUtilities.FieldElement y;
  25. GcmUtilities.One(out y);
  26. int bit = 0;
  27. while (pow > 0)
  28. {
  29. if ((pow & 1L) != 0)
  30. {
  31. EnsureAvailable(bit);
  32. GcmUtilities.FieldElement powX2 = (GcmUtilities.FieldElement)lookupPowX2[bit];
  33. GcmUtilities.Multiply(ref y, ref powX2);
  34. }
  35. ++bit;
  36. pow >>= 1;
  37. }
  38. GcmUtilities.AsBytes(ref y, output);
  39. }
  40. private void EnsureAvailable(int bit)
  41. {
  42. int count = lookupPowX2.Count;
  43. if (count <= bit)
  44. {
  45. GcmUtilities.FieldElement powX2 = (GcmUtilities.FieldElement)lookupPowX2[count - 1];
  46. do
  47. {
  48. GcmUtilities.Square(ref powX2);
  49. lookupPowX2.Add(powX2);
  50. }
  51. while (++count <= bit);
  52. }
  53. }
  54. }
  55. }
  56. #pragma warning restore
  57. #endif