FastSalsa20Engine.cs 12 KB

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