BufferedBlockCipher.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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.Modes;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  6. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto
  7. {
  8. /**
  9. * A wrapper class that allows block ciphers to be used to process data in
  10. * a piecemeal fashion. The BufferedBlockCipher outputs a block only when the
  11. * buffer is full and more data is being added, or on a doFinal.
  12. * <p>
  13. * Note: in the case where the underlying cipher is either a CFB cipher or an
  14. * OFB one the last block may not be a multiple of the block size.
  15. * </p>
  16. */
  17. public class BufferedBlockCipher
  18. : BufferedCipherBase
  19. {
  20. internal byte[] buf;
  21. internal int bufOff;
  22. internal bool forEncryption;
  23. internal IBlockCipherMode m_cipherMode;
  24. /**
  25. * constructor for subclasses
  26. */
  27. protected BufferedBlockCipher()
  28. {
  29. }
  30. public BufferedBlockCipher(IBlockCipher cipher)
  31. : this(EcbBlockCipher.GetBlockCipherMode(cipher))
  32. {
  33. }
  34. /**
  35. * Create a buffered block cipher without padding.
  36. *
  37. * @param cipher the underlying block cipher this buffering object wraps.
  38. * false otherwise.
  39. */
  40. public BufferedBlockCipher(IBlockCipherMode cipherMode)
  41. {
  42. if (cipherMode == null)
  43. throw new ArgumentNullException(nameof(cipherMode));
  44. m_cipherMode = cipherMode;
  45. buf = new byte[cipherMode.GetBlockSize()];
  46. bufOff = 0;
  47. }
  48. public override string AlgorithmName
  49. {
  50. get { return m_cipherMode.AlgorithmName; }
  51. }
  52. /**
  53. * initialise the cipher.
  54. *
  55. * @param forEncryption if true the cipher is initialised for
  56. * encryption, if false for decryption.
  57. * @param param the key and other data required by the cipher.
  58. * @exception ArgumentException if the parameters argument is
  59. * inappropriate.
  60. */
  61. // Note: This doubles as the Init in the event that this cipher is being used as an IWrapper
  62. public override void Init(bool forEncryption, ICipherParameters parameters)
  63. {
  64. this.forEncryption = forEncryption;
  65. if (parameters is ParametersWithRandom withRandom)
  66. {
  67. parameters = withRandom.Parameters;
  68. }
  69. Reset();
  70. m_cipherMode.Init(forEncryption, parameters);
  71. }
  72. /**
  73. * return the blocksize for the underlying cipher.
  74. *
  75. * @return the blocksize for the underlying cipher.
  76. */
  77. public override int GetBlockSize()
  78. {
  79. return m_cipherMode.GetBlockSize();
  80. }
  81. /**
  82. * return the size of the output buffer required for an update
  83. * an input of len bytes.
  84. *
  85. * @param len the length of the input.
  86. * @return the space required to accommodate a call to update
  87. * with len bytes of input.
  88. */
  89. public override int GetUpdateOutputSize(int length)
  90. {
  91. int total = length + bufOff;
  92. int leftOver = total % buf.Length;
  93. return total - leftOver;
  94. }
  95. /**
  96. * return the size of the output buffer required for an update plus a
  97. * doFinal with an input of len bytes.
  98. *
  99. * @param len the length of the input.
  100. * @return the space required to accommodate a call to update and doFinal
  101. * with len bytes of input.
  102. */
  103. public override int GetOutputSize(int length)
  104. {
  105. // Note: Can assume IsPartialBlockOkay is true for purposes of this calculation
  106. return length + bufOff;
  107. }
  108. /**
  109. * process a single byte, producing an output block if necessary.
  110. *
  111. * @param in the input byte.
  112. * @param out the space for any output that might be produced.
  113. * @param outOff the offset from which the output will be copied.
  114. * @return the number of output bytes copied to out.
  115. * @exception DataLengthException if there isn't enough space in out.
  116. * @exception InvalidOperationException if the cipher isn't initialised.
  117. */
  118. public override int ProcessByte(byte input, byte[] output, int outOff)
  119. {
  120. buf[bufOff++] = input;
  121. if (bufOff == buf.Length)
  122. {
  123. if ((outOff + buf.Length) > output.Length)
  124. throw new DataLengthException("output buffer too short");
  125. bufOff = 0;
  126. return m_cipherMode.ProcessBlock(buf, 0, output, outOff);
  127. }
  128. return 0;
  129. }
  130. public override byte[] ProcessByte(byte input)
  131. {
  132. int outLength = GetUpdateOutputSize(1);
  133. byte[] outBytes = outLength > 0 ? new byte[outLength] : null;
  134. int pos = ProcessByte(input, outBytes, 0);
  135. if (outLength > 0 && pos < outLength)
  136. {
  137. byte[] tmp = new byte[pos];
  138. Array.Copy(outBytes, 0, tmp, 0, pos);
  139. outBytes = tmp;
  140. }
  141. return outBytes;
  142. }
  143. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  144. public override int ProcessByte(byte input, Span<byte> output)
  145. {
  146. buf[bufOff++] = input;
  147. if (bufOff == buf.Length)
  148. {
  149. Check.OutputLength(output, buf.Length, "output buffer too short");
  150. bufOff = 0;
  151. return m_cipherMode.ProcessBlock(buf, output);
  152. }
  153. return 0;
  154. }
  155. #endif
  156. public override byte[] ProcessBytes(byte[] input, int inOff, int length)
  157. {
  158. if (input == null)
  159. throw new ArgumentNullException(nameof(input));
  160. if (length < 1)
  161. return null;
  162. int outLength = GetUpdateOutputSize(length);
  163. byte[] outBytes = outLength > 0 ? new byte[outLength] : null;
  164. int pos = ProcessBytes(input, inOff, length, outBytes, 0);
  165. if (outLength > 0 && pos < outLength)
  166. {
  167. byte[] tmp = new byte[pos];
  168. Array.Copy(outBytes, 0, tmp, 0, pos);
  169. outBytes = tmp;
  170. }
  171. return outBytes;
  172. }
  173. /**
  174. * process an array of bytes, producing output if necessary.
  175. *
  176. * @param in the input byte array.
  177. * @param inOff the offset at which the input data starts.
  178. * @param len the number of bytes to be copied out of the input array.
  179. * @param out the space for any output that might be produced.
  180. * @param outOff the offset from which the output will be copied.
  181. * @return the number of output bytes copied to out.
  182. * @exception DataLengthException if there isn't enough space in out.
  183. * @exception InvalidOperationException if the cipher isn't initialised.
  184. */
  185. public override int ProcessBytes(byte[] input, int inOff, int length, byte[] output, int outOff)
  186. {
  187. if (length < 1)
  188. {
  189. if (length < 0)
  190. throw new ArgumentException("Can't have a negative input length!");
  191. return 0;
  192. }
  193. int blockSize = GetBlockSize();
  194. int outLength = GetUpdateOutputSize(length);
  195. if (outLength > 0)
  196. {
  197. Check.OutputLength(output, outOff, outLength, "output buffer too short");
  198. }
  199. int resultLen = 0;
  200. int gapLen = buf.Length - bufOff;
  201. if (length >= gapLen)
  202. {
  203. Array.Copy(input, inOff, buf, bufOff, gapLen);
  204. resultLen = m_cipherMode.ProcessBlock(buf, 0, output, outOff);
  205. bufOff = 0;
  206. length -= gapLen;
  207. inOff += gapLen;
  208. while (length >= buf.Length)
  209. {
  210. resultLen += m_cipherMode.ProcessBlock(input, inOff, output, outOff + resultLen);
  211. length -= blockSize;
  212. inOff += blockSize;
  213. }
  214. }
  215. Array.Copy(input, inOff, buf, bufOff, length);
  216. bufOff += length;
  217. return resultLen;
  218. }
  219. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  220. public override int ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
  221. {
  222. if (input.IsEmpty)
  223. return 0;
  224. int blockSize = GetBlockSize();
  225. int outLength = GetUpdateOutputSize(input.Length);
  226. if (outLength > 0)
  227. {
  228. Check.OutputLength(output, outLength, "output buffer too short");
  229. }
  230. int resultLen = 0;
  231. int gapLen = buf.Length - bufOff;
  232. if (input.Length >= gapLen)
  233. {
  234. input[..gapLen].CopyTo(buf.AsSpan(bufOff));
  235. resultLen = m_cipherMode.ProcessBlock(buf, output);
  236. bufOff = 0;
  237. input = input[gapLen..];
  238. while (input.Length >= buf.Length)
  239. {
  240. resultLen += m_cipherMode.ProcessBlock(input, output[resultLen..]);
  241. input = input[blockSize..];
  242. }
  243. }
  244. input.CopyTo(buf.AsSpan(bufOff));
  245. bufOff += input.Length;
  246. return resultLen;
  247. }
  248. #endif
  249. public override byte[] DoFinal()
  250. {
  251. byte[] outBytes = EmptyBuffer;
  252. int length = GetOutputSize(0);
  253. if (length > 0)
  254. {
  255. outBytes = new byte[length];
  256. int pos = DoFinal(outBytes, 0);
  257. if (pos < outBytes.Length)
  258. {
  259. byte[] tmp = new byte[pos];
  260. Array.Copy(outBytes, 0, tmp, 0, pos);
  261. outBytes = tmp;
  262. }
  263. }
  264. else
  265. {
  266. Reset();
  267. }
  268. return outBytes;
  269. }
  270. public override byte[] DoFinal(byte[] input, int inOff, int inLen)
  271. {
  272. if (input == null)
  273. throw new ArgumentNullException(nameof(input));
  274. int length = GetOutputSize(inLen);
  275. byte[] outBytes = EmptyBuffer;
  276. if (length > 0)
  277. {
  278. outBytes = new byte[length];
  279. int pos = (inLen > 0)
  280. ? ProcessBytes(input, inOff, inLen, outBytes, 0)
  281. : 0;
  282. pos += DoFinal(outBytes, pos);
  283. if (pos < outBytes.Length)
  284. {
  285. byte[] tmp = new byte[pos];
  286. Array.Copy(outBytes, 0, tmp, 0, pos);
  287. outBytes = tmp;
  288. }
  289. }
  290. else
  291. {
  292. Reset();
  293. }
  294. return outBytes;
  295. }
  296. /**
  297. * Process the last block in the buffer.
  298. *
  299. * @param out the array the block currently being held is copied into.
  300. * @param outOff the offset at which the copying starts.
  301. * @return the number of output bytes copied to out.
  302. * @exception DataLengthException if there is insufficient space in out for
  303. * the output, or the input is not block size aligned and should be.
  304. * @exception InvalidOperationException if the underlying cipher is not
  305. * initialised.
  306. * @exception InvalidCipherTextException if padding is expected and not found.
  307. * @exception DataLengthException if the input is not block size
  308. * aligned.
  309. */
  310. public override int DoFinal(byte[] output, int outOff)
  311. {
  312. try
  313. {
  314. if (bufOff != 0)
  315. {
  316. Check.DataLength(!m_cipherMode.IsPartialBlockOkay, "data not block size aligned");
  317. Check.OutputLength(output, outOff, bufOff, "output buffer too short for DoFinal()");
  318. // NB: Can't copy directly, or we may write too much output
  319. m_cipherMode.ProcessBlock(buf, 0, buf, 0);
  320. Array.Copy(buf, 0, output, outOff, bufOff);
  321. }
  322. return bufOff;
  323. }
  324. finally
  325. {
  326. Reset();
  327. }
  328. }
  329. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  330. public override int DoFinal(Span<byte> output)
  331. {
  332. try
  333. {
  334. if (bufOff != 0)
  335. {
  336. Check.DataLength(!m_cipherMode.IsPartialBlockOkay, "data not block size aligned");
  337. Check.OutputLength(output, bufOff, "output buffer too short for DoFinal()");
  338. // NB: Can't copy directly, or we may write too much output
  339. m_cipherMode.ProcessBlock(buf, buf);
  340. buf.AsSpan(0, bufOff).CopyTo(output);
  341. }
  342. return bufOff;
  343. }
  344. finally
  345. {
  346. Reset();
  347. }
  348. }
  349. #endif
  350. /**
  351. * Reset the buffer and cipher. After resetting the object is in the same
  352. * state as it was after the last init (if there was one).
  353. */
  354. public override void Reset()
  355. {
  356. Array.Clear(buf, 0, buf.Length);
  357. bufOff = 0;
  358. m_cipherMode.Reset();
  359. }
  360. }
  361. }
  362. #pragma warning restore
  363. #endif