Salsa20Engine.cs 9.0 KB

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