FastChaCha7539Engine.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  5. namespace BestHTTP.Connections.TLS.Crypto.Impl
  6. {
  7. /// <summary>
  8. /// Implementation of Daniel J. Bernstein's ChaCha stream cipher.
  9. /// </summary>
  10. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  11. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  12. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  13. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  14. public sealed class FastChaCha7539Engine
  15. : FastSalsa20Engine
  16. {
  17. /// <summary>
  18. /// Creates a 20 rounds ChaCha engine.
  19. /// </summary>
  20. public FastChaCha7539Engine()
  21. : base()
  22. {
  23. }
  24. public override string AlgorithmName
  25. {
  26. get { return "ChaCha7539"; }
  27. }
  28. protected override int NonceSize
  29. {
  30. get { return 12; }
  31. }
  32. protected override void AdvanceCounter()
  33. {
  34. if (++engineState[12] == 0)
  35. throw new InvalidOperationException("attempt to increase counter past 2^32.");
  36. }
  37. protected override void ResetCounter()
  38. {
  39. engineState[12] = 0;
  40. }
  41. protected override void SetKey(byte[] keyBytes, byte[] ivBytes)
  42. {
  43. if (keyBytes != null)
  44. {
  45. if (keyBytes.Length != 32)
  46. throw new ArgumentException(AlgorithmName + " requires 256 bit key");
  47. PackTauOrSigma(keyBytes.Length, engineState, 0);
  48. // Key
  49. Pack.LE_To_UInt32(keyBytes, 0, engineState, 4, 8);
  50. }
  51. // IV
  52. Pack.LE_To_UInt32(ivBytes, 0, engineState, 13, 3);
  53. }
  54. protected override void GenerateKeyStream(byte[] output)
  55. {
  56. FastChaChaEngine.ChachaCore(rounds, engineState, x);
  57. Pack.UInt32_To_LE(x, output, 0);
  58. }
  59. }
  60. }
  61. #pragma warning restore
  62. #endif