ChaCha7539Engine.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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.SecureProtocol.Org.BouncyCastle.Crypto.Engines
  6. {
  7. /// <summary>
  8. /// Implementation of Daniel J. Bernstein's ChaCha stream cipher.
  9. /// </summary>
  10. public class ChaCha7539Engine
  11. : Salsa20Engine
  12. {
  13. /// <summary>
  14. /// Creates a 20 rounds ChaCha engine.
  15. /// </summary>
  16. public ChaCha7539Engine()
  17. {
  18. }
  19. public override string AlgorithmName
  20. {
  21. get { return "ChaCha7539" + rounds; }
  22. }
  23. protected override int NonceSize
  24. {
  25. get { return 12; }
  26. }
  27. protected override void AdvanceCounter()
  28. {
  29. if (++engineState[12] == 0)
  30. throw new InvalidOperationException("attempt to increase counter past 2^32.");
  31. }
  32. protected override void ResetCounter()
  33. {
  34. engineState[12] = 0;
  35. }
  36. protected override void SetKey(byte[] keyBytes, byte[] ivBytes)
  37. {
  38. if (keyBytes != null)
  39. {
  40. if (keyBytes.Length != 32)
  41. throw new ArgumentException(AlgorithmName + " requires 256 bit key");
  42. PackTauOrSigma(keyBytes.Length, engineState, 0);
  43. // Key
  44. Pack.LE_To_UInt32(keyBytes, 0, engineState, 4, 8);
  45. }
  46. // IV
  47. Pack.LE_To_UInt32(ivBytes, 0, engineState, 13, 3);
  48. }
  49. protected override void GenerateKeyStream(byte[] output)
  50. {
  51. ChaChaEngine.ChachaCore(rounds, engineState, x);
  52. Pack.UInt32_To_LE(x, output, 0);
  53. }
  54. }
  55. }
  56. #pragma warning restore
  57. #endif