GCMBlockCipher.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  5. using System.Runtime.CompilerServices;
  6. #endif
  7. #if NETCOREAPP3_0_OR_GREATER
  8. using System.Runtime.InteropServices;
  9. using System.Runtime.Intrinsics;
  10. using System.Runtime.Intrinsics.X86;
  11. #endif
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm;
  13. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  14. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  15. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  16. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
  17. {
  18. /// <summary>
  19. /// Implements the Galois/Counter mode (GCM) detailed in NIST Special Publication 800-38D.
  20. /// </summary>
  21. public sealed class GcmBlockCipher
  22. : IAeadBlockCipher
  23. {
  24. private static IGcmMultiplier CreateGcmMultiplier()
  25. {
  26. #if NETCOREAPP3_0_OR_GREATER
  27. // TODO Prefer more tightly coupled test
  28. if (Pclmulqdq.IsSupported)
  29. {
  30. return new BasicGcmMultiplier();
  31. }
  32. #endif
  33. return new Tables4kGcmMultiplier();
  34. }
  35. private const int BlockSize = 16;
  36. byte[] ctrBlock = new byte[BlockSize];
  37. private readonly IBlockCipher cipher;
  38. private readonly IGcmMultiplier multiplier;
  39. private IGcmExponentiator exp;
  40. // These fields are set by Init and not modified by processing
  41. private bool forEncryption;
  42. private bool initialised;
  43. private int macSize;
  44. private byte[] lastKey;
  45. private byte[] nonce;
  46. private byte[] initialAssociatedText;
  47. private byte[] H;
  48. private byte[] J0;
  49. // These fields are modified during processing
  50. private byte[] bufBlock;
  51. private byte[] macBlock;
  52. private byte[] S, S_at, S_atPre;
  53. private byte[] counter;
  54. private uint counter32;
  55. private uint blocksRemaining;
  56. private int bufOff;
  57. private ulong totalLength;
  58. private byte[] atBlock;
  59. private int atBlockPos;
  60. private ulong atLength;
  61. private ulong atLengthPre;
  62. public GcmBlockCipher(
  63. IBlockCipher c)
  64. : this(c, null)
  65. {
  66. }
  67. public GcmBlockCipher(
  68. IBlockCipher c,
  69. IGcmMultiplier m)
  70. {
  71. if (c.GetBlockSize() != BlockSize)
  72. throw new ArgumentException("cipher required with a block size of " + BlockSize + ".");
  73. if (m == null)
  74. {
  75. m = CreateGcmMultiplier();
  76. }
  77. this.cipher = c;
  78. this.multiplier = m;
  79. }
  80. public string AlgorithmName => cipher.AlgorithmName + "/GCM";
  81. public IBlockCipher UnderlyingCipher => cipher;
  82. public int GetBlockSize()
  83. {
  84. return BlockSize;
  85. }
  86. /// <remarks>
  87. /// MAC sizes from 32 bits to 128 bits (must be a multiple of 8) are supported. The default is 128 bits.
  88. /// Sizes less than 96 are not recommended, but are supported for specialized applications.
  89. /// </remarks>
  90. public void Init(bool forEncryption, ICipherParameters parameters)
  91. {
  92. this.forEncryption = forEncryption;
  93. this.macBlock = null;
  94. this.initialised = true;
  95. KeyParameter keyParam;
  96. byte[] newNonce;
  97. if (parameters is AeadParameters)
  98. {
  99. AeadParameters param = (AeadParameters)parameters;
  100. newNonce = param.GetNonce();
  101. initialAssociatedText = param.GetAssociatedText();
  102. int macSizeBits = param.MacSize;
  103. if (macSizeBits < 32 || macSizeBits > 128 || macSizeBits % 8 != 0)
  104. {
  105. throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
  106. }
  107. macSize = macSizeBits / 8;
  108. keyParam = param.Key;
  109. }
  110. else if (parameters is ParametersWithIV)
  111. {
  112. ParametersWithIV param = (ParametersWithIV)parameters;
  113. newNonce = param.GetIV();
  114. initialAssociatedText = null;
  115. macSize = 16;
  116. keyParam = (KeyParameter)param.Parameters;
  117. }
  118. else
  119. {
  120. throw new ArgumentException("invalid parameters passed to GCM");
  121. }
  122. int bufLength = forEncryption ? BlockSize : (BlockSize + macSize);
  123. this.bufBlock = new byte[bufLength];
  124. if (newNonce == null || newNonce.Length < 1)
  125. {
  126. throw new ArgumentException("IV must be at least 1 byte");
  127. }
  128. if (forEncryption)
  129. {
  130. if (nonce != null && Arrays.AreEqual(nonce, newNonce))
  131. {
  132. if (keyParam == null)
  133. {
  134. throw new ArgumentException("cannot reuse nonce for GCM encryption");
  135. }
  136. if (lastKey != null && Arrays.AreEqual(lastKey, keyParam.GetKey()))
  137. {
  138. throw new ArgumentException("cannot reuse nonce for GCM encryption");
  139. }
  140. }
  141. }
  142. nonce = newNonce;
  143. if (keyParam != null)
  144. {
  145. lastKey = keyParam.GetKey();
  146. }
  147. // TODO Restrict macSize to 16 if nonce length not 12?
  148. // Cipher always used in forward mode
  149. // if keyParam is null we're reusing the last key.
  150. if (keyParam != null)
  151. {
  152. cipher.Init(true, keyParam);
  153. this.H = new byte[BlockSize];
  154. cipher.ProcessBlock(H, 0, H, 0);
  155. // if keyParam is null we're reusing the last key and the multiplier doesn't need re-init
  156. multiplier.Init(H);
  157. exp = null;
  158. }
  159. else if (this.H == null)
  160. {
  161. throw new ArgumentException("Key must be specified in initial init");
  162. }
  163. this.J0 = new byte[BlockSize];
  164. if (nonce.Length == 12)
  165. {
  166. Array.Copy(nonce, 0, J0, 0, nonce.Length);
  167. this.J0[BlockSize - 1] = 0x01;
  168. }
  169. else
  170. {
  171. gHASH(J0, nonce, nonce.Length);
  172. byte[] X = new byte[BlockSize];
  173. Pack.UInt64_To_BE((ulong)nonce.Length * 8UL, X, 8);
  174. gHASHBlock(J0, X);
  175. }
  176. this.S = new byte[BlockSize];
  177. this.S_at = new byte[BlockSize];
  178. this.S_atPre = new byte[BlockSize];
  179. this.atBlock = new byte[BlockSize];
  180. this.atBlockPos = 0;
  181. this.atLength = 0;
  182. this.atLengthPre = 0;
  183. this.counter = Arrays.Clone(J0);
  184. this.counter32 = Pack.BE_To_UInt32(counter, 12);
  185. this.blocksRemaining = uint.MaxValue - 1; // page 8, len(P) <= 2^39 - 256, 1 block used by tag
  186. this.bufOff = 0;
  187. this.totalLength = 0;
  188. if (initialAssociatedText != null)
  189. {
  190. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  191. }
  192. }
  193. public byte[] GetMac()
  194. {
  195. return macBlock == null
  196. ? new byte[macSize]
  197. : Arrays.Clone(macBlock);
  198. }
  199. public int GetOutputSize(int len)
  200. {
  201. int totalData = len + bufOff;
  202. if (forEncryption)
  203. {
  204. return totalData + macSize;
  205. }
  206. return totalData < macSize ? 0 : totalData - macSize;
  207. }
  208. public int GetUpdateOutputSize(int len)
  209. {
  210. int totalData = len + bufOff;
  211. if (!forEncryption)
  212. {
  213. if (totalData < macSize)
  214. {
  215. return 0;
  216. }
  217. totalData -= macSize;
  218. }
  219. return totalData - totalData % BlockSize;
  220. }
  221. public void ProcessAadByte(byte input)
  222. {
  223. CheckStatus();
  224. atBlock[atBlockPos] = input;
  225. if (++atBlockPos == BlockSize)
  226. {
  227. // Hash each block as it fills
  228. gHASHBlock(S_at, atBlock);
  229. atBlockPos = 0;
  230. atLength += BlockSize;
  231. }
  232. }
  233. public void ProcessAadBytes(byte[] inBytes, int inOff, int len)
  234. {
  235. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  236. ProcessAadBytes(inBytes.AsSpan(inOff, len));
  237. #else
  238. CheckStatus();
  239. if (atBlockPos > 0)
  240. {
  241. int available = BlockSize - atBlockPos;
  242. if (len < available)
  243. {
  244. Array.Copy(inBytes, inOff, atBlock, atBlockPos, len);
  245. atBlockPos += len;
  246. return;
  247. }
  248. Array.Copy(inBytes, inOff, atBlock, atBlockPos, available);
  249. gHASHBlock(S_at, atBlock);
  250. atLength += BlockSize;
  251. inOff += available;
  252. len -= available;
  253. //atBlockPos = 0;
  254. }
  255. int inLimit = inOff + len - BlockSize;
  256. while (inOff <= inLimit)
  257. {
  258. gHASHBlock(S_at, inBytes, inOff);
  259. atLength += BlockSize;
  260. inOff += BlockSize;
  261. }
  262. atBlockPos = BlockSize + inLimit - inOff;
  263. Array.Copy(inBytes, inOff, atBlock, 0, atBlockPos);
  264. #endif
  265. }
  266. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  267. public void ProcessAadBytes(ReadOnlySpan<byte> input)
  268. {
  269. CheckStatus();
  270. if (atBlockPos > 0)
  271. {
  272. int available = BlockSize - atBlockPos;
  273. if (input.Length < available)
  274. {
  275. input.CopyTo(atBlock.AsSpan(atBlockPos));
  276. atBlockPos += input.Length;
  277. return;
  278. }
  279. input[..available].CopyTo(atBlock.AsSpan(atBlockPos));
  280. gHASHBlock(S_at, atBlock);
  281. atLength += BlockSize;
  282. input = input[available..];
  283. //atBlockPos = 0;
  284. }
  285. while (input.Length >= BlockSize)
  286. {
  287. gHASHBlock(S_at, input);
  288. atLength += BlockSize;
  289. input = input[BlockSize..];
  290. }
  291. input.CopyTo(atBlock);
  292. atBlockPos = input.Length;
  293. }
  294. #endif
  295. private void InitCipher()
  296. {
  297. if (atLength > 0)
  298. {
  299. Array.Copy(S_at, 0, S_atPre, 0, BlockSize);
  300. atLengthPre = atLength;
  301. }
  302. // Finish hash for partial AAD block
  303. if (atBlockPos > 0)
  304. {
  305. gHASHPartial(S_atPre, atBlock, 0, atBlockPos);
  306. atLengthPre += (uint)atBlockPos;
  307. }
  308. if (atLengthPre > 0)
  309. {
  310. Array.Copy(S_atPre, 0, S, 0, BlockSize);
  311. }
  312. }
  313. public int ProcessByte(byte input, byte[] output, int outOff)
  314. {
  315. CheckStatus();
  316. bufBlock[bufOff] = input;
  317. if (++bufOff == bufBlock.Length)
  318. {
  319. if (forEncryption)
  320. {
  321. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  322. EncryptBlock(bufBlock, output.AsSpan(outOff));
  323. #else
  324. EncryptBlock(bufBlock, 0, output, outOff);
  325. #endif
  326. bufOff = 0;
  327. }
  328. else
  329. {
  330. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  331. DecryptBlock(bufBlock, output.AsSpan(outOff));
  332. #else
  333. DecryptBlock(bufBlock, 0, output, outOff);
  334. #endif
  335. Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize);
  336. bufOff = macSize;
  337. }
  338. return BlockSize;
  339. }
  340. return 0;
  341. }
  342. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  343. public int ProcessByte(byte input, Span<byte> output)
  344. {
  345. CheckStatus();
  346. bufBlock[bufOff] = input;
  347. if (++bufOff == bufBlock.Length)
  348. {
  349. if (forEncryption)
  350. {
  351. EncryptBlock(bufBlock, output);
  352. bufOff = 0;
  353. }
  354. else
  355. {
  356. DecryptBlock(bufBlock, output);
  357. Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize);
  358. bufOff = macSize;
  359. }
  360. return BlockSize;
  361. }
  362. return 0;
  363. }
  364. #endif
  365. public int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
  366. {
  367. CheckStatus();
  368. Check.DataLength(input, inOff, len, "input buffer too short");
  369. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  370. return ProcessBytes(input.AsSpan(inOff, len), Spans.FromNullable(output, outOff));
  371. #else
  372. int resultLen = 0;
  373. if (forEncryption)
  374. {
  375. if (bufOff > 0)
  376. {
  377. int available = BlockSize - bufOff;
  378. if (len < available)
  379. {
  380. Array.Copy(input, inOff, bufBlock, bufOff, len);
  381. bufOff += len;
  382. return 0;
  383. }
  384. Array.Copy(input, inOff, bufBlock, bufOff, available);
  385. EncryptBlock(bufBlock, 0, output, outOff);
  386. inOff += available;
  387. len -= available;
  388. resultLen = BlockSize;
  389. //bufOff = 0;
  390. }
  391. int inLimit1 = inOff + len - BlockSize;
  392. int inLimit2 = inLimit1 - BlockSize;
  393. while (inOff <= inLimit2)
  394. {
  395. EncryptBlocks2(input, inOff, output, outOff + resultLen);
  396. inOff += BlockSize * 2;
  397. resultLen += BlockSize * 2;
  398. }
  399. if (inOff <= inLimit1)
  400. {
  401. EncryptBlock(input, inOff, output, outOff + resultLen);
  402. inOff += BlockSize;
  403. resultLen += BlockSize;
  404. }
  405. bufOff = BlockSize + inLimit1 - inOff;
  406. Array.Copy(input, inOff, bufBlock, 0, bufOff);
  407. }
  408. else
  409. {
  410. int available = bufBlock.Length - bufOff;
  411. if (len < available)
  412. {
  413. Array.Copy(input, inOff, bufBlock, bufOff, len);
  414. bufOff += len;
  415. return 0;
  416. }
  417. if (bufOff >= BlockSize)
  418. {
  419. DecryptBlock(bufBlock, 0, output, outOff);
  420. Array.Copy(bufBlock, BlockSize, bufBlock, 0, bufOff -= BlockSize);
  421. resultLen = BlockSize;
  422. available += BlockSize;
  423. if (len < available)
  424. {
  425. Array.Copy(input, inOff, bufBlock, bufOff, len);
  426. bufOff += len;
  427. return resultLen;
  428. }
  429. }
  430. int inLimit1 = inOff + len - bufBlock.Length;
  431. int inLimit2 = inLimit1 - BlockSize;
  432. available = BlockSize - bufOff;
  433. Array.Copy(input, inOff, bufBlock, bufOff, available);
  434. DecryptBlock(bufBlock, 0, output, outOff + resultLen);
  435. inOff += available;
  436. resultLen += BlockSize;
  437. //bufOff = 0;
  438. while (inOff <= inLimit2)
  439. {
  440. DecryptBlocks2(input, inOff, output, outOff + resultLen);
  441. inOff += BlockSize * 2;
  442. resultLen += BlockSize * 2;
  443. }
  444. if (inOff <= inLimit1)
  445. {
  446. DecryptBlock(input, inOff, output, outOff + resultLen);
  447. inOff += BlockSize;
  448. resultLen += BlockSize;
  449. }
  450. bufOff = bufBlock.Length + inLimit1 - inOff;
  451. Array.Copy(input, inOff, bufBlock, 0, bufOff);
  452. }
  453. return resultLen;
  454. #endif
  455. }
  456. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  457. public int ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
  458. {
  459. CheckStatus();
  460. int resultLen = 0;
  461. if (forEncryption)
  462. {
  463. if (bufOff > 0)
  464. {
  465. int available = BlockSize - bufOff;
  466. if (input.Length < available)
  467. {
  468. input.CopyTo(bufBlock.AsSpan(bufOff));
  469. bufOff += input.Length;
  470. return 0;
  471. }
  472. input[..available].CopyTo(bufBlock.AsSpan(bufOff));
  473. EncryptBlock(bufBlock, output);
  474. input = input[available..];
  475. resultLen = BlockSize;
  476. //bufOff = 0;
  477. }
  478. while (input.Length >= BlockSize * 2)
  479. {
  480. EncryptBlocks2(input, output[resultLen..]);
  481. input = input[(BlockSize * 2)..];
  482. resultLen += BlockSize * 2;
  483. }
  484. if (input.Length >= BlockSize)
  485. {
  486. EncryptBlock(input, output[resultLen..]);
  487. input = input[BlockSize..];
  488. resultLen += BlockSize;
  489. }
  490. bufOff = input.Length;
  491. input.CopyTo(bufBlock);
  492. }
  493. else
  494. {
  495. int available = bufBlock.Length - bufOff;
  496. if (input.Length < available)
  497. {
  498. input.CopyTo(bufBlock.AsSpan(bufOff));
  499. bufOff += input.Length;
  500. return 0;
  501. }
  502. if (bufOff >= BlockSize)
  503. {
  504. DecryptBlock(bufBlock, output);
  505. Array.Copy(bufBlock, BlockSize, bufBlock, 0, bufOff -= BlockSize);
  506. resultLen = BlockSize;
  507. available += BlockSize;
  508. if (input.Length < available)
  509. {
  510. input.CopyTo(bufBlock.AsSpan(bufOff));
  511. bufOff += input.Length;
  512. return resultLen;
  513. }
  514. }
  515. int inLimit1 = bufBlock.Length;
  516. int inLimit2 = inLimit1 + BlockSize;
  517. available = BlockSize - bufOff;
  518. input[..available].CopyTo(bufBlock.AsSpan(bufOff));
  519. DecryptBlock(bufBlock, output[resultLen..]);
  520. input = input[available..];
  521. resultLen += BlockSize;
  522. //bufOff = 0;
  523. while (input.Length >= inLimit2)
  524. {
  525. DecryptBlocks2(input, output[resultLen..]);
  526. input = input[(BlockSize * 2)..];
  527. resultLen += BlockSize * 2;
  528. }
  529. if (input.Length >= inLimit1)
  530. {
  531. DecryptBlock(input, output[resultLen..]);
  532. input = input[BlockSize..];
  533. resultLen += BlockSize;
  534. }
  535. bufOff = input.Length;
  536. input.CopyTo(bufBlock);
  537. }
  538. return resultLen;
  539. }
  540. #endif
  541. public int DoFinal(byte[] output, int outOff)
  542. {
  543. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  544. return DoFinal(output.AsSpan(outOff));
  545. #else
  546. CheckStatus();
  547. if (totalLength == 0)
  548. {
  549. InitCipher();
  550. }
  551. int extra = bufOff;
  552. if (forEncryption)
  553. {
  554. Check.OutputLength(output, outOff, extra + macSize, "output buffer too short");
  555. }
  556. else
  557. {
  558. if (extra < macSize)
  559. throw new InvalidCipherTextException("data too short");
  560. extra -= macSize;
  561. Check.OutputLength(output, outOff, extra, "output buffer too short");
  562. }
  563. if (extra > 0)
  564. {
  565. ProcessPartial(bufBlock, 0, extra, output, outOff);
  566. }
  567. atLength += (uint)atBlockPos;
  568. if (atLength > atLengthPre)
  569. {
  570. /*
  571. * Some AAD was sent after the cipher started. We determine the difference b/w the hash value
  572. * we actually used when the cipher started (S_atPre) and the final hash value calculated (S_at).
  573. * Then we carry this difference forward by multiplying by H^c, where c is the number of (full or
  574. * partial) cipher-text blocks produced, and adjust the current hash.
  575. */
  576. // Finish hash for partial AAD block
  577. if (atBlockPos > 0)
  578. {
  579. gHASHPartial(S_at, atBlock, 0, atBlockPos);
  580. }
  581. // Find the difference between the AAD hashes
  582. if (atLengthPre > 0)
  583. {
  584. GcmUtilities.Xor(S_at, S_atPre);
  585. }
  586. // Number of cipher-text blocks produced
  587. long c = (long)(((totalLength * 8) + 127) >> 7);
  588. // Calculate the adjustment factor
  589. byte[] H_c = new byte[16];
  590. if (exp == null)
  591. {
  592. exp = new BasicGcmExponentiator();
  593. exp.Init(H);
  594. }
  595. exp.ExponentiateX(c, H_c);
  596. // Carry the difference forward
  597. GcmUtilities.Multiply(S_at, H_c);
  598. // Adjust the current hash
  599. GcmUtilities.Xor(S, S_at);
  600. }
  601. // Final gHASH
  602. byte[] X = new byte[BlockSize];
  603. Pack.UInt64_To_BE(atLength * 8UL, X, 0);
  604. Pack.UInt64_To_BE(totalLength * 8UL, X, 8);
  605. gHASHBlock(S, X);
  606. // T = MSBt(GCTRk(J0,S))
  607. byte[] tag = new byte[BlockSize];
  608. cipher.ProcessBlock(J0, 0, tag, 0);
  609. GcmUtilities.Xor(tag, S);
  610. int resultLen = extra;
  611. // We place into macBlock our calculated value for T
  612. this.macBlock = new byte[macSize];
  613. Array.Copy(tag, 0, macBlock, 0, macSize);
  614. if (forEncryption)
  615. {
  616. // Append T to the message
  617. Array.Copy(macBlock, 0, output, outOff + bufOff, macSize);
  618. resultLen += macSize;
  619. }
  620. else
  621. {
  622. // Retrieve the T value from the message and compare to calculated one
  623. byte[] msgMac = new byte[macSize];
  624. Array.Copy(bufBlock, extra, msgMac, 0, macSize);
  625. if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac))
  626. throw new InvalidCipherTextException("mac check in GCM failed");
  627. }
  628. Reset(false);
  629. return resultLen;
  630. #endif
  631. }
  632. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  633. public int DoFinal(Span<byte> output)
  634. {
  635. CheckStatus();
  636. if (totalLength == 0)
  637. {
  638. InitCipher();
  639. }
  640. int extra = bufOff;
  641. if (forEncryption)
  642. {
  643. Check.OutputLength(output, extra + macSize, "output buffer too short");
  644. }
  645. else
  646. {
  647. if (extra < macSize)
  648. throw new InvalidCipherTextException("data too short");
  649. extra -= macSize;
  650. Check.OutputLength(output, extra, "output buffer too short");
  651. }
  652. if (extra > 0)
  653. {
  654. ProcessPartial(bufBlock.AsSpan(0, extra), output);
  655. }
  656. atLength += (uint)atBlockPos;
  657. if (atLength > atLengthPre)
  658. {
  659. /*
  660. * Some AAD was sent after the cipher started. We determine the difference b/w the hash value
  661. * we actually used when the cipher started (S_atPre) and the final hash value calculated (S_at).
  662. * Then we carry this difference forward by multiplying by H^c, where c is the number of (full or
  663. * partial) cipher-text blocks produced, and adjust the current hash.
  664. */
  665. // Finish hash for partial AAD block
  666. if (atBlockPos > 0)
  667. {
  668. gHASHPartial(S_at, atBlock, 0, atBlockPos);
  669. }
  670. // Find the difference between the AAD hashes
  671. if (atLengthPre > 0)
  672. {
  673. GcmUtilities.Xor(S_at, S_atPre);
  674. }
  675. // Number of cipher-text blocks produced
  676. long c = (long)(((totalLength * 8) + 127) >> 7);
  677. // Calculate the adjustment factor
  678. byte[] H_c = new byte[16];
  679. if (exp == null)
  680. {
  681. exp = new BasicGcmExponentiator();
  682. exp.Init(H);
  683. }
  684. exp.ExponentiateX(c, H_c);
  685. // Carry the difference forward
  686. GcmUtilities.Multiply(S_at, H_c);
  687. // Adjust the current hash
  688. GcmUtilities.Xor(S, S_at);
  689. }
  690. // Final gHASH
  691. Span<byte> X = stackalloc byte[BlockSize];
  692. Pack.UInt64_To_BE(atLength * 8UL, X);
  693. Pack.UInt64_To_BE(totalLength * 8UL, X[8..]);
  694. gHASHBlock(S, X);
  695. // T = MSBt(GCTRk(J0,S))
  696. Span<byte> tag = stackalloc byte[BlockSize];
  697. cipher.ProcessBlock(J0, tag);
  698. GcmUtilities.Xor(tag, S);
  699. int resultLen = extra;
  700. // We place into macBlock our calculated value for T
  701. this.macBlock = new byte[macSize];
  702. tag[..macSize].CopyTo(macBlock);
  703. if (forEncryption)
  704. {
  705. // Append T to the message
  706. macBlock.CopyTo(output[bufOff..]);
  707. resultLen += macSize;
  708. }
  709. else
  710. {
  711. // Retrieve the T value from the message and compare to calculated one
  712. Span<byte> msgMac = stackalloc byte[macSize];
  713. bufBlock.AsSpan(extra, macSize).CopyTo(msgMac);
  714. if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac))
  715. throw new InvalidCipherTextException("mac check in GCM failed");
  716. }
  717. Reset(false);
  718. return resultLen;
  719. }
  720. #endif
  721. public void Reset()
  722. {
  723. Reset(true);
  724. }
  725. private void Reset(bool clearMac)
  726. {
  727. // note: we do not reset the nonce.
  728. S = new byte[BlockSize];
  729. S_at = new byte[BlockSize];
  730. S_atPre = new byte[BlockSize];
  731. atBlock = new byte[BlockSize];
  732. atBlockPos = 0;
  733. atLength = 0;
  734. atLengthPre = 0;
  735. counter = Arrays.Clone(J0);
  736. counter32 = Pack.BE_To_UInt32(counter, 12);
  737. blocksRemaining = uint.MaxValue - 1;
  738. bufOff = 0;
  739. totalLength = 0;
  740. if (bufBlock != null)
  741. {
  742. Arrays.Fill(bufBlock, 0);
  743. }
  744. if (clearMac)
  745. {
  746. macBlock = null;
  747. }
  748. if (forEncryption)
  749. {
  750. initialised = false;
  751. }
  752. else
  753. {
  754. if (initialAssociatedText != null)
  755. {
  756. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  757. }
  758. }
  759. }
  760. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  761. private void DecryptBlock(ReadOnlySpan<byte> input, Span<byte> output)
  762. {
  763. Check.OutputLength(output, BlockSize, "output buffer too short");
  764. if (totalLength == 0)
  765. {
  766. InitCipher();
  767. }
  768. Span<byte> ctrBlock = stackalloc byte[BlockSize];
  769. GetNextCtrBlock(ctrBlock);
  770. #if NETCOREAPP3_0_OR_GREATER
  771. if (Sse2.IsSupported && Unsafe.SizeOf<Vector128<byte>>() == BlockSize)
  772. {
  773. var t0 = MemoryMarshal.Read<Vector128<byte>>(input);
  774. var t1 = MemoryMarshal.Read<Vector128<byte>>(ctrBlock);
  775. var t2 = MemoryMarshal.Read<Vector128<byte>>(S.AsSpan());
  776. t1 = Sse2.Xor(t1, t0);
  777. t2 = Sse2.Xor(t2, t0);
  778. MemoryMarshal.Write(output, ref t1);
  779. MemoryMarshal.Write(S.AsSpan(), ref t2);
  780. }
  781. else
  782. #endif
  783. {
  784. for (int i = 0; i < BlockSize; i += 4)
  785. {
  786. byte c0 = input[i + 0];
  787. byte c1 = input[i + 1];
  788. byte c2 = input[i + 2];
  789. byte c3 = input[i + 3];
  790. S[i + 0] ^= c0;
  791. S[i + 1] ^= c1;
  792. S[i + 2] ^= c2;
  793. S[i + 3] ^= c3;
  794. output[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]);
  795. output[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]);
  796. output[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]);
  797. output[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]);
  798. }
  799. }
  800. multiplier.MultiplyH(S);
  801. totalLength += BlockSize;
  802. }
  803. private void DecryptBlocks2(ReadOnlySpan<byte> input, Span<byte> output)
  804. {
  805. Check.OutputLength(output, BlockSize * 2, "output buffer too short");
  806. if (totalLength == 0)
  807. {
  808. InitCipher();
  809. }
  810. Span<byte> ctrBlock = stackalloc byte[BlockSize];
  811. GetNextCtrBlock(ctrBlock);
  812. #if NETCOREAPP3_0_OR_GREATER
  813. if (Sse2.IsSupported && Unsafe.SizeOf<Vector128<byte>>() == BlockSize)
  814. {
  815. var t0 = MemoryMarshal.Read<Vector128<byte>>(input);
  816. var t1 = MemoryMarshal.Read<Vector128<byte>>(ctrBlock);
  817. var t2 = MemoryMarshal.Read<Vector128<byte>>(S.AsSpan());
  818. t1 = Sse2.Xor(t1, t0);
  819. t2 = Sse2.Xor(t2, t0);
  820. MemoryMarshal.Write(output, ref t1);
  821. MemoryMarshal.Write(S.AsSpan(), ref t2);
  822. }
  823. else
  824. #endif
  825. {
  826. for (int i = 0; i < BlockSize; i += 4)
  827. {
  828. byte c0 = input[i + 0];
  829. byte c1 = input[i + 1];
  830. byte c2 = input[i + 2];
  831. byte c3 = input[i + 3];
  832. S[i + 0] ^= c0;
  833. S[i + 1] ^= c1;
  834. S[i + 2] ^= c2;
  835. S[i + 3] ^= c3;
  836. output[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]);
  837. output[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]);
  838. output[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]);
  839. output[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]);
  840. }
  841. }
  842. multiplier.MultiplyH(S);
  843. input = input[BlockSize..];
  844. output = output[BlockSize..];
  845. GetNextCtrBlock(ctrBlock);
  846. #if NETCOREAPP3_0_OR_GREATER
  847. if (Sse2.IsSupported && Unsafe.SizeOf<Vector128<byte>>() == BlockSize)
  848. {
  849. var t0 = MemoryMarshal.Read<Vector128<byte>>(input);
  850. var t1 = MemoryMarshal.Read<Vector128<byte>>(ctrBlock);
  851. var t2 = MemoryMarshal.Read<Vector128<byte>>(S.AsSpan());
  852. t1 = Sse2.Xor(t1, t0);
  853. t2 = Sse2.Xor(t2, t0);
  854. MemoryMarshal.Write(output, ref t1);
  855. MemoryMarshal.Write(S.AsSpan(), ref t2);
  856. }
  857. else
  858. #endif
  859. {
  860. for (int i = 0; i < BlockSize; i += 4)
  861. {
  862. byte c0 = input[i + 0];
  863. byte c1 = input[i + 1];
  864. byte c2 = input[i + 2];
  865. byte c3 = input[i + 3];
  866. S[i + 0] ^= c0;
  867. S[i + 1] ^= c1;
  868. S[i + 2] ^= c2;
  869. S[i + 3] ^= c3;
  870. output[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]);
  871. output[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]);
  872. output[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]);
  873. output[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]);
  874. }
  875. }
  876. multiplier.MultiplyH(S);
  877. totalLength += BlockSize * 2;
  878. }
  879. private void EncryptBlock(ReadOnlySpan<byte> input, Span<byte> output)
  880. {
  881. Check.OutputLength(output, BlockSize, "output buffer too short");
  882. if (totalLength == 0)
  883. {
  884. InitCipher();
  885. }
  886. Span<byte> ctrBlock = stackalloc byte[BlockSize];
  887. GetNextCtrBlock(ctrBlock);
  888. #if NETCOREAPP3_0_OR_GREATER
  889. if (Sse2.IsSupported && Unsafe.SizeOf<Vector128<byte>>() == BlockSize)
  890. {
  891. var t0 = MemoryMarshal.Read<Vector128<byte>>(input);
  892. var t1 = MemoryMarshal.Read<Vector128<byte>>(ctrBlock);
  893. var t2 = MemoryMarshal.Read<Vector128<byte>>(S.AsSpan());
  894. t1 = Sse2.Xor(t1, t0);
  895. t2 = Sse2.Xor(t2, t1);
  896. MemoryMarshal.Write(output, ref t1);
  897. MemoryMarshal.Write(S.AsSpan(), ref t2);
  898. }
  899. else
  900. #endif
  901. {
  902. for (int i = 0; i < BlockSize; i += 4)
  903. {
  904. byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]);
  905. byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]);
  906. byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]);
  907. byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]);
  908. S[i + 0] ^= c0;
  909. S[i + 1] ^= c1;
  910. S[i + 2] ^= c2;
  911. S[i + 3] ^= c3;
  912. output[i + 0] = c0;
  913. output[i + 1] = c1;
  914. output[i + 2] = c2;
  915. output[i + 3] = c3;
  916. }
  917. }
  918. multiplier.MultiplyH(S);
  919. totalLength += BlockSize;
  920. }
  921. private void EncryptBlocks2(ReadOnlySpan<byte> input, Span<byte> output)
  922. {
  923. Check.OutputLength(output, BlockSize * 2, "Output buffer too short");
  924. if (totalLength == 0)
  925. {
  926. InitCipher();
  927. }
  928. Span<byte> ctrBlock = stackalloc byte[BlockSize];
  929. GetNextCtrBlock(ctrBlock);
  930. #if NETCOREAPP3_0_OR_GREATER
  931. if (Sse2.IsSupported && Unsafe.SizeOf<Vector128<byte>>() == BlockSize)
  932. {
  933. var t0 = MemoryMarshal.Read<Vector128<byte>>(input);
  934. var t1 = MemoryMarshal.Read<Vector128<byte>>(ctrBlock);
  935. var t2 = MemoryMarshal.Read<Vector128<byte>>(S.AsSpan());
  936. t1 = Sse2.Xor(t1, t0);
  937. t2 = Sse2.Xor(t2, t1);
  938. MemoryMarshal.Write(output, ref t1);
  939. MemoryMarshal.Write(S.AsSpan(), ref t2);
  940. }
  941. else
  942. #endif
  943. {
  944. for (int i = 0; i < BlockSize; i += 4)
  945. {
  946. byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]);
  947. byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]);
  948. byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]);
  949. byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]);
  950. S[i + 0] ^= c0;
  951. S[i + 1] ^= c1;
  952. S[i + 2] ^= c2;
  953. S[i + 3] ^= c3;
  954. output[i + 0] = c0;
  955. output[i + 1] = c1;
  956. output[i + 2] = c2;
  957. output[i + 3] = c3;
  958. }
  959. }
  960. multiplier.MultiplyH(S);
  961. input = input[BlockSize..];
  962. output = output[BlockSize..];
  963. GetNextCtrBlock(ctrBlock);
  964. #if NETCOREAPP3_0_OR_GREATER
  965. if (Sse2.IsSupported && Unsafe.SizeOf<Vector128<byte>>() == BlockSize)
  966. {
  967. var t0 = MemoryMarshal.Read<Vector128<byte>>(input);
  968. var t1 = MemoryMarshal.Read<Vector128<byte>>(ctrBlock);
  969. var t2 = MemoryMarshal.Read<Vector128<byte>>(S.AsSpan());
  970. t1 = Sse2.Xor(t1, t0);
  971. t2 = Sse2.Xor(t2, t1);
  972. MemoryMarshal.Write(output, ref t1);
  973. MemoryMarshal.Write(S.AsSpan(), ref t2);
  974. }
  975. else
  976. #endif
  977. {
  978. for (int i = 0; i < BlockSize; i += 4)
  979. {
  980. byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]);
  981. byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]);
  982. byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]);
  983. byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]);
  984. S[i + 0] ^= c0;
  985. S[i + 1] ^= c1;
  986. S[i + 2] ^= c2;
  987. S[i + 3] ^= c3;
  988. output[i + 0] = c0;
  989. output[i + 1] = c1;
  990. output[i + 2] = c2;
  991. output[i + 3] = c3;
  992. }
  993. }
  994. multiplier.MultiplyH(S);
  995. totalLength += BlockSize * 2;
  996. }
  997. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  998. private void GetNextCtrBlock(Span<byte> block)
  999. {
  1000. if (blocksRemaining == 0)
  1001. throw new InvalidOperationException("Attempt to process too many blocks");
  1002. blocksRemaining--;
  1003. Pack.UInt32_To_BE(++counter32, counter, 12);
  1004. cipher.ProcessBlock(counter, block);
  1005. }
  1006. private void ProcessPartial(Span<byte> partialBlock, Span<byte> output)
  1007. {
  1008. Span<byte> ctrBlock = stackalloc byte[BlockSize];
  1009. GetNextCtrBlock(ctrBlock);
  1010. if (forEncryption)
  1011. {
  1012. GcmUtilities.Xor(partialBlock, ctrBlock, partialBlock.Length);
  1013. gHASHPartial(S, partialBlock);
  1014. }
  1015. else
  1016. {
  1017. gHASHPartial(S, partialBlock);
  1018. GcmUtilities.Xor(partialBlock, ctrBlock, partialBlock.Length);
  1019. }
  1020. partialBlock.CopyTo(output);
  1021. totalLength += (uint)partialBlock.Length;
  1022. }
  1023. #else
  1024. private void DecryptBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff)
  1025. {
  1026. Check.OutputLength(outBuf, outOff, BlockSize, "Output buffer too short");
  1027. if (totalLength == 0)
  1028. {
  1029. InitCipher();
  1030. }
  1031. //byte[] ctrBlock = new byte[BlockSize];
  1032. GetNextCtrBlock(ctrBlock);
  1033. {
  1034. for (int i = 0; i < BlockSize; i += 4)
  1035. {
  1036. byte c0 = inBuf[inOff + i + 0];
  1037. byte c1 = inBuf[inOff + i + 1];
  1038. byte c2 = inBuf[inOff + i + 2];
  1039. byte c3 = inBuf[inOff + i + 3];
  1040. S[i + 0] ^= c0;
  1041. S[i + 1] ^= c1;
  1042. S[i + 2] ^= c2;
  1043. S[i + 3] ^= c3;
  1044. outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]);
  1045. outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]);
  1046. outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]);
  1047. outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]);
  1048. }
  1049. }
  1050. multiplier.MultiplyH(S);
  1051. totalLength += BlockSize;
  1052. }
  1053. private void DecryptBlocks2(byte[] inBuf, int inOff, byte[] outBuf, int outOff)
  1054. {
  1055. Check.OutputLength(outBuf, outOff, BlockSize * 2, "Output buffer too short");
  1056. if (totalLength == 0)
  1057. {
  1058. InitCipher();
  1059. }
  1060. //byte[] ctrBlock = new byte[BlockSize];
  1061. GetNextCtrBlock(ctrBlock);
  1062. {
  1063. for (int i = 0; i < BlockSize; i += 4)
  1064. {
  1065. byte c0 = inBuf[inOff + i + 0];
  1066. byte c1 = inBuf[inOff + i + 1];
  1067. byte c2 = inBuf[inOff + i + 2];
  1068. byte c3 = inBuf[inOff + i + 3];
  1069. S[i + 0] ^= c0;
  1070. S[i + 1] ^= c1;
  1071. S[i + 2] ^= c2;
  1072. S[i + 3] ^= c3;
  1073. outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]);
  1074. outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]);
  1075. outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]);
  1076. outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]);
  1077. }
  1078. }
  1079. multiplier.MultiplyH(S);
  1080. inOff += BlockSize;
  1081. outOff += BlockSize;
  1082. GetNextCtrBlock(ctrBlock);
  1083. {
  1084. for (int i = 0; i < BlockSize; i += 4)
  1085. {
  1086. byte c0 = inBuf[inOff + i + 0];
  1087. byte c1 = inBuf[inOff + i + 1];
  1088. byte c2 = inBuf[inOff + i + 2];
  1089. byte c3 = inBuf[inOff + i + 3];
  1090. S[i + 0] ^= c0;
  1091. S[i + 1] ^= c1;
  1092. S[i + 2] ^= c2;
  1093. S[i + 3] ^= c3;
  1094. outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]);
  1095. outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]);
  1096. outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]);
  1097. outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]);
  1098. }
  1099. }
  1100. multiplier.MultiplyH(S);
  1101. totalLength += BlockSize * 2;
  1102. }
  1103. private void EncryptBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff)
  1104. {
  1105. Check.OutputLength(outBuf, outOff, BlockSize, "Output buffer too short");
  1106. if (totalLength == 0)
  1107. {
  1108. InitCipher();
  1109. }
  1110. //byte[] ctrBlock = new byte[BlockSize];
  1111. GetNextCtrBlock(ctrBlock);
  1112. {
  1113. for (int i = 0; i < BlockSize; i += 4)
  1114. {
  1115. byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]);
  1116. byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]);
  1117. byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]);
  1118. byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]);
  1119. S[i + 0] ^= c0;
  1120. S[i + 1] ^= c1;
  1121. S[i + 2] ^= c2;
  1122. S[i + 3] ^= c3;
  1123. outBuf[outOff + i + 0] = c0;
  1124. outBuf[outOff + i + 1] = c1;
  1125. outBuf[outOff + i + 2] = c2;
  1126. outBuf[outOff + i + 3] = c3;
  1127. }
  1128. }
  1129. multiplier.MultiplyH(S);
  1130. totalLength += BlockSize;
  1131. }
  1132. private void EncryptBlocks2(byte[] inBuf, int inOff, byte[] outBuf, int outOff)
  1133. {
  1134. Check.OutputLength(outBuf, outOff, BlockSize * 2, "Output buffer too short");
  1135. if (totalLength == 0)
  1136. {
  1137. InitCipher();
  1138. }
  1139. //byte[] ctrBlock = new byte[BlockSize];
  1140. GetNextCtrBlock(ctrBlock);
  1141. {
  1142. for (int i = 0; i < BlockSize; i += 4)
  1143. {
  1144. byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]);
  1145. byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]);
  1146. byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]);
  1147. byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]);
  1148. S[i + 0] ^= c0;
  1149. S[i + 1] ^= c1;
  1150. S[i + 2] ^= c2;
  1151. S[i + 3] ^= c3;
  1152. outBuf[outOff + i + 0] = c0;
  1153. outBuf[outOff + i + 1] = c1;
  1154. outBuf[outOff + i + 2] = c2;
  1155. outBuf[outOff + i + 3] = c3;
  1156. }
  1157. }
  1158. multiplier.MultiplyH(S);
  1159. inOff += BlockSize;
  1160. outOff += BlockSize;
  1161. GetNextCtrBlock(ctrBlock);
  1162. {
  1163. for (int i = 0; i < BlockSize; i += 4)
  1164. {
  1165. byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]);
  1166. byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]);
  1167. byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]);
  1168. byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]);
  1169. S[i + 0] ^= c0;
  1170. S[i + 1] ^= c1;
  1171. S[i + 2] ^= c2;
  1172. S[i + 3] ^= c3;
  1173. outBuf[outOff + i + 0] = c0;
  1174. outBuf[outOff + i + 1] = c1;
  1175. outBuf[outOff + i + 2] = c2;
  1176. outBuf[outOff + i + 3] = c3;
  1177. }
  1178. }
  1179. multiplier.MultiplyH(S);
  1180. totalLength += BlockSize * 2;
  1181. }
  1182. private void GetNextCtrBlock(byte[] block)
  1183. {
  1184. if (blocksRemaining == 0)
  1185. throw new InvalidOperationException("Attempt to process too many blocks");
  1186. blocksRemaining--;
  1187. Pack.UInt32_To_BE(++counter32, counter, 12);
  1188. cipher.ProcessBlock(counter, 0, block, 0);
  1189. }
  1190. private void ProcessPartial(byte[] buf, int off, int len, byte[] output, int outOff)
  1191. {
  1192. //byte[] ctrBlock = new byte[BlockSize];
  1193. GetNextCtrBlock(ctrBlock);
  1194. if (forEncryption)
  1195. {
  1196. GcmUtilities.Xor(buf, off, ctrBlock, 0, len);
  1197. gHASHPartial(S, buf, off, len);
  1198. }
  1199. else
  1200. {
  1201. gHASHPartial(S, buf, off, len);
  1202. GcmUtilities.Xor(buf, off, ctrBlock, 0, len);
  1203. }
  1204. Array.Copy(buf, off, output, outOff, len);
  1205. totalLength += (uint)len;
  1206. }
  1207. #endif
  1208. private void gHASH(byte[] Y, byte[] b, int len)
  1209. {
  1210. for (int pos = 0; pos < len; pos += BlockSize)
  1211. {
  1212. int num = System.Math.Min(len - pos, BlockSize);
  1213. gHASHPartial(Y, b, pos, num);
  1214. }
  1215. }
  1216. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_
  1217. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1218. private void gHASHBlock(byte[] Y, ReadOnlySpan<byte> b)
  1219. {
  1220. GcmUtilities.Xor(Y, b);
  1221. multiplier.MultiplyH(Y);
  1222. }
  1223. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1224. private void gHASHPartial(byte[] Y, ReadOnlySpan<byte> b)
  1225. {
  1226. GcmUtilities.Xor(Y, b, b.Length);
  1227. multiplier.MultiplyH(Y);
  1228. }
  1229. #else
  1230. private void gHASHBlock(byte[] Y, byte[] b)
  1231. {
  1232. GcmUtilities.Xor(Y, b);
  1233. multiplier.MultiplyH(Y);
  1234. }
  1235. private void gHASHBlock(byte[] Y, byte[] b, int off)
  1236. {
  1237. GcmUtilities.Xor(Y, b, off);
  1238. multiplier.MultiplyH(Y);
  1239. }
  1240. #endif
  1241. private void gHASHPartial(byte[] Y, byte[] b, int off, int len)
  1242. {
  1243. GcmUtilities.Xor(Y, b, off, len);
  1244. multiplier.MultiplyH(Y);
  1245. }
  1246. private void CheckStatus()
  1247. {
  1248. if (!initialised)
  1249. {
  1250. if (forEncryption)
  1251. {
  1252. throw new InvalidOperationException("GCM cipher cannot be reused for encryption");
  1253. }
  1254. throw new InvalidOperationException("GCM cipher needs to be initialised");
  1255. }
  1256. }
  1257. }
  1258. }
  1259. #pragma warning restore
  1260. #endif