Salsa20Engine.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Text;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
  9. {
  10. /// <summary>
  11. /// Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005
  12. /// </summary>
  13. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  14. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  15. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  16. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  17. public class Salsa20Engine
  18. : IStreamCipher
  19. {
  20. public static readonly int DEFAULT_ROUNDS = 20;
  21. /** Constants */
  22. private const int StateSize = 16; // 16, 32 bit ints = 64 bytes
  23. private readonly static uint[] TAU_SIGMA = Pack.LE_To_UInt32(Strings.ToAsciiByteArray("expand 16-byte k" + "expand 32-byte k"), 0, 8);
  24. internal void PackTauOrSigma(int keyLength, uint[] state, int stateOffset)
  25. {
  26. int tsOff = (keyLength - 16) / 4;
  27. state[stateOffset] = TAU_SIGMA[tsOff];
  28. state[stateOffset + 1] = TAU_SIGMA[tsOff + 1];
  29. state[stateOffset + 2] = TAU_SIGMA[tsOff + 2];
  30. state[stateOffset + 3] = TAU_SIGMA[tsOff + 3];
  31. }
  32. [Obsolete]
  33. protected readonly static byte[]
  34. sigma = Strings.ToAsciiByteArray("expand 32-byte k"),
  35. tau = Strings.ToAsciiByteArray("expand 16-byte k");
  36. protected int rounds;
  37. /*
  38. * variables to hold the state of the engine
  39. * during encryption and decryption
  40. */
  41. private int index = 0;
  42. internal uint[] engineState = new uint[StateSize]; // state
  43. internal uint[] x = new uint[StateSize]; // internal buffer
  44. private byte[] keyStream = new byte[StateSize * 4]; // expanded state, 64 bytes
  45. private bool initialised = false;
  46. /*
  47. * internal counter
  48. */
  49. private uint cW0, cW1, cW2;
  50. /// <summary>
  51. /// Creates a 20 round Salsa20 engine.
  52. /// </summary>
  53. public Salsa20Engine()
  54. : this(DEFAULT_ROUNDS)
  55. {
  56. }
  57. /// <summary>
  58. /// Creates a Salsa20 engine with a specific number of rounds.
  59. /// </summary>
  60. /// <param name="rounds">the number of rounds (must be an even number).</param>
  61. public Salsa20Engine(int rounds)
  62. {
  63. if (rounds <= 0 || (rounds & 1) != 0)
  64. {
  65. throw new ArgumentException("'rounds' must be a positive, even number");
  66. }
  67. this.rounds = rounds;
  68. }
  69. public virtual void Init(
  70. bool forEncryption,
  71. ICipherParameters parameters)
  72. {
  73. /*
  74. * Salsa20 encryption and decryption is completely
  75. * symmetrical, so the 'forEncryption' is
  76. * irrelevant. (Like 90% of stream ciphers)
  77. */
  78. ParametersWithIV ivParams = parameters as ParametersWithIV;
  79. if (ivParams == null)
  80. throw new ArgumentException(AlgorithmName + " Init requires an IV", "parameters");
  81. byte[] iv = ivParams.GetIV();
  82. if (iv == null || iv.Length != NonceSize)
  83. throw new ArgumentException(AlgorithmName + " requires exactly " + NonceSize + " bytes of IV");
  84. ICipherParameters keyParam = ivParams.Parameters;
  85. if (keyParam == null)
  86. {
  87. if (!initialised)
  88. throw new InvalidOperationException(AlgorithmName + " KeyParameter can not be null for first initialisation");
  89. SetKey(null, iv);
  90. }
  91. else if (keyParam is KeyParameter)
  92. {
  93. SetKey(((KeyParameter)keyParam).GetKey(), iv);
  94. }
  95. else
  96. {
  97. throw new ArgumentException(AlgorithmName + " Init parameters must contain a KeyParameter (or null for re-init)");
  98. }
  99. Reset();
  100. initialised = true;
  101. }
  102. protected virtual int NonceSize
  103. {
  104. get { return 8; }
  105. }
  106. public virtual string AlgorithmName
  107. {
  108. get
  109. {
  110. string name = "Salsa20";
  111. if (rounds != DEFAULT_ROUNDS)
  112. {
  113. name += "/" + rounds;
  114. }
  115. return name;
  116. }
  117. }
  118. public virtual byte ReturnByte(
  119. byte input)
  120. {
  121. if (LimitExceeded())
  122. {
  123. throw new MaxBytesExceededException("2^70 byte limit per IV; Change IV");
  124. }
  125. if (index == 0)
  126. {
  127. GenerateKeyStream(keyStream);
  128. AdvanceCounter();
  129. }
  130. byte output = (byte)(keyStream[index] ^ input);
  131. index = (index + 1) & 63;
  132. return output;
  133. }
  134. protected virtual void AdvanceCounter()
  135. {
  136. if (++engineState[8] == 0)
  137. {
  138. ++engineState[9];
  139. }
  140. }
  141. public virtual void ProcessBytes(
  142. byte[] inBytes,
  143. int inOff,
  144. int len,
  145. byte[] outBytes,
  146. int outOff)
  147. {
  148. if (!initialised)
  149. throw new InvalidOperationException(AlgorithmName + " not initialised");
  150. Check.DataLength(inBytes, inOff, len, "input buffer too short");
  151. Check.OutputLength(outBytes, outOff, len, "output buffer too short");
  152. if (LimitExceeded((uint)len))
  153. throw new MaxBytesExceededException("2^70 byte limit per IV would be exceeded; Change IV");
  154. for (int i = 0; i < len; i++)
  155. {
  156. if (index == 0)
  157. {
  158. GenerateKeyStream(keyStream);
  159. AdvanceCounter();
  160. }
  161. outBytes[i+outOff] = (byte)(keyStream[index]^inBytes[i+inOff]);
  162. index = (index + 1) & 63;
  163. }
  164. }
  165. public virtual void Reset()
  166. {
  167. index = 0;
  168. ResetLimitCounter();
  169. ResetCounter();
  170. }
  171. protected virtual void ResetCounter()
  172. {
  173. engineState[8] = engineState[9] = 0;
  174. }
  175. protected virtual void SetKey(byte[] keyBytes, byte[] ivBytes)
  176. {
  177. if (keyBytes != null)
  178. {
  179. if ((keyBytes.Length != 16) && (keyBytes.Length != 32))
  180. throw new ArgumentException(AlgorithmName + " requires 128 bit or 256 bit key");
  181. int tsOff = (keyBytes.Length - 16) / 4;
  182. engineState[0] = TAU_SIGMA[tsOff];
  183. engineState[5] = TAU_SIGMA[tsOff + 1];
  184. engineState[10] = TAU_SIGMA[tsOff + 2];
  185. engineState[15] = TAU_SIGMA[tsOff + 3];
  186. // Key
  187. Pack.LE_To_UInt32(keyBytes, 0, engineState, 1, 4);
  188. Pack.LE_To_UInt32(keyBytes, keyBytes.Length - 16, engineState, 11, 4);
  189. }
  190. // IV
  191. Pack.LE_To_UInt32(ivBytes, 0, engineState, 6, 2);
  192. }
  193. protected virtual void GenerateKeyStream(byte[] output)
  194. {
  195. SalsaCore(rounds, engineState, x);
  196. Pack.UInt32_To_LE(x, output, 0);
  197. }
  198. internal static void SalsaCore(int rounds, uint[] input, uint[] x)
  199. {
  200. if (input.Length != 16)
  201. throw new ArgumentException();
  202. if (x.Length != 16)
  203. throw new ArgumentException();
  204. if (rounds % 2 != 0)
  205. throw new ArgumentException("Number of rounds must be even");
  206. uint x00 = input[ 0];
  207. uint x01 = input[ 1];
  208. uint x02 = input[ 2];
  209. uint x03 = input[ 3];
  210. uint x04 = input[ 4];
  211. uint x05 = input[ 5];
  212. uint x06 = input[ 6];
  213. uint x07 = input[ 7];
  214. uint x08 = input[ 8];
  215. uint x09 = input[ 9];
  216. uint x10 = input[10];
  217. uint x11 = input[11];
  218. uint x12 = input[12];
  219. uint x13 = input[13];
  220. uint x14 = input[14];
  221. uint x15 = input[15];
  222. for (int i = rounds; i > 0; i -= 2)
  223. {
  224. x04 ^= Integers.RotateLeft((x00+x12), 7);
  225. x08 ^= Integers.RotateLeft((x04+x00), 9);
  226. x12 ^= Integers.RotateLeft((x08+x04),13);
  227. x00 ^= Integers.RotateLeft((x12+x08),18);
  228. x09 ^= Integers.RotateLeft((x05+x01), 7);
  229. x13 ^= Integers.RotateLeft((x09+x05), 9);
  230. x01 ^= Integers.RotateLeft((x13+x09),13);
  231. x05 ^= Integers.RotateLeft((x01+x13),18);
  232. x14 ^= Integers.RotateLeft((x10+x06), 7);
  233. x02 ^= Integers.RotateLeft((x14+x10), 9);
  234. x06 ^= Integers.RotateLeft((x02+x14),13);
  235. x10 ^= Integers.RotateLeft((x06+x02),18);
  236. x03 ^= Integers.RotateLeft((x15+x11), 7);
  237. x07 ^= Integers.RotateLeft((x03+x15), 9);
  238. x11 ^= Integers.RotateLeft((x07+x03),13);
  239. x15 ^= Integers.RotateLeft((x11+x07),18);
  240. x01 ^= Integers.RotateLeft((x00+x03), 7);
  241. x02 ^= Integers.RotateLeft((x01+x00), 9);
  242. x03 ^= Integers.RotateLeft((x02+x01),13);
  243. x00 ^= Integers.RotateLeft((x03+x02),18);
  244. x06 ^= Integers.RotateLeft((x05+x04), 7);
  245. x07 ^= Integers.RotateLeft((x06+x05), 9);
  246. x04 ^= Integers.RotateLeft((x07+x06),13);
  247. x05 ^= Integers.RotateLeft((x04+x07),18);
  248. x11 ^= Integers.RotateLeft((x10+x09), 7);
  249. x08 ^= Integers.RotateLeft((x11+x10), 9);
  250. x09 ^= Integers.RotateLeft((x08+x11),13);
  251. x10 ^= Integers.RotateLeft((x09+x08),18);
  252. x12 ^= Integers.RotateLeft((x15+x14), 7);
  253. x13 ^= Integers.RotateLeft((x12+x15), 9);
  254. x14 ^= Integers.RotateLeft((x13+x12),13);
  255. x15 ^= Integers.RotateLeft((x14+x13),18);
  256. }
  257. x[ 0] = x00 + input[ 0];
  258. x[ 1] = x01 + input[ 1];
  259. x[ 2] = x02 + input[ 2];
  260. x[ 3] = x03 + input[ 3];
  261. x[ 4] = x04 + input[ 4];
  262. x[ 5] = x05 + input[ 5];
  263. x[ 6] = x06 + input[ 6];
  264. x[ 7] = x07 + input[ 7];
  265. x[ 8] = x08 + input[ 8];
  266. x[ 9] = x09 + input[ 9];
  267. x[10] = x10 + input[10];
  268. x[11] = x11 + input[11];
  269. x[12] = x12 + input[12];
  270. x[13] = x13 + input[13];
  271. x[14] = x14 + input[14];
  272. x[15] = x15 + input[15];
  273. }
  274. private void ResetLimitCounter()
  275. {
  276. cW0 = 0;
  277. cW1 = 0;
  278. cW2 = 0;
  279. }
  280. private bool LimitExceeded()
  281. {
  282. if (++cW0 == 0)
  283. {
  284. if (++cW1 == 0)
  285. {
  286. return (++cW2 & 0x20) != 0; // 2^(32 + 32 + 6)
  287. }
  288. }
  289. return false;
  290. }
  291. /*
  292. * this relies on the fact len will always be positive.
  293. */
  294. private bool LimitExceeded(
  295. uint len)
  296. {
  297. uint old = cW0;
  298. cW0 += len;
  299. if (cW0 < old)
  300. {
  301. if (++cW1 == 0)
  302. {
  303. return (++cW2 & 0x20) != 0; // 2^(32 + 32 + 6)
  304. }
  305. }
  306. return false;
  307. }
  308. }
  309. }
  310. #pragma warning restore
  311. #endif