ChaCha20Poly1305.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
  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.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. public virtual int ProcessByte(byte input, byte[] outBytes, int outOff)
  177. {
  178. CheckData();
  179. switch (mState)
  180. {
  181. case State.DecData:
  182. {
  183. mBuf[mBufPos] = input;
  184. if (++mBufPos == mBuf.Length)
  185. {
  186. mPoly1305.BlockUpdate(mBuf, 0, BufSize);
  187. ProcessData(mBuf, 0, BufSize, outBytes, outOff);
  188. Array.Copy(mBuf, BufSize, mBuf, 0, MacSize);
  189. this.mBufPos = MacSize;
  190. return BufSize;
  191. }
  192. return 0;
  193. }
  194. case State.EncData:
  195. {
  196. mBuf[mBufPos] = input;
  197. if (++mBufPos == BufSize)
  198. {
  199. ProcessData(mBuf, 0, BufSize, outBytes, outOff);
  200. mPoly1305.BlockUpdate(outBytes, outOff, BufSize);
  201. this.mBufPos = 0;
  202. return BufSize;
  203. }
  204. return 0;
  205. }
  206. default:
  207. throw new InvalidOperationException();
  208. }
  209. }
  210. public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff)
  211. {
  212. if (null == inBytes)
  213. throw new ArgumentNullException("inBytes");
  214. /*
  215. * Following bc-java, we allow null when no output is expected (e.g. based on a
  216. * GetUpdateOutputSize call).
  217. */
  218. if (null == outBytes)
  219. {
  220. //throw new ArgumentNullException("outBytes");
  221. }
  222. if (inOff < 0)
  223. throw new ArgumentException("cannot be negative", "inOff");
  224. if (len < 0)
  225. throw new ArgumentException("cannot be negative", "len");
  226. Check.DataLength(inBytes, inOff, len, "input buffer too short");
  227. if (outOff < 0)
  228. throw new ArgumentException("cannot be negative", "outOff");
  229. CheckData();
  230. int resultLen = 0;
  231. switch (mState)
  232. {
  233. case State.DecData:
  234. {
  235. for (int i = 0; i < len; ++i)
  236. {
  237. mBuf[mBufPos] = inBytes[inOff + i];
  238. if (++mBufPos == mBuf.Length)
  239. {
  240. mPoly1305.BlockUpdate(mBuf, 0, BufSize);
  241. ProcessData(mBuf, 0, BufSize, outBytes, outOff + resultLen);
  242. Array.Copy(mBuf, BufSize, mBuf, 0, MacSize);
  243. this.mBufPos = MacSize;
  244. resultLen += BufSize;
  245. }
  246. }
  247. break;
  248. }
  249. case State.EncData:
  250. {
  251. if (mBufPos != 0)
  252. {
  253. while (len > 0)
  254. {
  255. --len;
  256. mBuf[mBufPos] = inBytes[inOff++];
  257. if (++mBufPos == BufSize)
  258. {
  259. ProcessData(mBuf, 0, BufSize, outBytes, outOff);
  260. mPoly1305.BlockUpdate(outBytes, outOff, BufSize);
  261. this.mBufPos = 0;
  262. resultLen = BufSize;
  263. break;
  264. }
  265. }
  266. }
  267. while (len >= BufSize)
  268. {
  269. ProcessData(inBytes, inOff, BufSize, outBytes, outOff + resultLen);
  270. mPoly1305.BlockUpdate(outBytes, outOff + resultLen, BufSize);
  271. inOff += BufSize;
  272. len -= BufSize;
  273. resultLen += BufSize;
  274. }
  275. if (len > 0)
  276. {
  277. Array.Copy(inBytes, inOff, mBuf, 0, len);
  278. this.mBufPos = len;
  279. }
  280. break;
  281. }
  282. default:
  283. throw new InvalidOperationException();
  284. }
  285. return resultLen;
  286. }
  287. public virtual int DoFinal(byte[] outBytes, int outOff)
  288. {
  289. if (null == outBytes)
  290. throw new ArgumentNullException("outBytes");
  291. if (outOff < 0)
  292. throw new ArgumentException("cannot be negative", "outOff");
  293. CheckData();
  294. Array.Clear(mMac, 0, MacSize);
  295. int resultLen = 0;
  296. switch (mState)
  297. {
  298. case State.DecData:
  299. {
  300. if (mBufPos < MacSize)
  301. throw new InvalidCipherTextException("data too short");
  302. resultLen = mBufPos - MacSize;
  303. Check.OutputLength(outBytes, outOff, resultLen, "output buffer too short");
  304. if (resultLen > 0)
  305. {
  306. mPoly1305.BlockUpdate(mBuf, 0, resultLen);
  307. ProcessData(mBuf, 0, resultLen, outBytes, outOff);
  308. }
  309. FinishData(State.DecFinal);
  310. if (!Arrays.ConstantTimeAreEqual(MacSize, mMac, 0, mBuf, resultLen))
  311. {
  312. throw new InvalidCipherTextException("mac check in ChaCha20Poly1305 failed");
  313. }
  314. break;
  315. }
  316. case State.EncData:
  317. {
  318. resultLen = mBufPos + MacSize;
  319. Check.OutputLength(outBytes, outOff, resultLen, "output buffer too short");
  320. if (mBufPos > 0)
  321. {
  322. ProcessData(mBuf, 0, mBufPos, outBytes, outOff);
  323. mPoly1305.BlockUpdate(outBytes, outOff, mBufPos);
  324. }
  325. FinishData(State.EncFinal);
  326. Array.Copy(mMac, 0, outBytes, outOff + mBufPos, MacSize);
  327. break;
  328. }
  329. default:
  330. throw new InvalidOperationException();
  331. }
  332. Reset(false, true);
  333. return resultLen;
  334. }
  335. public virtual byte[] GetMac()
  336. {
  337. return Arrays.Clone(mMac);
  338. }
  339. public virtual void Reset()
  340. {
  341. Reset(true, true);
  342. }
  343. private void CheckAad()
  344. {
  345. switch (mState)
  346. {
  347. case State.DecInit:
  348. this.mState = State.DecAad;
  349. break;
  350. case State.EncInit:
  351. this.mState = State.EncAad;
  352. break;
  353. case State.DecAad:
  354. case State.EncAad:
  355. break;
  356. case State.EncFinal:
  357. throw new InvalidOperationException("ChaCha20Poly1305 cannot be reused for encryption");
  358. default:
  359. throw new InvalidOperationException();
  360. }
  361. }
  362. private void CheckData()
  363. {
  364. switch (mState)
  365. {
  366. case State.DecInit:
  367. case State.DecAad:
  368. FinishAad(State.DecData);
  369. break;
  370. case State.EncInit:
  371. case State.EncAad:
  372. FinishAad(State.EncData);
  373. break;
  374. case State.DecData:
  375. case State.EncData:
  376. break;
  377. case State.EncFinal:
  378. throw new InvalidOperationException("ChaCha20Poly1305 cannot be reused for encryption");
  379. default:
  380. throw new InvalidOperationException();
  381. }
  382. }
  383. private void FinishAad(State nextState)
  384. {
  385. PadMac(mAadCount);
  386. this.mState = nextState;
  387. }
  388. private void FinishData(State nextState)
  389. {
  390. PadMac(mDataCount);
  391. byte[] lengths = new byte[16];
  392. Pack.UInt64_To_LE(mAadCount, lengths, 0);
  393. Pack.UInt64_To_LE(mDataCount, lengths, 8);
  394. mPoly1305.BlockUpdate(lengths, 0, 16);
  395. mPoly1305.DoFinal(mMac, 0);
  396. this.mState = nextState;
  397. }
  398. private ulong IncrementCount(ulong count, uint increment, ulong limit)
  399. {
  400. if (count > (limit - increment))
  401. throw new InvalidOperationException ("Limit exceeded");
  402. return count + increment;
  403. }
  404. private void InitMac()
  405. {
  406. byte[] firstBlock = new byte[64];
  407. try
  408. {
  409. mChacha20.ProcessBytes(firstBlock, 0, 64, firstBlock, 0);
  410. mPoly1305.Init(new KeyParameter(firstBlock, 0, 32));
  411. }
  412. finally
  413. {
  414. Array.Clear(firstBlock, 0, 64);
  415. }
  416. }
  417. private void PadMac(ulong count)
  418. {
  419. int partial = (int)count & (MacSize - 1);
  420. if (0 != partial)
  421. {
  422. mPoly1305.BlockUpdate(Zeroes, 0, MacSize - partial);
  423. }
  424. }
  425. private void ProcessData(byte[] inBytes, int inOff, int inLen, byte[] outBytes, int outOff)
  426. {
  427. Check.OutputLength(outBytes, outOff, inLen, "output buffer too short");
  428. mChacha20.ProcessBytes(inBytes, inOff, inLen, outBytes, outOff);
  429. this.mDataCount = IncrementCount(mDataCount, (uint)inLen, DataLimit);
  430. }
  431. private void Reset(bool clearMac, bool resetCipher)
  432. {
  433. Array.Clear(mBuf, 0, mBuf.Length);
  434. if (clearMac)
  435. {
  436. Array.Clear(mMac, 0, mMac.Length);
  437. }
  438. this.mAadCount = 0UL;
  439. this.mDataCount = 0UL;
  440. this.mBufPos = 0;
  441. switch (mState)
  442. {
  443. case State.DecInit:
  444. case State.EncInit:
  445. break;
  446. case State.DecAad:
  447. case State.DecData:
  448. case State.DecFinal:
  449. this.mState = State.DecInit;
  450. break;
  451. case State.EncAad:
  452. case State.EncData:
  453. case State.EncFinal:
  454. this.mState = State.EncFinal;
  455. return;
  456. default:
  457. throw new InvalidOperationException();
  458. }
  459. if (resetCipher)
  460. {
  461. mChacha20.Reset();
  462. }
  463. InitMac();
  464. if (null != mInitialAad)
  465. {
  466. ProcessAadBytes(mInitialAad, 0, mInitialAad.Length);
  467. }
  468. }
  469. }
  470. }
  471. #pragma warning restore
  472. #endif