ChaCha20Poly1305.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
  10. {
  11. public class ChaCha20Poly1305
  12. : IAeadCipher
  13. {
  14. private enum State
  15. {
  16. Uninitialized = 0,
  17. EncInit = 1,
  18. EncAad = 2,
  19. EncData = 3,
  20. EncFinal = 4,
  21. DecInit = 5,
  22. DecAad = 6,
  23. DecData = 7,
  24. DecFinal = 8,
  25. }
  26. private const int BufSize = 64;
  27. private const int KeySize = 32;
  28. private const int NonceSize = 12;
  29. private const int MacSize = 16;
  30. private static readonly byte[] Zeroes = new byte[MacSize - 1];
  31. private const ulong AadLimit = ulong.MaxValue;
  32. private const ulong DataLimit = ((1UL << 32) - 1) * 64;
  33. private readonly ChaCha7539Engine mChacha20;
  34. private readonly IMac mPoly1305;
  35. private readonly byte[] mKey = new byte[KeySize];
  36. private readonly byte[] mNonce = new byte[NonceSize];
  37. private readonly byte[] mBuf = new byte[BufSize + MacSize];
  38. private readonly byte[] mMac = new byte[MacSize];
  39. private byte[] mInitialAad;
  40. private ulong mAadCount;
  41. private ulong mDataCount;
  42. private State mState = State.Uninitialized;
  43. private int mBufPos;
  44. public ChaCha20Poly1305()
  45. : this(new Poly1305())
  46. {
  47. }
  48. public ChaCha20Poly1305(IMac poly1305)
  49. {
  50. if (null == poly1305)
  51. throw new ArgumentNullException("poly1305");
  52. if (MacSize != poly1305.GetMacSize())
  53. throw new ArgumentException("must be a 128-bit MAC", "poly1305");
  54. this.mChacha20 = new ChaCha7539Engine();
  55. this.mPoly1305 = poly1305;
  56. }
  57. public virtual string AlgorithmName
  58. {
  59. get { return "ChaCha20Poly1305"; }
  60. }
  61. public virtual void Init(bool forEncryption, ICipherParameters parameters)
  62. {
  63. KeyParameter initKeyParam;
  64. byte[] initNonce;
  65. ICipherParameters chacha20Params;
  66. if (parameters is AeadParameters)
  67. {
  68. AeadParameters aeadParams = (AeadParameters)parameters;
  69. int macSizeBits = aeadParams.MacSize;
  70. if ((MacSize * 8) != macSizeBits)
  71. throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
  72. initKeyParam = aeadParams.Key;
  73. initNonce = aeadParams.GetNonce();
  74. chacha20Params = new ParametersWithIV(initKeyParam, initNonce);
  75. this.mInitialAad = aeadParams.GetAssociatedText();
  76. }
  77. else if (parameters is ParametersWithIV)
  78. {
  79. ParametersWithIV ivParams = (ParametersWithIV)parameters;
  80. initKeyParam = (KeyParameter)ivParams.Parameters;
  81. initNonce = ivParams.GetIV();
  82. chacha20Params = ivParams;
  83. this.mInitialAad = null;
  84. }
  85. else
  86. {
  87. throw new ArgumentException("invalid parameters passed to ChaCha20Poly1305", "parameters");
  88. }
  89. // Validate key
  90. if (null == initKeyParam)
  91. {
  92. if (State.Uninitialized == mState)
  93. throw new ArgumentException("Key must be specified in initial init");
  94. }
  95. else
  96. {
  97. if (KeySize != initKeyParam.GetKey().Length)
  98. throw new ArgumentException("Key must be 256 bits");
  99. }
  100. // Validate nonce
  101. if (null == initNonce || NonceSize != initNonce.Length)
  102. throw new ArgumentException("Nonce must be 96 bits");
  103. // Check for encryption with reused nonce
  104. if (State.Uninitialized != mState && forEncryption && Arrays.AreEqual(mNonce, initNonce))
  105. {
  106. if (null == initKeyParam || Arrays.AreEqual(mKey, initKeyParam.GetKey()))
  107. throw new ArgumentException("cannot reuse nonce for ChaCha20Poly1305 encryption");
  108. }
  109. if (null != initKeyParam)
  110. {
  111. Array.Copy(initKeyParam.GetKey(), 0, mKey, 0, KeySize);
  112. }
  113. Array.Copy(initNonce, 0, mNonce, 0, NonceSize);
  114. mChacha20.Init(true, chacha20Params);
  115. this.mState = forEncryption ? State.EncInit : State.DecInit;
  116. Reset(true, false);
  117. }
  118. public virtual int GetOutputSize(int len)
  119. {
  120. int total = System.Math.Max(0, len) + mBufPos;
  121. switch (mState)
  122. {
  123. case State.DecInit:
  124. case State.DecAad:
  125. case State.DecData:
  126. return System.Math.Max(0, total - MacSize);
  127. case State.EncInit:
  128. case State.EncAad:
  129. case State.EncData:
  130. return total + MacSize;
  131. default:
  132. throw new InvalidOperationException();
  133. }
  134. }
  135. public virtual int GetUpdateOutputSize(int len)
  136. {
  137. int total = System.Math.Max(0, len) + mBufPos;
  138. switch (mState)
  139. {
  140. case State.DecInit:
  141. case State.DecAad:
  142. case State.DecData:
  143. total = System.Math.Max(0, total - MacSize);
  144. break;
  145. case State.EncInit:
  146. case State.EncAad:
  147. case State.EncData:
  148. break;
  149. default:
  150. throw new InvalidOperationException();
  151. }
  152. return total - (total % BufSize);
  153. }
  154. public virtual void ProcessAadByte(byte input)
  155. {
  156. CheckAad();
  157. this.mAadCount = IncrementCount(mAadCount, 1, AadLimit);
  158. mPoly1305.Update(input);
  159. }
  160. public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
  161. {
  162. if (null == inBytes)
  163. throw new ArgumentNullException("inBytes");
  164. if (inOff < 0)
  165. throw new ArgumentException("cannot be negative", "inOff");
  166. if (len < 0)
  167. throw new ArgumentException("cannot be negative", "len");
  168. Check.DataLength(inBytes, inOff, len, "input buffer too short");
  169. CheckAad();
  170. if (len > 0)
  171. {
  172. this.mAadCount = IncrementCount(mAadCount, (uint)len, AadLimit);
  173. mPoly1305.BlockUpdate(inBytes, inOff, len);
  174. }
  175. }
  176. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  177. public virtual void ProcessAadBytes(ReadOnlySpan<byte> input)
  178. {
  179. CheckAad();
  180. if (!input.IsEmpty)
  181. {
  182. this.mAadCount = IncrementCount(mAadCount, (uint)input.Length, AadLimit);
  183. mPoly1305.BlockUpdate(input);
  184. }
  185. }
  186. #endif
  187. public virtual int ProcessByte(byte input, byte[] outBytes, int outOff)
  188. {
  189. CheckData();
  190. switch (mState)
  191. {
  192. case State.DecData:
  193. {
  194. mBuf[mBufPos] = input;
  195. if (++mBufPos == mBuf.Length)
  196. {
  197. mPoly1305.BlockUpdate(mBuf, 0, BufSize);
  198. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  199. ProcessBlock(mBuf, outBytes.AsSpan(outOff));
  200. #else
  201. ProcessBlock(mBuf, 0, outBytes, outOff);
  202. #endif
  203. Array.Copy(mBuf, BufSize, mBuf, 0, MacSize);
  204. this.mBufPos = MacSize;
  205. return BufSize;
  206. }
  207. return 0;
  208. }
  209. case State.EncData:
  210. {
  211. mBuf[mBufPos] = input;
  212. if (++mBufPos == BufSize)
  213. {
  214. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  215. ProcessBlock(mBuf, outBytes.AsSpan(outOff));
  216. #else
  217. ProcessBlock(mBuf, 0, outBytes, outOff);
  218. #endif
  219. mPoly1305.BlockUpdate(outBytes, outOff, BufSize);
  220. this.mBufPos = 0;
  221. return BufSize;
  222. }
  223. return 0;
  224. }
  225. default:
  226. throw new InvalidOperationException();
  227. }
  228. }
  229. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  230. public virtual int ProcessByte(byte input, Span<byte> output)
  231. {
  232. CheckData();
  233. switch (mState)
  234. {
  235. case State.DecData:
  236. {
  237. mBuf[mBufPos] = input;
  238. if (++mBufPos == mBuf.Length)
  239. {
  240. mPoly1305.BlockUpdate(mBuf.AsSpan(0, BufSize));
  241. ProcessBlock(mBuf, output);
  242. Array.Copy(mBuf, BufSize, mBuf, 0, MacSize);
  243. this.mBufPos = MacSize;
  244. return BufSize;
  245. }
  246. return 0;
  247. }
  248. case State.EncData:
  249. {
  250. mBuf[mBufPos] = input;
  251. if (++mBufPos == BufSize)
  252. {
  253. ProcessBlock(mBuf, output);
  254. mPoly1305.BlockUpdate(output[..BufSize]);
  255. this.mBufPos = 0;
  256. return BufSize;
  257. }
  258. return 0;
  259. }
  260. default:
  261. throw new InvalidOperationException();
  262. }
  263. }
  264. #endif
  265. public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff)
  266. {
  267. if (null == inBytes)
  268. throw new ArgumentNullException("inBytes");
  269. /*
  270. * Following bc-java, we allow null when no output is expected (e.g. based on a
  271. * GetUpdateOutputSize call).
  272. */
  273. if (null == outBytes)
  274. {
  275. //throw new ArgumentNullException("outBytes");
  276. }
  277. if (inOff < 0)
  278. throw new ArgumentException("cannot be negative", "inOff");
  279. if (len < 0)
  280. throw new ArgumentException("cannot be negative", "len");
  281. Check.DataLength(inBytes, inOff, len, "input buffer too short");
  282. if (outOff < 0)
  283. throw new ArgumentException("cannot be negative", "outOff");
  284. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  285. return ProcessBytes(inBytes.AsSpan(inOff, len), Spans.FromNullable(outBytes, outOff));
  286. #else
  287. CheckData();
  288. int resultLen = 0;
  289. switch (mState)
  290. {
  291. case State.DecData:
  292. {
  293. int available = mBuf.Length - mBufPos;
  294. if (len < available)
  295. {
  296. Array.Copy(inBytes, inOff, mBuf, mBufPos, len);
  297. mBufPos += len;
  298. break;
  299. }
  300. if (mBufPos >= BufSize)
  301. {
  302. mPoly1305.BlockUpdate(mBuf, 0, BufSize);
  303. ProcessBlock(mBuf, 0, outBytes, outOff);
  304. Array.Copy(mBuf, BufSize, mBuf, 0, mBufPos -= BufSize);
  305. resultLen = BufSize;
  306. available += BufSize;
  307. if (len < available)
  308. {
  309. Array.Copy(inBytes, inOff, mBuf, mBufPos, len);
  310. mBufPos += len;
  311. break;
  312. }
  313. }
  314. int inLimit1 = inOff + len - mBuf.Length;
  315. int inLimit2 = inLimit1 - BufSize;
  316. available = BufSize - mBufPos;
  317. Array.Copy(inBytes, inOff, mBuf, mBufPos, available);
  318. mPoly1305.BlockUpdate(mBuf, 0, BufSize);
  319. ProcessBlock(mBuf, 0, outBytes, outOff + resultLen);
  320. inOff += available;
  321. resultLen += BufSize;
  322. while (inOff <= inLimit2)
  323. {
  324. mPoly1305.BlockUpdate(inBytes, inOff, BufSize * 2);
  325. ProcessBlocks2(inBytes, inOff, outBytes, outOff + resultLen);
  326. inOff += BufSize * 2;
  327. resultLen += BufSize * 2;
  328. }
  329. if (inOff <= inLimit1)
  330. {
  331. mPoly1305.BlockUpdate(inBytes, inOff, BufSize);
  332. ProcessBlock(inBytes, inOff, outBytes, outOff + resultLen);
  333. inOff += BufSize;
  334. resultLen += BufSize;
  335. }
  336. mBufPos = mBuf.Length + inLimit1 - inOff;
  337. Array.Copy(inBytes, inOff, mBuf, 0, mBufPos);
  338. break;
  339. }
  340. case State.EncData:
  341. {
  342. int available = BufSize - mBufPos;
  343. if (len < available)
  344. {
  345. Array.Copy(inBytes, inOff, mBuf, mBufPos, len);
  346. mBufPos += len;
  347. break;
  348. }
  349. int inLimit1 = inOff + len - BufSize;
  350. int inLimit2 = inLimit1 - BufSize;
  351. if (mBufPos > 0)
  352. {
  353. Array.Copy(inBytes, inOff, mBuf, mBufPos, available);
  354. ProcessBlock(mBuf, 0, outBytes, outOff);
  355. inOff += available;
  356. resultLen = BufSize;
  357. }
  358. while (inOff <= inLimit2)
  359. {
  360. ProcessBlocks2(inBytes, inOff, outBytes, outOff + resultLen);
  361. inOff += BufSize * 2;
  362. resultLen += BufSize * 2;
  363. }
  364. if (inOff <= inLimit1)
  365. {
  366. ProcessBlock(inBytes, inOff, outBytes, outOff + resultLen);
  367. inOff += BufSize;
  368. resultLen += BufSize;
  369. }
  370. mPoly1305.BlockUpdate(outBytes, outOff, resultLen);
  371. mBufPos = BufSize + inLimit1 - inOff;
  372. Array.Copy(inBytes, inOff, mBuf, 0, mBufPos);
  373. break;
  374. }
  375. default:
  376. throw new InvalidOperationException();
  377. }
  378. return resultLen;
  379. #endif
  380. }
  381. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  382. public virtual int ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
  383. {
  384. CheckData();
  385. int resultLen = 0;
  386. switch (mState)
  387. {
  388. case State.DecData:
  389. {
  390. int available = mBuf.Length - mBufPos;
  391. if (input.Length < available)
  392. {
  393. input.CopyTo(mBuf.AsSpan(mBufPos));
  394. mBufPos += input.Length;
  395. break;
  396. }
  397. if (mBufPos >= BufSize)
  398. {
  399. mPoly1305.BlockUpdate(mBuf.AsSpan(0, BufSize));
  400. ProcessBlock(mBuf, output);
  401. Array.Copy(mBuf, BufSize, mBuf, 0, mBufPos -= BufSize);
  402. resultLen = BufSize;
  403. available += BufSize;
  404. if (input.Length < available)
  405. {
  406. input.CopyTo(mBuf.AsSpan(mBufPos));
  407. mBufPos += input.Length;
  408. break;
  409. }
  410. }
  411. int inLimit1 = mBuf.Length;
  412. int inLimit2 = inLimit1 + BufSize;
  413. available = BufSize - mBufPos;
  414. input[..available].CopyTo(mBuf.AsSpan(mBufPos));
  415. mPoly1305.BlockUpdate(mBuf.AsSpan(0, BufSize));
  416. ProcessBlock(mBuf, output[resultLen..]);
  417. input = input[available..];
  418. resultLen += BufSize;
  419. while (input.Length >= inLimit2)
  420. {
  421. mPoly1305.BlockUpdate(input[..(BufSize * 2)]);
  422. ProcessBlocks2(input, output[resultLen..]);
  423. input = input[(BufSize * 2)..];
  424. resultLen += BufSize * 2;
  425. }
  426. if (input.Length >= inLimit1)
  427. {
  428. mPoly1305.BlockUpdate(input[..BufSize]);
  429. ProcessBlock(input, output[resultLen..]);
  430. input = input[BufSize..];
  431. resultLen += BufSize;
  432. }
  433. mBufPos = input.Length;
  434. input.CopyTo(mBuf);
  435. break;
  436. }
  437. case State.EncData:
  438. {
  439. int available = BufSize - mBufPos;
  440. if (input.Length < available)
  441. {
  442. input.CopyTo(mBuf.AsSpan(mBufPos));
  443. mBufPos += input.Length;
  444. break;
  445. }
  446. if (mBufPos > 0)
  447. {
  448. input[..available].CopyTo(mBuf.AsSpan(mBufPos));
  449. ProcessBlock(mBuf, output);
  450. input = input[available..];
  451. resultLen = BufSize;
  452. }
  453. while (input.Length >= BufSize * 2)
  454. {
  455. ProcessBlocks2(input, output[resultLen..]);
  456. input = input[(BufSize * 2)..];
  457. resultLen += BufSize * 2;
  458. }
  459. if (input.Length >= BufSize)
  460. {
  461. ProcessBlock(input, output[resultLen..]);
  462. input = input[BufSize..];
  463. resultLen += BufSize;
  464. }
  465. mPoly1305.BlockUpdate(output[..resultLen]);
  466. mBufPos = input.Length;
  467. input.CopyTo(mBuf);
  468. break;
  469. }
  470. default:
  471. throw new InvalidOperationException();
  472. }
  473. return resultLen;
  474. }
  475. #endif
  476. public virtual int DoFinal(byte[] outBytes, int outOff)
  477. {
  478. if (null == outBytes)
  479. throw new ArgumentNullException("outBytes");
  480. if (outOff < 0)
  481. throw new ArgumentException("cannot be negative", "outOff");
  482. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  483. return DoFinal(outBytes.AsSpan(outOff));
  484. #else
  485. CheckData();
  486. Array.Clear(mMac, 0, MacSize);
  487. int resultLen = 0;
  488. switch (mState)
  489. {
  490. case State.DecData:
  491. {
  492. if (mBufPos < MacSize)
  493. throw new InvalidCipherTextException("data too short");
  494. resultLen = mBufPos - MacSize;
  495. Check.OutputLength(outBytes, outOff, resultLen, "output buffer too short");
  496. if (resultLen > 0)
  497. {
  498. mPoly1305.BlockUpdate(mBuf, 0, resultLen);
  499. ProcessData(mBuf, 0, resultLen, outBytes, outOff);
  500. }
  501. FinishData(State.DecFinal);
  502. if (!Arrays.ConstantTimeAreEqual(MacSize, mMac, 0, mBuf, resultLen))
  503. throw new InvalidCipherTextException("mac check in ChaCha20Poly1305 failed");
  504. break;
  505. }
  506. case State.EncData:
  507. {
  508. resultLen = mBufPos + MacSize;
  509. Check.OutputLength(outBytes, outOff, resultLen, "output buffer too short");
  510. if (mBufPos > 0)
  511. {
  512. ProcessData(mBuf, 0, mBufPos, outBytes, outOff);
  513. mPoly1305.BlockUpdate(outBytes, outOff, mBufPos);
  514. }
  515. FinishData(State.EncFinal);
  516. Array.Copy(mMac, 0, outBytes, outOff + mBufPos, MacSize);
  517. break;
  518. }
  519. default:
  520. throw new InvalidOperationException();
  521. }
  522. Reset(false, true);
  523. return resultLen;
  524. #endif
  525. }
  526. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  527. public virtual int DoFinal(Span<byte> output)
  528. {
  529. CheckData();
  530. Array.Clear(mMac, 0, MacSize);
  531. int resultLen = 0;
  532. switch (mState)
  533. {
  534. case State.DecData:
  535. {
  536. if (mBufPos < MacSize)
  537. throw new InvalidCipherTextException("data too short");
  538. resultLen = mBufPos - MacSize;
  539. Check.OutputLength(output, resultLen, "output buffer too short");
  540. if (resultLen > 0)
  541. {
  542. mPoly1305.BlockUpdate(mBuf, 0, resultLen);
  543. ProcessData(mBuf.AsSpan(0, resultLen), output);
  544. }
  545. FinishData(State.DecFinal);
  546. if (!Arrays.ConstantTimeAreEqual(MacSize, mMac, 0, mBuf, resultLen))
  547. throw new InvalidCipherTextException("mac check in ChaCha20Poly1305 failed");
  548. break;
  549. }
  550. case State.EncData:
  551. {
  552. resultLen = mBufPos + MacSize;
  553. Check.OutputLength(output, resultLen, "output buffer too short");
  554. if (mBufPos > 0)
  555. {
  556. ProcessData(mBuf.AsSpan(0, mBufPos), output);
  557. mPoly1305.BlockUpdate(output[..mBufPos]);
  558. }
  559. FinishData(State.EncFinal);
  560. mMac.AsSpan(0, MacSize).CopyTo(output[mBufPos..]);
  561. break;
  562. }
  563. default:
  564. throw new InvalidOperationException();
  565. }
  566. Reset(false, true);
  567. return resultLen;
  568. }
  569. #endif
  570. public virtual byte[] GetMac()
  571. {
  572. return Arrays.Clone(mMac);
  573. }
  574. public virtual void Reset()
  575. {
  576. Reset(true, true);
  577. }
  578. private void CheckAad()
  579. {
  580. switch (mState)
  581. {
  582. case State.DecInit:
  583. this.mState = State.DecAad;
  584. break;
  585. case State.EncInit:
  586. this.mState = State.EncAad;
  587. break;
  588. case State.DecAad:
  589. case State.EncAad:
  590. break;
  591. case State.EncFinal:
  592. throw new InvalidOperationException("ChaCha20Poly1305 cannot be reused for encryption");
  593. default:
  594. throw new InvalidOperationException();
  595. }
  596. }
  597. private void CheckData()
  598. {
  599. switch (mState)
  600. {
  601. case State.DecInit:
  602. case State.DecAad:
  603. FinishAad(State.DecData);
  604. break;
  605. case State.EncInit:
  606. case State.EncAad:
  607. FinishAad(State.EncData);
  608. break;
  609. case State.DecData:
  610. case State.EncData:
  611. break;
  612. case State.EncFinal:
  613. throw new InvalidOperationException("ChaCha20Poly1305 cannot be reused for encryption");
  614. default:
  615. throw new InvalidOperationException();
  616. }
  617. }
  618. private void FinishAad(State nextState)
  619. {
  620. PadMac(mAadCount);
  621. this.mState = nextState;
  622. }
  623. private void FinishData(State nextState)
  624. {
  625. PadMac(mDataCount);
  626. byte[] lengths = new byte[16];
  627. Pack.UInt64_To_LE(mAadCount, lengths, 0);
  628. Pack.UInt64_To_LE(mDataCount, lengths, 8);
  629. mPoly1305.BlockUpdate(lengths, 0, 16);
  630. mPoly1305.DoFinal(mMac, 0);
  631. this.mState = nextState;
  632. }
  633. private ulong IncrementCount(ulong count, uint increment, ulong limit)
  634. {
  635. if (count > (limit - increment))
  636. throw new InvalidOperationException ("Limit exceeded");
  637. return count + increment;
  638. }
  639. private void InitMac()
  640. {
  641. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  642. Span<byte> firstBlock = stackalloc byte[64];
  643. try
  644. {
  645. mChacha20.ProcessBytes(firstBlock, firstBlock);
  646. mPoly1305.Init(new KeyParameter(firstBlock[..32]));
  647. }
  648. finally
  649. {
  650. firstBlock.Fill(0x00);
  651. }
  652. #else
  653. byte[] firstBlock = new byte[64];
  654. try
  655. {
  656. mChacha20.ProcessBytes(firstBlock, 0, 64, firstBlock, 0);
  657. mPoly1305.Init(new KeyParameter(firstBlock, 0, 32));
  658. }
  659. finally
  660. {
  661. Array.Clear(firstBlock, 0, 64);
  662. }
  663. #endif
  664. }
  665. private void PadMac(ulong count)
  666. {
  667. int partial = (int)count & (MacSize - 1);
  668. if (0 != partial)
  669. {
  670. mPoly1305.BlockUpdate(Zeroes, 0, MacSize - partial);
  671. }
  672. }
  673. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  674. private void ProcessBlock(ReadOnlySpan<byte> input, Span<byte> output)
  675. {
  676. Check.OutputLength(output, 64, "output buffer too short");
  677. mChacha20.ProcessBlock(input, output);
  678. this.mDataCount = IncrementCount(mDataCount, 64U, DataLimit);
  679. }
  680. private void ProcessBlocks2(ReadOnlySpan<byte> input, Span<byte> output)
  681. {
  682. Check.OutputLength(output, 128, "output buffer too short");
  683. mChacha20.ProcessBlocks2(input, output);
  684. this.mDataCount = IncrementCount(mDataCount, 128U, DataLimit);
  685. }
  686. private void ProcessData(ReadOnlySpan<byte> input, Span<byte> output)
  687. {
  688. Check.OutputLength(output, input.Length, "output buffer too short");
  689. mChacha20.ProcessBytes(input, output);
  690. this.mDataCount = IncrementCount(mDataCount, (uint)input.Length, DataLimit);
  691. }
  692. #else
  693. private void ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff)
  694. {
  695. Check.OutputLength(outBytes, outOff, 64, "output buffer too short");
  696. mChacha20.ProcessBlock(inBytes, inOff, outBytes, outOff);
  697. this.mDataCount = IncrementCount(mDataCount, 64U, DataLimit);
  698. }
  699. private void ProcessBlocks2(byte[] inBytes, int inOff, byte[] outBytes, int outOff)
  700. {
  701. Check.OutputLength(outBytes, outOff, 128, "output buffer too short");
  702. mChacha20.ProcessBlocks2(inBytes, inOff, outBytes, outOff);
  703. this.mDataCount = IncrementCount(mDataCount, 128U, DataLimit);
  704. }
  705. private void ProcessData(byte[] inBytes, int inOff, int inLen, byte[] outBytes, int outOff)
  706. {
  707. Check.OutputLength(outBytes, outOff, inLen, "output buffer too short");
  708. mChacha20.ProcessBytes(inBytes, inOff, inLen, outBytes, outOff);
  709. this.mDataCount = IncrementCount(mDataCount, (uint)inLen, DataLimit);
  710. }
  711. #endif
  712. private void Reset(bool clearMac, bool resetCipher)
  713. {
  714. Array.Clear(mBuf, 0, mBuf.Length);
  715. if (clearMac)
  716. {
  717. Array.Clear(mMac, 0, mMac.Length);
  718. }
  719. this.mAadCount = 0UL;
  720. this.mDataCount = 0UL;
  721. this.mBufPos = 0;
  722. switch (mState)
  723. {
  724. case State.DecInit:
  725. case State.EncInit:
  726. break;
  727. case State.DecAad:
  728. case State.DecData:
  729. case State.DecFinal:
  730. this.mState = State.DecInit;
  731. break;
  732. case State.EncAad:
  733. case State.EncData:
  734. case State.EncFinal:
  735. this.mState = State.EncFinal;
  736. return;
  737. default:
  738. throw new InvalidOperationException();
  739. }
  740. if (resetCipher)
  741. {
  742. mChacha20.Reset();
  743. }
  744. InitMac();
  745. if (null != mInitialAad)
  746. {
  747. ProcessAadBytes(mInitialAad, 0, mInitialAad.Length);
  748. }
  749. }
  750. }
  751. }
  752. #pragma warning restore
  753. #endif