ChaCha7539Engine.cs 1.7 KB

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