XSalsa20Engine.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 XSalsa20 stream cipher - Salsa20 with an extended nonce.
  9. /// </summary>
  10. /// <remarks>
  11. /// XSalsa20 requires a 256 bit key, and a 192 bit nonce.
  12. /// </remarks>
  13. public class XSalsa20Engine
  14. : Salsa20Engine
  15. {
  16. public override string AlgorithmName
  17. {
  18. get { return "XSalsa20"; }
  19. }
  20. protected override int NonceSize
  21. {
  22. get { return 24; }
  23. }
  24. /// <summary>
  25. /// XSalsa20 key generation: process 256 bit input key and 128 bits of the input nonce
  26. /// using a core Salsa20 function without input addition to produce 256 bit working key
  27. /// and use that with the remaining 64 bits of nonce to initialize a standard Salsa20 engine state.
  28. /// </summary>
  29. protected override void SetKey(byte[] keyBytes, byte[] ivBytes)
  30. {
  31. if (keyBytes == null)
  32. throw new ArgumentException(AlgorithmName + " doesn't support re-init with null key");
  33. if (keyBytes.Length != 32)
  34. throw new ArgumentException(AlgorithmName + " requires a 256 bit key");
  35. // Set key for HSalsa20
  36. base.SetKey(keyBytes, ivBytes);
  37. // Pack next 64 bits of IV into engine state instead of counter
  38. Pack.LE_To_UInt32(ivBytes, 8, engineState, 8, 2);
  39. // Process engine state to generate Salsa20 key
  40. uint[] hsalsa20Out = new uint[engineState.Length];
  41. SalsaCore(20, engineState, hsalsa20Out);
  42. // Set new key, removing addition in last round of salsaCore
  43. engineState[1] = hsalsa20Out[0] - engineState[0];
  44. engineState[2] = hsalsa20Out[5] - engineState[5];
  45. engineState[3] = hsalsa20Out[10] - engineState[10];
  46. engineState[4] = hsalsa20Out[15] - engineState[15];
  47. engineState[11] = hsalsa20Out[6] - engineState[6];
  48. engineState[12] = hsalsa20Out[7] - engineState[7];
  49. engineState[13] = hsalsa20Out[8] - engineState[8];
  50. engineState[14] = hsalsa20Out[9] - engineState[9];
  51. // Last 64 bits of input IV
  52. Pack.LE_To_UInt32(ivBytes, 16, engineState, 6, 2);
  53. }
  54. }
  55. }
  56. #pragma warning restore
  57. #endif