FastCcmBlockCipher.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace BestHTTP.Connections.TLS.Crypto.Impl
  11. {
  12. public class FastSicBlockCipher
  13. : IBlockCipher
  14. {
  15. private readonly IBlockCipher cipher;
  16. private readonly int blockSize;
  17. private readonly byte[] counter;
  18. private readonly byte[] counterOut;
  19. private byte[] IV;
  20. /**
  21. * Basic constructor.
  22. *
  23. * @param c the block cipher to be used.
  24. */
  25. public FastSicBlockCipher(IBlockCipher cipher)
  26. {
  27. this.cipher = cipher;
  28. this.blockSize = cipher.GetBlockSize();
  29. this.counter = new byte[blockSize];
  30. this.counterOut = new byte[blockSize];
  31. this.IV = new byte[blockSize];
  32. }
  33. /**
  34. * return the underlying block cipher that we are wrapping.
  35. *
  36. * @return the underlying block cipher that we are wrapping.
  37. */
  38. public virtual IBlockCipher GetUnderlyingCipher()
  39. {
  40. return cipher;
  41. }
  42. public virtual void Init(
  43. bool forEncryption, //ignored by this CTR mode
  44. ICipherParameters parameters)
  45. {
  46. FastParametersWithIV ivParam = parameters as FastParametersWithIV;
  47. if (ivParam == null)
  48. throw new ArgumentException("CTR/SIC mode requires ParametersWithIV", "parameters");
  49. this.IV = ivParam.GetIV();
  50. if (blockSize < IV.Length)
  51. throw new ArgumentException("CTR/SIC mode requires IV no greater than: " + blockSize + " bytes.");
  52. int maxCounterSize = System.Math.Min(8, blockSize / 2);
  53. if (blockSize - IV.Length > maxCounterSize)
  54. throw new ArgumentException("CTR/SIC mode requires IV of at least: " + (blockSize - maxCounterSize) + " bytes.");
  55. // if null it's an IV changed only.
  56. if (ivParam.Parameters != null)
  57. {
  58. cipher.Init(true, ivParam.Parameters);
  59. }
  60. Reset();
  61. }
  62. public virtual string AlgorithmName
  63. {
  64. get { return cipher.AlgorithmName + "/SIC"; }
  65. }
  66. public virtual bool IsPartialBlockOkay
  67. {
  68. get { return true; }
  69. }
  70. public virtual int GetBlockSize()
  71. {
  72. return cipher.GetBlockSize();
  73. }
  74. public virtual int ProcessBlock(
  75. byte[] input,
  76. int inOff,
  77. byte[] output,
  78. int outOff)
  79. {
  80. cipher.ProcessBlock(counter, 0, counterOut, 0);
  81. //
  82. // XOR the counterOut with the plaintext producing the cipher text
  83. //
  84. for (int i = 0; i < counterOut.Length; i++)
  85. {
  86. output[outOff + i] = (byte)(counterOut[i] ^ input[inOff + i]);
  87. }
  88. // Increment the counter
  89. int j = counter.Length;
  90. while (--j >= 0 && ++counter[j] == 0)
  91. {
  92. }
  93. return counter.Length;
  94. }
  95. public virtual void Reset()
  96. {
  97. Arrays.Fill(counter, (byte)0);
  98. Array.Copy(IV, 0, counter, 0, IV.Length);
  99. cipher.Reset();
  100. }
  101. }
  102. /**
  103. * Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
  104. * NIST Special Publication 800-38C.
  105. * <p>
  106. * <b>Note</b>: this mode is a packet mode - it needs all the data up front.
  107. * </p>
  108. */
  109. public class FastCcmBlockCipher
  110. : IAeadBlockCipher
  111. {
  112. private static readonly int BlockSize = 16;
  113. private readonly IBlockCipher cipher;
  114. private readonly byte[] macBlock;
  115. private bool forEncryption;
  116. private byte[] nonce;
  117. private byte[] initialAssociatedText;
  118. private int macSize;
  119. private ICipherParameters keyParam;
  120. private readonly MemoryStream associatedText = new MemoryStream();
  121. private readonly MemoryStream data = new MemoryStream();
  122. /**
  123. * Basic constructor.
  124. *
  125. * @param cipher the block cipher to be used.
  126. */
  127. public FastCcmBlockCipher(
  128. IBlockCipher cipher)
  129. {
  130. this.cipher = cipher;
  131. this.macBlock = new byte[BlockSize];
  132. if (cipher.GetBlockSize() != BlockSize)
  133. throw new ArgumentException("cipher required with a block size of " + BlockSize + ".");
  134. }
  135. /**
  136. * return the underlying block cipher that we are wrapping.
  137. *
  138. * @return the underlying block cipher that we are wrapping.
  139. */
  140. public virtual IBlockCipher GetUnderlyingCipher()
  141. {
  142. return cipher;
  143. }
  144. public virtual void Init(
  145. bool forEncryption,
  146. ICipherParameters parameters)
  147. {
  148. this.forEncryption = forEncryption;
  149. ICipherParameters cipherParameters;
  150. if (parameters is FastAeadParameters)
  151. {
  152. AeadParameters param = (AeadParameters)parameters;
  153. nonce = param.GetNonce();
  154. initialAssociatedText = param.GetAssociatedText();
  155. macSize = GetMacSize(forEncryption, param.MacSize);
  156. cipherParameters = param.Key;
  157. }
  158. else if (parameters is FastParametersWithIV)
  159. {
  160. FastParametersWithIV param = (FastParametersWithIV)parameters;
  161. nonce = param.GetIV();
  162. initialAssociatedText = null;
  163. macSize = GetMacSize(forEncryption, 64);
  164. cipherParameters = param.Parameters;
  165. }
  166. else
  167. {
  168. throw new ArgumentException("invalid parameters passed to CCM");
  169. }
  170. // NOTE: Very basic support for key re-use, but no performance gain from it
  171. if (cipherParameters != null)
  172. {
  173. keyParam = cipherParameters;
  174. }
  175. if (nonce == null || nonce.Length < 7 || nonce.Length > 13)
  176. throw new ArgumentException("nonce must have length from 7 to 13 octets");
  177. Reset();
  178. }
  179. public virtual string AlgorithmName
  180. {
  181. get { return cipher.AlgorithmName + "/CCM"; }
  182. }
  183. public virtual int GetBlockSize()
  184. {
  185. return cipher.GetBlockSize();
  186. }
  187. public virtual void ProcessAadByte(byte input)
  188. {
  189. associatedText.WriteByte(input);
  190. }
  191. public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
  192. {
  193. // TODO: Process AAD online
  194. associatedText.Write(inBytes, inOff, len);
  195. }
  196. public virtual int ProcessByte(
  197. byte input,
  198. byte[] outBytes,
  199. int outOff)
  200. {
  201. data.WriteByte(input);
  202. return 0;
  203. }
  204. public virtual int ProcessBytes(
  205. byte[] inBytes,
  206. int inOff,
  207. int inLen,
  208. byte[] outBytes,
  209. int outOff)
  210. {
  211. Check.DataLength(inBytes, inOff, inLen, "Input buffer too short");
  212. data.Write(inBytes, inOff, inLen);
  213. return 0;
  214. }
  215. public virtual int DoFinal(
  216. byte[] outBytes,
  217. int outOff)
  218. {
  219. #if PORTABLE || NETFX_CORE
  220. byte[] input = data.ToArray();
  221. int inLen = input.Length;
  222. #else
  223. byte[] input = data.GetBuffer();
  224. int inLen = (int)data.Position;
  225. #endif
  226. int len = ProcessPacket(input, 0, inLen, outBytes, outOff);
  227. Reset();
  228. return len;
  229. }
  230. public virtual void Reset()
  231. {
  232. cipher.Reset();
  233. associatedText.SetLength(0);
  234. data.SetLength(0);
  235. }
  236. /**
  237. * Returns a byte array containing the mac calculated as part of the
  238. * last encrypt or decrypt operation.
  239. *
  240. * @return the last mac calculated.
  241. */
  242. public virtual byte[] GetMac()
  243. {
  244. return Arrays.CopyOfRange(macBlock, 0, macSize);
  245. }
  246. public virtual int GetUpdateOutputSize(
  247. int len)
  248. {
  249. return 0;
  250. }
  251. public virtual int GetOutputSize(
  252. int len)
  253. {
  254. int totalData = (int)data.Length + len;
  255. if (forEncryption)
  256. {
  257. return totalData + macSize;
  258. }
  259. return totalData < macSize ? 0 : totalData - macSize;
  260. }
  261. /**
  262. * Process a packet of data for either CCM decryption or encryption.
  263. *
  264. * @param in data for processing.
  265. * @param inOff offset at which data starts in the input array.
  266. * @param inLen length of the data in the input array.
  267. * @return a byte array containing the processed input..
  268. * @throws IllegalStateException if the cipher is not appropriately set up.
  269. * @throws InvalidCipherTextException if the input data is truncated or the mac check fails.
  270. */
  271. public virtual byte[] ProcessPacket(byte[] input, int inOff, int inLen)
  272. {
  273. byte[] output;
  274. if (forEncryption)
  275. {
  276. output = new byte[inLen + macSize];
  277. }
  278. else
  279. {
  280. if (inLen < macSize)
  281. throw new InvalidCipherTextException("data too short");
  282. output = new byte[inLen - macSize];
  283. }
  284. ProcessPacket(input, inOff, inLen, output, 0);
  285. return output;
  286. }
  287. /**
  288. * Process a packet of data for either CCM decryption or encryption.
  289. *
  290. * @param in data for processing.
  291. * @param inOff offset at which data starts in the input array.
  292. * @param inLen length of the data in the input array.
  293. * @param output output array.
  294. * @param outOff offset into output array to start putting processed bytes.
  295. * @return the number of bytes added to output.
  296. * @throws IllegalStateException if the cipher is not appropriately set up.
  297. * @throws InvalidCipherTextException if the input data is truncated or the mac check fails.
  298. * @throws DataLengthException if output buffer too short.
  299. */
  300. public virtual int ProcessPacket(byte[] input, int inOff, int inLen, byte[] output, int outOff)
  301. {
  302. // TODO: handle null keyParam (e.g. via RepeatedKeySpec)
  303. // Need to keep the CTR and CBC Mac parts around and reset
  304. if (keyParam == null)
  305. throw new InvalidOperationException("CCM cipher unitialized.");
  306. int n = nonce.Length;
  307. int q = 15 - n;
  308. if (q < 4)
  309. {
  310. int limitLen = 1 << (8 * q);
  311. if (inLen >= limitLen)
  312. throw new InvalidOperationException("CCM packet too large for choice of q.");
  313. }
  314. byte[] iv = new byte[BlockSize];
  315. iv[0] = (byte)((q - 1) & 0x7);
  316. nonce.CopyTo(iv, 1);
  317. IBlockCipher ctrCipher = new FastSicBlockCipher(cipher);
  318. ctrCipher.Init(forEncryption, new FastParametersWithIV(keyParam, iv));
  319. int outputLen;
  320. int inIndex = inOff;
  321. int outIndex = outOff;
  322. if (forEncryption)
  323. {
  324. outputLen = inLen + macSize;
  325. Check.OutputLength(output, outOff, outputLen, "Output buffer too short.");
  326. CalculateMac(input, inOff, inLen, macBlock);
  327. byte[] encMac = new byte[BlockSize];
  328. ctrCipher.ProcessBlock(macBlock, 0, encMac, 0); // S0
  329. while (inIndex < (inOff + inLen - BlockSize)) // S1...
  330. {
  331. ctrCipher.ProcessBlock(input, inIndex, output, outIndex);
  332. outIndex += BlockSize;
  333. inIndex += BlockSize;
  334. }
  335. byte[] block = new byte[BlockSize];
  336. Array.Copy(input, inIndex, block, 0, inLen + inOff - inIndex);
  337. ctrCipher.ProcessBlock(block, 0, block, 0);
  338. Array.Copy(block, 0, output, outIndex, inLen + inOff - inIndex);
  339. Array.Copy(encMac, 0, output, outOff + inLen, macSize);
  340. }
  341. else
  342. {
  343. if (inLen < macSize)
  344. throw new InvalidCipherTextException("data too short");
  345. outputLen = inLen - macSize;
  346. Check.OutputLength(output, outOff, outputLen, "Output buffer too short.");
  347. Array.Copy(input, inOff + outputLen, macBlock, 0, macSize);
  348. ctrCipher.ProcessBlock(macBlock, 0, macBlock, 0);
  349. for (int i = macSize; i != macBlock.Length; i++)
  350. {
  351. macBlock[i] = 0;
  352. }
  353. while (inIndex < (inOff + outputLen - BlockSize))
  354. {
  355. ctrCipher.ProcessBlock(input, inIndex, output, outIndex);
  356. outIndex += BlockSize;
  357. inIndex += BlockSize;
  358. }
  359. byte[] block = new byte[BlockSize];
  360. Array.Copy(input, inIndex, block, 0, outputLen - (inIndex - inOff));
  361. ctrCipher.ProcessBlock(block, 0, block, 0);
  362. Array.Copy(block, 0, output, outIndex, outputLen - (inIndex - inOff));
  363. byte[] calculatedMacBlock = new byte[BlockSize];
  364. CalculateMac(output, outOff, outputLen, calculatedMacBlock);
  365. if (!Arrays.ConstantTimeAreEqual(macBlock, calculatedMacBlock))
  366. throw new InvalidCipherTextException("mac check in CCM failed");
  367. }
  368. return outputLen;
  369. }
  370. private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock)
  371. {
  372. IMac cMac = new CbcBlockCipherMac(cipher, macSize * 8);
  373. cMac.Init(keyParam);
  374. //
  375. // build b0
  376. //
  377. byte[] b0 = new byte[16];
  378. if (HasAssociatedText())
  379. {
  380. b0[0] |= 0x40;
  381. }
  382. b0[0] |= (byte)((((cMac.GetMacSize() - 2) / 2) & 0x7) << 3);
  383. b0[0] |= (byte)(((15 - nonce.Length) - 1) & 0x7);
  384. Array.Copy(nonce, 0, b0, 1, nonce.Length);
  385. int q = dataLen;
  386. int count = 1;
  387. while (q > 0)
  388. {
  389. b0[b0.Length - count] = (byte)(q & 0xff);
  390. q >>= 8;
  391. count++;
  392. }
  393. cMac.BlockUpdate(b0, 0, b0.Length);
  394. //
  395. // process associated text
  396. //
  397. if (HasAssociatedText())
  398. {
  399. int extra;
  400. int textLength = GetAssociatedTextLength();
  401. if (textLength < ((1 << 16) - (1 << 8)))
  402. {
  403. cMac.Update((byte)(textLength >> 8));
  404. cMac.Update((byte)textLength);
  405. extra = 2;
  406. }
  407. else // can't go any higher than 2^32
  408. {
  409. cMac.Update((byte)0xff);
  410. cMac.Update((byte)0xfe);
  411. cMac.Update((byte)(textLength >> 24));
  412. cMac.Update((byte)(textLength >> 16));
  413. cMac.Update((byte)(textLength >> 8));
  414. cMac.Update((byte)textLength);
  415. extra = 6;
  416. }
  417. if (initialAssociatedText != null)
  418. {
  419. cMac.BlockUpdate(initialAssociatedText, 0, initialAssociatedText.Length);
  420. }
  421. if (associatedText.Position > 0)
  422. {
  423. #if PORTABLE || NETFX_CORE
  424. byte[] input = associatedText.ToArray();
  425. int len = input.Length;
  426. #else
  427. byte[] input = associatedText.GetBuffer();
  428. int len = (int)associatedText.Position;
  429. #endif
  430. cMac.BlockUpdate(input, 0, len);
  431. }
  432. extra = (extra + textLength) % 16;
  433. if (extra != 0)
  434. {
  435. for (int i = extra; i < 16; ++i)
  436. {
  437. cMac.Update((byte)0x00);
  438. }
  439. }
  440. }
  441. //
  442. // add the text
  443. //
  444. cMac.BlockUpdate(data, dataOff, dataLen);
  445. return cMac.DoFinal(macBlock, 0);
  446. }
  447. private int GetMacSize(bool forEncryption, int requestedMacBits)
  448. {
  449. if (forEncryption && (requestedMacBits < 32 || requestedMacBits > 128 || 0 != (requestedMacBits & 15)))
  450. throw new ArgumentException("tag length in octets must be one of {4,6,8,10,12,14,16}");
  451. return requestedMacBits >> 3;
  452. }
  453. private int GetAssociatedTextLength()
  454. {
  455. return (int)associatedText.Length + ((initialAssociatedText == null) ? 0 : initialAssociatedText.Length);
  456. }
  457. private bool HasAssociatedText()
  458. {
  459. return GetAssociatedTextLength() > 0;
  460. }
  461. }
  462. }
  463. #pragma warning restore
  464. #endif