OCBBlockCipher.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.Collections;
  4. using Org.BouncyCastle.Crypto.Parameters;
  5. using Org.BouncyCastle.Utilities;
  6. namespace Org.BouncyCastle.Crypto.Modes
  7. {
  8. /**
  9. * An implementation of <a href="http://tools.ietf.org/html/rfc7253">RFC 7253 on The OCB
  10. * Authenticated-Encryption Algorithm</a>, licensed per:
  11. *
  12. * <blockquote><p><a href="http://www.cs.ucdavis.edu/~rogaway/ocb/license1.pdf">License for
  13. * Open-Source Software Implementations of OCB</a> (Jan 9, 2013) - 'License 1'<br/>
  14. * Under this license, you are authorized to make, use, and distribute open-source software
  15. * implementations of OCB. This license terminates for you if you sue someone over their open-source
  16. * software implementation of OCB claiming that you have a patent covering their implementation.
  17. * </p><p>
  18. * This is a non-binding summary of a legal document (the link above). The parameters of the license
  19. * are specified in the license document and that document is controlling.</p></blockquote>
  20. */
  21. public class OcbBlockCipher
  22. : IAeadBlockCipher
  23. {
  24. private const int BLOCK_SIZE = 16;
  25. private readonly IBlockCipher hashCipher;
  26. private readonly IBlockCipher mainCipher;
  27. /*
  28. * CONFIGURATION
  29. */
  30. private bool forEncryption;
  31. private int macSize;
  32. private byte[] initialAssociatedText;
  33. /*
  34. * KEY-DEPENDENT
  35. */
  36. // NOTE: elements are lazily calculated
  37. private IList L;
  38. private byte[] L_Asterisk, L_Dollar;
  39. /*
  40. * NONCE-DEPENDENT
  41. */
  42. private byte[] KtopInput = null;
  43. private byte[] Stretch = new byte[24];
  44. private byte[] OffsetMAIN_0 = new byte[16];
  45. /*
  46. * PER-ENCRYPTION/DECRYPTION
  47. */
  48. private byte[] hashBlock, mainBlock;
  49. private int hashBlockPos, mainBlockPos;
  50. private long hashBlockCount, mainBlockCount;
  51. private byte[] OffsetHASH;
  52. private byte[] Sum;
  53. private byte[] OffsetMAIN = new byte[16];
  54. private byte[] Checksum;
  55. // NOTE: The MAC value is preserved after doFinal
  56. private byte[] macBlock;
  57. public OcbBlockCipher(IBlockCipher hashCipher, IBlockCipher mainCipher)
  58. {
  59. if (hashCipher == null)
  60. throw new ArgumentNullException("hashCipher");
  61. if (hashCipher.GetBlockSize() != BLOCK_SIZE)
  62. throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "hashCipher");
  63. if (mainCipher == null)
  64. throw new ArgumentNullException("mainCipher");
  65. if (mainCipher.GetBlockSize() != BLOCK_SIZE)
  66. throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "mainCipher");
  67. if (!hashCipher.AlgorithmName.Equals(mainCipher.AlgorithmName))
  68. throw new ArgumentException("'hashCipher' and 'mainCipher' must be the same algorithm");
  69. this.hashCipher = hashCipher;
  70. this.mainCipher = mainCipher;
  71. }
  72. public virtual IBlockCipher GetUnderlyingCipher()
  73. {
  74. return mainCipher;
  75. }
  76. public virtual string AlgorithmName
  77. {
  78. get { return mainCipher.AlgorithmName + "/OCB"; }
  79. }
  80. public virtual void Init(bool forEncryption, ICipherParameters parameters)
  81. {
  82. bool oldForEncryption = this.forEncryption;
  83. this.forEncryption = forEncryption;
  84. this.macBlock = null;
  85. KeyParameter keyParameter;
  86. byte[] N;
  87. if (parameters is AeadParameters)
  88. {
  89. AeadParameters aeadParameters = (AeadParameters) parameters;
  90. N = aeadParameters.GetNonce();
  91. initialAssociatedText = aeadParameters.GetAssociatedText();
  92. int macSizeBits = aeadParameters.MacSize;
  93. if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0)
  94. throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
  95. macSize = macSizeBits / 8;
  96. keyParameter = aeadParameters.Key;
  97. }
  98. else if (parameters is ParametersWithIV)
  99. {
  100. ParametersWithIV parametersWithIV = (ParametersWithIV) parameters;
  101. N = parametersWithIV.GetIV();
  102. initialAssociatedText = null;
  103. macSize = 16;
  104. keyParameter = (KeyParameter) parametersWithIV.Parameters;
  105. }
  106. else
  107. {
  108. throw new ArgumentException("invalid parameters passed to OCB");
  109. }
  110. this.hashBlock = new byte[16];
  111. this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];
  112. if (N == null)
  113. {
  114. N = new byte[0];
  115. }
  116. if (N.Length > 15)
  117. {
  118. throw new ArgumentException("IV must be no more than 15 bytes");
  119. }
  120. /*
  121. * KEY-DEPENDENT INITIALISATION
  122. */
  123. if (keyParameter != null)
  124. {
  125. // hashCipher always used in forward mode
  126. hashCipher.Init(true, keyParameter);
  127. mainCipher.Init(forEncryption, keyParameter);
  128. KtopInput = null;
  129. }
  130. else if (oldForEncryption != forEncryption)
  131. {
  132. throw new ArgumentException("cannot change encrypting state without providing key.");
  133. }
  134. this.L_Asterisk = new byte[16];
  135. hashCipher.ProcessBlock(L_Asterisk, 0, L_Asterisk, 0);
  136. this.L_Dollar = OCB_double(L_Asterisk);
  137. this.L = Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  138. this.L.Add(OCB_double(L_Dollar));
  139. /*
  140. * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
  141. */
  142. int bottom = ProcessNonce(N);
  143. int bits = bottom % 8, bytes = bottom / 8;
  144. if (bits == 0)
  145. {
  146. Array.Copy(Stretch, bytes, OffsetMAIN_0, 0, 16);
  147. }
  148. else
  149. {
  150. for (int i = 0; i < 16; ++i)
  151. {
  152. uint b1 = Stretch[bytes];
  153. uint b2 = Stretch[++bytes];
  154. this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >> (8 - bits)));
  155. }
  156. }
  157. this.hashBlockPos = 0;
  158. this.mainBlockPos = 0;
  159. this.hashBlockCount = 0;
  160. this.mainBlockCount = 0;
  161. this.OffsetHASH = new byte[16];
  162. this.Sum = new byte[16];
  163. Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
  164. this.Checksum = new byte[16];
  165. if (initialAssociatedText != null)
  166. {
  167. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  168. }
  169. }
  170. protected virtual int ProcessNonce(byte[] N)
  171. {
  172. byte[] nonce = new byte[16];
  173. Array.Copy(N, 0, nonce, nonce.Length - N.Length, N.Length);
  174. nonce[0] = (byte)(macSize << 4);
  175. nonce[15 - N.Length] |= 1;
  176. int bottom = nonce[15] & 0x3F;
  177. nonce[15] &= 0xC0;
  178. /*
  179. * When used with incrementing nonces, the cipher is only applied once every 64 inits.
  180. */
  181. if (KtopInput == null || !Arrays.AreEqual(nonce, KtopInput))
  182. {
  183. byte[] Ktop = new byte[16];
  184. KtopInput = nonce;
  185. hashCipher.ProcessBlock(KtopInput, 0, Ktop, 0);
  186. Array.Copy(Ktop, 0, Stretch, 0, 16);
  187. for (int i = 0; i < 8; ++i)
  188. {
  189. Stretch[16 + i] = (byte)(Ktop[i] ^ Ktop[i + 1]);
  190. }
  191. }
  192. return bottom;
  193. }
  194. public virtual int GetBlockSize()
  195. {
  196. return BLOCK_SIZE;
  197. }
  198. public virtual byte[] GetMac()
  199. {
  200. return Arrays.Clone(macBlock);
  201. }
  202. public virtual int GetOutputSize(int len)
  203. {
  204. int totalData = len + mainBlockPos;
  205. if (forEncryption)
  206. {
  207. return totalData + macSize;
  208. }
  209. return totalData < macSize ? 0 : totalData - macSize;
  210. }
  211. public virtual int GetUpdateOutputSize(int len)
  212. {
  213. int totalData = len + mainBlockPos;
  214. if (!forEncryption)
  215. {
  216. if (totalData < macSize)
  217. {
  218. return 0;
  219. }
  220. totalData -= macSize;
  221. }
  222. return totalData - totalData % BLOCK_SIZE;
  223. }
  224. public virtual void ProcessAadByte(byte input)
  225. {
  226. hashBlock[hashBlockPos] = input;
  227. if (++hashBlockPos == hashBlock.Length)
  228. {
  229. ProcessHashBlock();
  230. }
  231. }
  232. public virtual void ProcessAadBytes(byte[] input, int off, int len)
  233. {
  234. for (int i = 0; i < len; ++i)
  235. {
  236. hashBlock[hashBlockPos] = input[off + i];
  237. if (++hashBlockPos == hashBlock.Length)
  238. {
  239. ProcessHashBlock();
  240. }
  241. }
  242. }
  243. public virtual int ProcessByte(byte input, byte[] output, int outOff)
  244. {
  245. mainBlock[mainBlockPos] = input;
  246. if (++mainBlockPos == mainBlock.Length)
  247. {
  248. ProcessMainBlock(output, outOff);
  249. return BLOCK_SIZE;
  250. }
  251. return 0;
  252. }
  253. public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
  254. {
  255. int resultLen = 0;
  256. for (int i = 0; i < len; ++i)
  257. {
  258. mainBlock[mainBlockPos] = input[inOff + i];
  259. if (++mainBlockPos == mainBlock.Length)
  260. {
  261. ProcessMainBlock(output, outOff + resultLen);
  262. resultLen += BLOCK_SIZE;
  263. }
  264. }
  265. return resultLen;
  266. }
  267. public virtual int DoFinal(byte[] output, int outOff)
  268. {
  269. /*
  270. * For decryption, get the tag from the end of the message
  271. */
  272. byte[] tag = null;
  273. if (!forEncryption) {
  274. if (mainBlockPos < macSize)
  275. throw new InvalidCipherTextException("data too short");
  276. mainBlockPos -= macSize;
  277. tag = new byte[macSize];
  278. Array.Copy(mainBlock, mainBlockPos, tag, 0, macSize);
  279. }
  280. /*
  281. * HASH: Process any final partial block; compute final hash value
  282. */
  283. if (hashBlockPos > 0)
  284. {
  285. OCB_extend(hashBlock, hashBlockPos);
  286. UpdateHASH(L_Asterisk);
  287. }
  288. /*
  289. * OCB-ENCRYPT/OCB-DECRYPT: Process any final partial block
  290. */
  291. if (mainBlockPos > 0)
  292. {
  293. if (forEncryption)
  294. {
  295. OCB_extend(mainBlock, mainBlockPos);
  296. Xor(Checksum, mainBlock);
  297. }
  298. Xor(OffsetMAIN, L_Asterisk);
  299. byte[] Pad = new byte[16];
  300. hashCipher.ProcessBlock(OffsetMAIN, 0, Pad, 0);
  301. Xor(mainBlock, Pad);
  302. Check.OutputLength(output, outOff, mainBlockPos, "Output buffer too short");
  303. Array.Copy(mainBlock, 0, output, outOff, mainBlockPos);
  304. if (!forEncryption)
  305. {
  306. OCB_extend(mainBlock, mainBlockPos);
  307. Xor(Checksum, mainBlock);
  308. }
  309. }
  310. /*
  311. * OCB-ENCRYPT/OCB-DECRYPT: Compute raw tag
  312. */
  313. Xor(Checksum, OffsetMAIN);
  314. Xor(Checksum, L_Dollar);
  315. hashCipher.ProcessBlock(Checksum, 0, Checksum, 0);
  316. Xor(Checksum, Sum);
  317. this.macBlock = new byte[macSize];
  318. Array.Copy(Checksum, 0, macBlock, 0, macSize);
  319. /*
  320. * Validate or append tag and reset this cipher for the next run
  321. */
  322. int resultLen = mainBlockPos;
  323. if (forEncryption)
  324. {
  325. Check.OutputLength(output, outOff, resultLen + macSize, "Output buffer too short");
  326. // Append tag to the message
  327. Array.Copy(macBlock, 0, output, outOff + resultLen, macSize);
  328. resultLen += macSize;
  329. }
  330. else
  331. {
  332. // Compare the tag from the message with the calculated one
  333. if (!Arrays.ConstantTimeAreEqual(macBlock, tag))
  334. throw new InvalidCipherTextException("mac check in OCB failed");
  335. }
  336. Reset(false);
  337. return resultLen;
  338. }
  339. public virtual void Reset()
  340. {
  341. Reset(true);
  342. }
  343. protected virtual void Clear(byte[] bs)
  344. {
  345. if (bs != null)
  346. {
  347. Array.Clear(bs, 0, bs.Length);
  348. }
  349. }
  350. protected virtual byte[] GetLSub(int n)
  351. {
  352. while (n >= L.Count)
  353. {
  354. L.Add(OCB_double((byte[]) L[L.Count - 1]));
  355. }
  356. return (byte[])L[n];
  357. }
  358. protected virtual void ProcessHashBlock()
  359. {
  360. /*
  361. * HASH: Process any whole blocks
  362. */
  363. UpdateHASH(GetLSub(OCB_ntz(++hashBlockCount)));
  364. hashBlockPos = 0;
  365. }
  366. protected virtual void ProcessMainBlock(byte[] output, int outOff)
  367. {
  368. Check.DataLength(output, outOff, BLOCK_SIZE, "Output buffer too short");
  369. /*
  370. * OCB-ENCRYPT/OCB-DECRYPT: Process any whole blocks
  371. */
  372. if (forEncryption)
  373. {
  374. Xor(Checksum, mainBlock);
  375. mainBlockPos = 0;
  376. }
  377. Xor(OffsetMAIN, GetLSub(OCB_ntz(++mainBlockCount)));
  378. Xor(mainBlock, OffsetMAIN);
  379. mainCipher.ProcessBlock(mainBlock, 0, mainBlock, 0);
  380. Xor(mainBlock, OffsetMAIN);
  381. Array.Copy(mainBlock, 0, output, outOff, 16);
  382. if (!forEncryption)
  383. {
  384. Xor(Checksum, mainBlock);
  385. Array.Copy(mainBlock, BLOCK_SIZE, mainBlock, 0, macSize);
  386. mainBlockPos = macSize;
  387. }
  388. }
  389. protected virtual void Reset(bool clearMac)
  390. {
  391. hashCipher.Reset();
  392. mainCipher.Reset();
  393. Clear(hashBlock);
  394. Clear(mainBlock);
  395. hashBlockPos = 0;
  396. mainBlockPos = 0;
  397. hashBlockCount = 0;
  398. mainBlockCount = 0;
  399. Clear(OffsetHASH);
  400. Clear(Sum);
  401. Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
  402. Clear(Checksum);
  403. if (clearMac)
  404. {
  405. macBlock = null;
  406. }
  407. if (initialAssociatedText != null)
  408. {
  409. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  410. }
  411. }
  412. protected virtual void UpdateHASH(byte[] LSub)
  413. {
  414. Xor(OffsetHASH, LSub);
  415. Xor(hashBlock, OffsetHASH);
  416. hashCipher.ProcessBlock(hashBlock, 0, hashBlock, 0);
  417. Xor(Sum, hashBlock);
  418. }
  419. protected static byte[] OCB_double(byte[] block)
  420. {
  421. byte[] result = new byte[16];
  422. int carry = ShiftLeft(block, result);
  423. /*
  424. * NOTE: This construction is an attempt at a constant-time implementation.
  425. */
  426. result[15] ^= (byte)(0x87 >> ((1 - carry) << 3));
  427. return result;
  428. }
  429. protected static void OCB_extend(byte[] block, int pos)
  430. {
  431. block[pos] = (byte) 0x80;
  432. while (++pos < 16)
  433. {
  434. block[pos] = 0;
  435. }
  436. }
  437. protected static int OCB_ntz(long x)
  438. {
  439. if (x == 0)
  440. {
  441. return 64;
  442. }
  443. int n = 0;
  444. ulong ux = (ulong)x;
  445. while ((ux & 1UL) == 0UL)
  446. {
  447. ++n;
  448. ux >>= 1;
  449. }
  450. return n;
  451. }
  452. protected static int ShiftLeft(byte[] block, byte[] output)
  453. {
  454. int i = 16;
  455. uint bit = 0;
  456. while (--i >= 0)
  457. {
  458. uint b = block[i];
  459. output[i] = (byte) ((b << 1) | bit);
  460. bit = (b >> 7) & 1;
  461. }
  462. return (int)bit;
  463. }
  464. protected static void Xor(byte[] block, byte[] val)
  465. {
  466. for (int i = 15; i >= 0; --i)
  467. {
  468. block[i] ^= val[i];
  469. }
  470. }
  471. }
  472. }
  473. #endif