FastGcmBlockCipher.cs 51 KB

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