OCBBlockCipher.cs 17 KB

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