Tables1kGcmExponentiator.cs 1.8 KB

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