Salsa20Engine.cs 8.9 KB

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