OCBBlockCipher.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections.Generic;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  7. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
  8. {
  9. /// <summary>An implementation of <a href="https://tools.ietf.org/html/rfc7253">RFC 7253 on The OCB
  10. /// Authenticated-Encryption Algorithm</a>.</summary>
  11. /// <remarks>
  12. /// For those still concerned about the original patents around this, please see:
  13. /// <para>https://mailarchive.ietf.org/arch/msg/cfrg/qLTveWOdTJcLn4HP3ev-vrj05Vg/</para>
  14. /// Text reproduced below:
  15. /// <para>
  16. /// Phillip Rogaway&lt;rogaway@cs.ucdavis.edu&gt; Sat, 27 February 2021 02:46 UTC
  17. ///
  18. /// I can confirm that I have abandoned all OCB patents and placed into the public domain all OCB-related IP of
  19. /// mine. While I have been telling people this for quite some time, I don't think I ever made a proper announcement
  20. /// to the CFRG or on the OCB webpage. Consider that done.
  21. /// </para>
  22. /// </remarks>
  23. public class OcbBlockCipher
  24. : IAeadBlockCipher
  25. {
  26. private const int BLOCK_SIZE = 16;
  27. private readonly IBlockCipher hashCipher;
  28. private readonly IBlockCipher mainCipher;
  29. /*
  30. * CONFIGURATION
  31. */
  32. private bool forEncryption;
  33. private int macSize;
  34. private byte[] initialAssociatedText;
  35. /*
  36. * KEY-DEPENDENT
  37. */
  38. // NOTE: elements are lazily calculated
  39. private IList<byte[]> L;
  40. private byte[] L_Asterisk, L_Dollar;
  41. /*
  42. * NONCE-DEPENDENT
  43. */
  44. private byte[] KtopInput = null;
  45. private byte[] Stretch = new byte[24];
  46. private byte[] OffsetMAIN_0 = new byte[16];
  47. /*
  48. * PER-ENCRYPTION/DECRYPTION
  49. */
  50. private byte[] hashBlock, mainBlock;
  51. private int hashBlockPos, mainBlockPos;
  52. private long hashBlockCount, mainBlockCount;
  53. private byte[] OffsetHASH;
  54. private byte[] Sum;
  55. private byte[] OffsetMAIN = new byte[16];
  56. private byte[] Checksum;
  57. // NOTE: The MAC value is preserved after doFinal
  58. private byte[] macBlock;
  59. public OcbBlockCipher(IBlockCipher hashCipher, IBlockCipher mainCipher)
  60. {
  61. if (hashCipher == null)
  62. throw new ArgumentNullException("hashCipher");
  63. if (hashCipher.GetBlockSize() != BLOCK_SIZE)
  64. throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "hashCipher");
  65. if (mainCipher == null)
  66. throw new ArgumentNullException("mainCipher");
  67. if (mainCipher.GetBlockSize() != BLOCK_SIZE)
  68. throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "mainCipher");
  69. if (!hashCipher.AlgorithmName.Equals(mainCipher.AlgorithmName))
  70. throw new ArgumentException("'hashCipher' and 'mainCipher' must be the same algorithm");
  71. this.hashCipher = hashCipher;
  72. this.mainCipher = mainCipher;
  73. }
  74. public virtual string AlgorithmName => mainCipher.AlgorithmName + "/OCB";
  75. public virtual IBlockCipher UnderlyingCipher => mainCipher;
  76. public virtual void Init(bool forEncryption, ICipherParameters parameters)
  77. {
  78. bool oldForEncryption = this.forEncryption;
  79. this.forEncryption = forEncryption;
  80. this.macBlock = null;
  81. KeyParameter keyParameter;
  82. byte[] N;
  83. if (parameters is AeadParameters aeadParameters)
  84. {
  85. N = aeadParameters.GetNonce();
  86. initialAssociatedText = aeadParameters.GetAssociatedText();
  87. int macSizeBits = aeadParameters.MacSize;
  88. if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0)
  89. throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
  90. macSize = macSizeBits / 8;
  91. keyParameter = aeadParameters.Key;
  92. }
  93. else if (parameters is ParametersWithIV parametersWithIV)
  94. {
  95. N = parametersWithIV.GetIV();
  96. initialAssociatedText = null;
  97. macSize = 16;
  98. keyParameter = (KeyParameter) parametersWithIV.Parameters;
  99. }
  100. else
  101. {
  102. throw new ArgumentException("invalid parameters passed to OCB");
  103. }
  104. this.hashBlock = new byte[16];
  105. this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];
  106. if (N == null)
  107. {
  108. N = new byte[0];
  109. }
  110. if (N.Length > 15)
  111. {
  112. throw new ArgumentException("IV must be no more than 15 bytes");
  113. }
  114. /*
  115. * KEY-DEPENDENT INITIALISATION
  116. */
  117. if (keyParameter != null)
  118. {
  119. // hashCipher always used in forward mode
  120. hashCipher.Init(true, keyParameter);
  121. mainCipher.Init(forEncryption, keyParameter);
  122. KtopInput = null;
  123. }
  124. else if (oldForEncryption != forEncryption)
  125. {
  126. throw new ArgumentException("cannot change encrypting state without providing key.");
  127. }
  128. this.L_Asterisk = new byte[16];
  129. hashCipher.ProcessBlock(L_Asterisk, 0, L_Asterisk, 0);
  130. this.L_Dollar = OCB_double(L_Asterisk);
  131. this.L = new List<byte[]>();
  132. this.L.Add(OCB_double(L_Dollar));
  133. /*
  134. * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
  135. */
  136. int bottom = ProcessNonce(N);
  137. int bits = bottom % 8, bytes = bottom / 8;
  138. if (bits == 0)
  139. {
  140. Array.Copy(Stretch, bytes, OffsetMAIN_0, 0, 16);
  141. }
  142. else
  143. {
  144. for (int i = 0; i < 16; ++i)
  145. {
  146. uint b1 = Stretch[bytes];
  147. uint b2 = Stretch[++bytes];
  148. this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >> (8 - bits)));
  149. }
  150. }
  151. this.hashBlockPos = 0;
  152. this.mainBlockPos = 0;
  153. this.hashBlockCount = 0;
  154. this.mainBlockCount = 0;
  155. this.OffsetHASH = new byte[16];
  156. this.Sum = new byte[16];
  157. Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
  158. this.Checksum = new byte[16];
  159. if (initialAssociatedText != null)
  160. {
  161. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  162. }
  163. }
  164. protected virtual int ProcessNonce(byte[] N)
  165. {
  166. byte[] nonce = new byte[16];
  167. Array.Copy(N, 0, nonce, nonce.Length - N.Length, N.Length);
  168. nonce[0] = (byte)(macSize << 4);
  169. nonce[15 - N.Length] |= 1;
  170. int bottom = nonce[15] & 0x3F;
  171. nonce[15] &= 0xC0;
  172. /*
  173. * When used with incrementing nonces, the cipher is only applied once every 64 inits.
  174. */
  175. if (KtopInput == null || !Arrays.AreEqual(nonce, KtopInput))
  176. {
  177. byte[] Ktop = new byte[16];
  178. KtopInput = nonce;
  179. hashCipher.ProcessBlock(KtopInput, 0, Ktop, 0);
  180. Array.Copy(Ktop, 0, Stretch, 0, 16);
  181. for (int i = 0; i < 8; ++i)
  182. {
  183. Stretch[16 + i] = (byte)(Ktop[i] ^ Ktop[i + 1]);
  184. }
  185. }
  186. return bottom;
  187. }
  188. public virtual int GetBlockSize()
  189. {
  190. return BLOCK_SIZE;
  191. }
  192. public virtual byte[] GetMac()
  193. {
  194. return macBlock == null
  195. ? new byte[macSize]
  196. : Arrays.Clone(macBlock);
  197. }
  198. public virtual int GetOutputSize(int len)
  199. {
  200. int totalData = len + mainBlockPos;
  201. if (forEncryption)
  202. {
  203. return totalData + macSize;
  204. }
  205. return totalData < macSize ? 0 : totalData - macSize;
  206. }
  207. public virtual int GetUpdateOutputSize(int len)
  208. {
  209. int totalData = len + mainBlockPos;
  210. if (!forEncryption)
  211. {
  212. if (totalData < macSize)
  213. {
  214. return 0;
  215. }
  216. totalData -= macSize;
  217. }
  218. return totalData - totalData % BLOCK_SIZE;
  219. }
  220. public virtual void ProcessAadByte(byte input)
  221. {
  222. hashBlock[hashBlockPos] = input;
  223. if (++hashBlockPos == hashBlock.Length)
  224. {
  225. ProcessHashBlock();
  226. }
  227. }
  228. public virtual void ProcessAadBytes(byte[] input, int off, int len)
  229. {
  230. for (int i = 0; i < len; ++i)
  231. {
  232. hashBlock[hashBlockPos] = input[off + i];
  233. if (++hashBlockPos == hashBlock.Length)
  234. {
  235. ProcessHashBlock();
  236. }
  237. }
  238. }
  239. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  240. public virtual void ProcessAadBytes(ReadOnlySpan<byte> input)
  241. {
  242. for (int i = 0; i < input.Length; ++i)
  243. {
  244. hashBlock[hashBlockPos] = input[i];
  245. if (++hashBlockPos == hashBlock.Length)
  246. {
  247. ProcessHashBlock();
  248. }
  249. }
  250. }
  251. #endif
  252. public virtual int ProcessByte(byte input, byte[] output, int outOff)
  253. {
  254. mainBlock[mainBlockPos] = input;
  255. if (++mainBlockPos == mainBlock.Length)
  256. {
  257. ProcessMainBlock(output, outOff);
  258. return BLOCK_SIZE;
  259. }
  260. return 0;
  261. }
  262. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  263. public virtual int ProcessByte(byte input, Span<byte> output)
  264. {
  265. mainBlock[mainBlockPos] = input;
  266. if (++mainBlockPos == mainBlock.Length)
  267. {
  268. ProcessMainBlock(output);
  269. return BLOCK_SIZE;
  270. }
  271. return 0;
  272. }
  273. #endif
  274. public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
  275. {
  276. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  277. return ProcessBytes(input.AsSpan(inOff, len), Spans.FromNullable(output, outOff));
  278. #else
  279. int resultLen = 0;
  280. for (int i = 0; i < len; ++i)
  281. {
  282. mainBlock[mainBlockPos] = input[inOff + i];
  283. if (++mainBlockPos == mainBlock.Length)
  284. {
  285. ProcessMainBlock(output, outOff + resultLen);
  286. resultLen += BLOCK_SIZE;
  287. }
  288. }
  289. return resultLen;
  290. #endif
  291. }
  292. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  293. public virtual int ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
  294. {
  295. int len = input.Length;
  296. int resultLen = 0;
  297. for (int i = 0; i < len; ++i)
  298. {
  299. mainBlock[mainBlockPos] = input[i];
  300. if (++mainBlockPos == mainBlock.Length)
  301. {
  302. ProcessMainBlock(output[resultLen..]);
  303. resultLen += BLOCK_SIZE;
  304. }
  305. }
  306. return resultLen;
  307. }
  308. #endif
  309. public virtual int DoFinal(byte[] output, int outOff)
  310. {
  311. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  312. return DoFinal(output.AsSpan(outOff));
  313. #else
  314. /*
  315. * For decryption, get the tag from the end of the message
  316. */
  317. byte[] tag = null;
  318. if (!forEncryption) {
  319. if (mainBlockPos < macSize)
  320. throw new InvalidCipherTextException("data too short");
  321. mainBlockPos -= macSize;
  322. tag = new byte[macSize];
  323. Array.Copy(mainBlock, mainBlockPos, tag, 0, macSize);
  324. }
  325. /*
  326. * HASH: Process any final partial block; compute final hash value
  327. */
  328. if (hashBlockPos > 0)
  329. {
  330. OCB_extend(hashBlock, hashBlockPos);
  331. UpdateHASH(L_Asterisk);
  332. }
  333. /*
  334. * OCB-ENCRYPT/OCB-DECRYPT: Process any final partial block
  335. */
  336. if (mainBlockPos > 0)
  337. {
  338. if (forEncryption)
  339. {
  340. OCB_extend(mainBlock, mainBlockPos);
  341. Xor(Checksum, mainBlock);
  342. }
  343. Xor(OffsetMAIN, L_Asterisk);
  344. byte[] Pad = new byte[16];
  345. hashCipher.ProcessBlock(OffsetMAIN, 0, Pad, 0);
  346. Xor(mainBlock, Pad);
  347. Check.OutputLength(output, outOff, mainBlockPos, "output buffer too short");
  348. Array.Copy(mainBlock, 0, output, outOff, mainBlockPos);
  349. if (!forEncryption)
  350. {
  351. OCB_extend(mainBlock, mainBlockPos);
  352. Xor(Checksum, mainBlock);
  353. }
  354. }
  355. /*
  356. * OCB-ENCRYPT/OCB-DECRYPT: Compute raw tag
  357. */
  358. Xor(Checksum, OffsetMAIN);
  359. Xor(Checksum, L_Dollar);
  360. hashCipher.ProcessBlock(Checksum, 0, Checksum, 0);
  361. Xor(Checksum, Sum);
  362. this.macBlock = new byte[macSize];
  363. Array.Copy(Checksum, 0, macBlock, 0, macSize);
  364. /*
  365. * Validate or append tag and reset this cipher for the next run
  366. */
  367. int resultLen = mainBlockPos;
  368. if (forEncryption)
  369. {
  370. Check.OutputLength(output, outOff, resultLen + macSize, "output buffer too short");
  371. // Append tag to the message
  372. Array.Copy(macBlock, 0, output, outOff + resultLen, macSize);
  373. resultLen += macSize;
  374. }
  375. else
  376. {
  377. // Compare the tag from the message with the calculated one
  378. if (!Arrays.ConstantTimeAreEqual(macBlock, tag))
  379. throw new InvalidCipherTextException("mac check in OCB failed");
  380. }
  381. Reset(false);
  382. return resultLen;
  383. #endif
  384. }
  385. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  386. public virtual int DoFinal(Span<byte> output)
  387. {
  388. /*
  389. * For decryption, get the tag from the end of the message
  390. */
  391. byte[] tag = null;
  392. if (!forEncryption)
  393. {
  394. if (mainBlockPos < macSize)
  395. throw new InvalidCipherTextException("data too short");
  396. mainBlockPos -= macSize;
  397. tag = new byte[macSize];
  398. Array.Copy(mainBlock, mainBlockPos, tag, 0, macSize);
  399. }
  400. /*
  401. * HASH: Process any final partial block; compute final hash value
  402. */
  403. if (hashBlockPos > 0)
  404. {
  405. OCB_extend(hashBlock, hashBlockPos);
  406. UpdateHASH(L_Asterisk);
  407. }
  408. /*
  409. * OCB-ENCRYPT/OCB-DECRYPT: Process any final partial block
  410. */
  411. if (mainBlockPos > 0)
  412. {
  413. if (forEncryption)
  414. {
  415. OCB_extend(mainBlock, mainBlockPos);
  416. Xor(Checksum, mainBlock);
  417. }
  418. Xor(OffsetMAIN, L_Asterisk);
  419. byte[] Pad = new byte[16];
  420. hashCipher.ProcessBlock(OffsetMAIN, 0, Pad, 0);
  421. Xor(mainBlock, Pad);
  422. Check.OutputLength(output, mainBlockPos, "output buffer too short");
  423. mainBlock.AsSpan(0, mainBlockPos).CopyTo(output);
  424. if (!forEncryption)
  425. {
  426. OCB_extend(mainBlock, mainBlockPos);
  427. Xor(Checksum, mainBlock);
  428. }
  429. }
  430. /*
  431. * OCB-ENCRYPT/OCB-DECRYPT: Compute raw tag
  432. */
  433. Xor(Checksum, OffsetMAIN);
  434. Xor(Checksum, L_Dollar);
  435. hashCipher.ProcessBlock(Checksum, 0, Checksum, 0);
  436. Xor(Checksum, Sum);
  437. this.macBlock = new byte[macSize];
  438. Array.Copy(Checksum, 0, macBlock, 0, macSize);
  439. /*
  440. * Validate or append tag and reset this cipher for the next run
  441. */
  442. int resultLen = mainBlockPos;
  443. if (forEncryption)
  444. {
  445. // Append tag to the message
  446. Check.OutputLength(output, resultLen + macSize, "output buffer too short");
  447. macBlock.AsSpan(0, macSize).CopyTo(output[resultLen..]);
  448. resultLen += macSize;
  449. }
  450. else
  451. {
  452. // Compare the tag from the message with the calculated one
  453. if (!Arrays.ConstantTimeAreEqual(macBlock, tag))
  454. throw new InvalidCipherTextException("mac check in OCB failed");
  455. }
  456. Reset(false);
  457. return resultLen;
  458. }
  459. #endif
  460. public virtual void Reset()
  461. {
  462. Reset(true);
  463. }
  464. protected virtual void Clear(byte[] bs)
  465. {
  466. if (bs != null)
  467. {
  468. Array.Clear(bs, 0, bs.Length);
  469. }
  470. }
  471. protected virtual byte[] GetLSub(int n)
  472. {
  473. while (n >= L.Count)
  474. {
  475. L.Add(OCB_double(L[L.Count - 1]));
  476. }
  477. return L[n];
  478. }
  479. protected virtual void ProcessHashBlock()
  480. {
  481. /*
  482. * HASH: Process any whole blocks
  483. */
  484. UpdateHASH(GetLSub(OCB_ntz(++hashBlockCount)));
  485. hashBlockPos = 0;
  486. }
  487. protected virtual void ProcessMainBlock(byte[] output, int outOff)
  488. {
  489. Check.DataLength(output, outOff, BLOCK_SIZE, "Output buffer too short");
  490. /*
  491. * OCB-ENCRYPT/OCB-DECRYPT: Process any whole blocks
  492. */
  493. if (forEncryption)
  494. {
  495. Xor(Checksum, mainBlock);
  496. mainBlockPos = 0;
  497. }
  498. Xor(OffsetMAIN, GetLSub(OCB_ntz(++mainBlockCount)));
  499. Xor(mainBlock, OffsetMAIN);
  500. mainCipher.ProcessBlock(mainBlock, 0, mainBlock, 0);
  501. Xor(mainBlock, OffsetMAIN);
  502. Array.Copy(mainBlock, 0, output, outOff, 16);
  503. if (!forEncryption)
  504. {
  505. Xor(Checksum, mainBlock);
  506. Array.Copy(mainBlock, BLOCK_SIZE, mainBlock, 0, macSize);
  507. mainBlockPos = macSize;
  508. }
  509. }
  510. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  511. protected virtual void ProcessMainBlock(Span<byte> output)
  512. {
  513. Check.DataLength(output, BLOCK_SIZE, "output buffer too short");
  514. /*
  515. * OCB-ENCRYPT/OCB-DECRYPT: Process any whole blocks
  516. */
  517. if (forEncryption)
  518. {
  519. Xor(Checksum, mainBlock);
  520. mainBlockPos = 0;
  521. }
  522. Xor(OffsetMAIN, GetLSub(OCB_ntz(++mainBlockCount)));
  523. Xor(mainBlock, OffsetMAIN);
  524. mainCipher.ProcessBlock(mainBlock, 0, mainBlock, 0);
  525. Xor(mainBlock, OffsetMAIN);
  526. mainBlock.AsSpan(0, BLOCK_SIZE).CopyTo(output);
  527. if (!forEncryption)
  528. {
  529. Xor(Checksum, mainBlock);
  530. Array.Copy(mainBlock, BLOCK_SIZE, mainBlock, 0, macSize);
  531. mainBlockPos = macSize;
  532. }
  533. }
  534. #endif
  535. protected virtual void Reset(bool clearMac)
  536. {
  537. Clear(hashBlock);
  538. Clear(mainBlock);
  539. hashBlockPos = 0;
  540. mainBlockPos = 0;
  541. hashBlockCount = 0;
  542. mainBlockCount = 0;
  543. Clear(OffsetHASH);
  544. Clear(Sum);
  545. Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
  546. Clear(Checksum);
  547. if (clearMac)
  548. {
  549. macBlock = null;
  550. }
  551. if (initialAssociatedText != null)
  552. {
  553. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  554. }
  555. }
  556. protected virtual void UpdateHASH(byte[] LSub)
  557. {
  558. Xor(OffsetHASH, LSub);
  559. Xor(hashBlock, OffsetHASH);
  560. hashCipher.ProcessBlock(hashBlock, 0, hashBlock, 0);
  561. Xor(Sum, hashBlock);
  562. }
  563. protected static byte[] OCB_double(byte[] block)
  564. {
  565. byte[] result = new byte[16];
  566. int carry = ShiftLeft(block, result);
  567. /*
  568. * NOTE: This construction is an attempt at a constant-time implementation.
  569. */
  570. result[15] ^= (byte)(0x87 >> ((1 - carry) << 3));
  571. return result;
  572. }
  573. protected static void OCB_extend(byte[] block, int pos)
  574. {
  575. block[pos] = (byte) 0x80;
  576. while (++pos < 16)
  577. {
  578. block[pos] = 0;
  579. }
  580. }
  581. protected static int OCB_ntz(long x)
  582. {
  583. if (x == 0)
  584. {
  585. return 64;
  586. }
  587. int n = 0;
  588. ulong ux = (ulong)x;
  589. while ((ux & 1UL) == 0UL)
  590. {
  591. ++n;
  592. ux >>= 1;
  593. }
  594. return n;
  595. }
  596. protected static int ShiftLeft(byte[] block, byte[] output)
  597. {
  598. int i = 16;
  599. uint bit = 0;
  600. while (--i >= 0)
  601. {
  602. uint b = block[i];
  603. output[i] = (byte) ((b << 1) | bit);
  604. bit = (b >> 7) & 1;
  605. }
  606. return (int)bit;
  607. }
  608. protected static void Xor(byte[] block, byte[] val)
  609. {
  610. for (int i = 15; i >= 0; --i)
  611. {
  612. block[i] ^= val[i];
  613. }
  614. }
  615. }
  616. }
  617. #pragma warning restore
  618. #endif