EAXBlockCipher.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
  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. /**
  10. * A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and
  11. * Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
  12. *
  13. * http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
  14. *
  15. * EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block
  16. * cipher to encrypt and authenticate data. It's on-line (the length of a
  17. * message isn't needed to begin processing it), has good performances, it's
  18. * simple and provably secure (provided the underlying block cipher is secure).
  19. *
  20. * Of course, this implementations is NOT thread-safe.
  21. */
  22. public class EaxBlockCipher
  23. : IAeadBlockCipher
  24. {
  25. private enum Tag : byte { N, H, C };
  26. private SicBlockCipher cipher;
  27. private bool forEncryption;
  28. private int blockSize;
  29. private IMac mac;
  30. private byte[] nonceMac;
  31. private byte[] associatedTextMac;
  32. private byte[] macBlock;
  33. private int macSize;
  34. private byte[] bufBlock;
  35. private int bufOff;
  36. private bool cipherInitialized;
  37. private byte[] initialAssociatedText;
  38. /**
  39. * Constructor that accepts an instance of a block cipher engine.
  40. *
  41. * @param cipher the engine to use
  42. */
  43. public EaxBlockCipher(
  44. IBlockCipher cipher)
  45. {
  46. blockSize = cipher.GetBlockSize();
  47. mac = new CMac(cipher);
  48. macBlock = new byte[blockSize];
  49. associatedTextMac = new byte[mac.GetMacSize()];
  50. nonceMac = new byte[mac.GetMacSize()];
  51. this.cipher = new SicBlockCipher(cipher);
  52. }
  53. public virtual string AlgorithmName => cipher.UnderlyingCipher.AlgorithmName + "/EAX";
  54. public virtual IBlockCipher UnderlyingCipher => cipher;
  55. public virtual int GetBlockSize()
  56. {
  57. return cipher.GetBlockSize();
  58. }
  59. public virtual void Init(bool forEncryption, ICipherParameters parameters)
  60. {
  61. this.forEncryption = forEncryption;
  62. byte[] nonce;
  63. ICipherParameters keyParam;
  64. if (parameters is AeadParameters aeadParameters)
  65. {
  66. nonce = aeadParameters.GetNonce();
  67. initialAssociatedText = aeadParameters.GetAssociatedText();
  68. macSize = aeadParameters.MacSize / 8;
  69. keyParam = aeadParameters.Key;
  70. }
  71. else if (parameters is ParametersWithIV parametersWithIV)
  72. {
  73. nonce = parametersWithIV.GetIV();
  74. initialAssociatedText = null;
  75. macSize = mac.GetMacSize() / 2;
  76. keyParam = parametersWithIV.Parameters;
  77. }
  78. else
  79. {
  80. throw new ArgumentException("invalid parameters passed to EAX");
  81. }
  82. bufBlock = new byte[forEncryption ? blockSize : (blockSize + macSize)];
  83. byte[] tag = new byte[blockSize];
  84. // Key reuse implemented in CBC mode of underlying CMac
  85. mac.Init(keyParam);
  86. tag[blockSize - 1] = (byte)Tag.N;
  87. mac.BlockUpdate(tag, 0, blockSize);
  88. mac.BlockUpdate(nonce, 0, nonce.Length);
  89. mac.DoFinal(nonceMac, 0);
  90. // Same BlockCipher underlies this and the mac, so reuse last key on cipher
  91. cipher.Init(true, new ParametersWithIV(null, nonceMac));
  92. Reset();
  93. }
  94. private void InitCipher()
  95. {
  96. if (cipherInitialized)
  97. {
  98. return;
  99. }
  100. cipherInitialized = true;
  101. mac.DoFinal(associatedTextMac, 0);
  102. byte[] tag = new byte[blockSize];
  103. tag[blockSize - 1] = (byte)Tag.C;
  104. mac.BlockUpdate(tag, 0, blockSize);
  105. }
  106. private void CalculateMac()
  107. {
  108. byte[] outC = new byte[blockSize];
  109. mac.DoFinal(outC, 0);
  110. for (int i = 0; i < macBlock.Length; i++)
  111. {
  112. macBlock[i] = (byte)(nonceMac[i] ^ associatedTextMac[i] ^ outC[i]);
  113. }
  114. }
  115. public virtual void Reset()
  116. {
  117. Reset(true);
  118. }
  119. private void Reset(
  120. bool clearMac)
  121. {
  122. cipher.Reset(); // TODO Redundant since the mac will reset it?
  123. mac.Reset();
  124. bufOff = 0;
  125. Array.Clear(bufBlock, 0, bufBlock.Length);
  126. if (clearMac)
  127. {
  128. Array.Clear(macBlock, 0, macBlock.Length);
  129. }
  130. byte[] tag = new byte[blockSize];
  131. tag[blockSize - 1] = (byte)Tag.H;
  132. mac.BlockUpdate(tag, 0, blockSize);
  133. cipherInitialized = false;
  134. if (initialAssociatedText != null)
  135. {
  136. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  137. }
  138. }
  139. public virtual void ProcessAadByte(byte input)
  140. {
  141. if (cipherInitialized)
  142. {
  143. throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
  144. }
  145. mac.Update(input);
  146. }
  147. public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
  148. {
  149. if (cipherInitialized)
  150. throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
  151. mac.BlockUpdate(inBytes, inOff, len);
  152. }
  153. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  154. public virtual void ProcessAadBytes(ReadOnlySpan<byte> input)
  155. {
  156. if (cipherInitialized)
  157. throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
  158. mac.BlockUpdate(input);
  159. }
  160. #endif
  161. public virtual int ProcessByte(byte input, byte[] outBytes, int outOff)
  162. {
  163. InitCipher();
  164. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  165. return Process(input, Spans.FromNullable(outBytes, outOff));
  166. #else
  167. return Process(input, outBytes, outOff);
  168. #endif
  169. }
  170. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  171. public virtual int ProcessByte(byte input, Span<byte> output)
  172. {
  173. InitCipher();
  174. return Process(input, output);
  175. }
  176. #endif
  177. public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff)
  178. {
  179. InitCipher();
  180. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  181. return ProcessBytes(inBytes.AsSpan(inOff, len), Spans.FromNullable(outBytes, outOff));
  182. #else
  183. int resultLen = 0;
  184. for (int i = 0; i != len; i++)
  185. {
  186. resultLen += Process(inBytes[inOff + i], outBytes, outOff + resultLen);
  187. }
  188. return resultLen;
  189. #endif
  190. }
  191. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  192. public virtual int ProcessBytes(ReadOnlySpan<byte> input, Span<byte> output)
  193. {
  194. InitCipher();
  195. int len = input.Length;
  196. int resultLen = 0;
  197. for (int i = 0; i != len; i++)
  198. {
  199. resultLen += Process(input[i], output[resultLen..]);
  200. }
  201. return resultLen;
  202. }
  203. #endif
  204. public virtual int DoFinal(byte[] outBytes, int outOff)
  205. {
  206. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  207. return DoFinal(outBytes.AsSpan(outOff));
  208. #else
  209. InitCipher();
  210. int extra = bufOff;
  211. byte[] tmp = new byte[bufBlock.Length];
  212. bufOff = 0;
  213. if (forEncryption)
  214. {
  215. Check.OutputLength(outBytes, outOff, extra + macSize, "output buffer too short");
  216. cipher.ProcessBlock(bufBlock, 0, tmp, 0);
  217. Array.Copy(tmp, 0, outBytes, outOff, extra);
  218. mac.BlockUpdate(tmp, 0, extra);
  219. CalculateMac();
  220. Array.Copy(macBlock, 0, outBytes, outOff + extra, macSize);
  221. Reset(false);
  222. return extra + macSize;
  223. }
  224. else
  225. {
  226. if (extra < macSize)
  227. throw new InvalidCipherTextException("data too short");
  228. Check.OutputLength(outBytes, outOff, extra - macSize, "output buffer too short");
  229. if (extra > macSize)
  230. {
  231. mac.BlockUpdate(bufBlock, 0, extra - macSize);
  232. cipher.ProcessBlock(bufBlock, 0, tmp, 0);
  233. Array.Copy(tmp, 0, outBytes, outOff, extra - macSize);
  234. }
  235. CalculateMac();
  236. if (!VerifyMac(bufBlock, extra - macSize))
  237. throw new InvalidCipherTextException("mac check in EAX failed");
  238. Reset(false);
  239. return extra - macSize;
  240. }
  241. #endif
  242. }
  243. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  244. public virtual int DoFinal(Span<byte> output)
  245. {
  246. InitCipher();
  247. int extra = bufOff;
  248. int tmpLength = bufBlock.Length;
  249. Span<byte> tmp = tmpLength <= 128
  250. ? stackalloc byte[tmpLength]
  251. : new byte[tmpLength];
  252. bufOff = 0;
  253. if (forEncryption)
  254. {
  255. Check.OutputLength(output, extra + macSize, "output buffer too short");
  256. cipher.ProcessBlock(bufBlock, tmp);
  257. tmp[..extra].CopyTo(output);
  258. mac.BlockUpdate(tmp[..extra]);
  259. CalculateMac();
  260. macBlock.AsSpan(0, macSize).CopyTo(output[extra..]);
  261. Reset(false);
  262. return extra + macSize;
  263. }
  264. else
  265. {
  266. if (extra < macSize)
  267. throw new InvalidCipherTextException("data too short");
  268. Check.OutputLength(output, extra - macSize, "output buffer too short");
  269. if (extra > macSize)
  270. {
  271. mac.BlockUpdate(bufBlock.AsSpan(0, extra - macSize));
  272. cipher.ProcessBlock(bufBlock, tmp);
  273. tmp[..(extra - macSize)].CopyTo(output);
  274. }
  275. CalculateMac();
  276. if (!VerifyMac(bufBlock, extra - macSize))
  277. throw new InvalidCipherTextException("mac check in EAX failed");
  278. Reset(false);
  279. return extra - macSize;
  280. }
  281. }
  282. #endif
  283. public virtual byte[] GetMac()
  284. {
  285. byte[] mac = new byte[macSize];
  286. Array.Copy(macBlock, 0, mac, 0, macSize);
  287. return mac;
  288. }
  289. public virtual int GetUpdateOutputSize(
  290. int len)
  291. {
  292. int totalData = len + bufOff;
  293. if (!forEncryption)
  294. {
  295. if (totalData < macSize)
  296. {
  297. return 0;
  298. }
  299. totalData -= macSize;
  300. }
  301. return totalData - totalData % blockSize;
  302. }
  303. public virtual int GetOutputSize(
  304. int len)
  305. {
  306. int totalData = len + bufOff;
  307. if (forEncryption)
  308. {
  309. return totalData + macSize;
  310. }
  311. return totalData < macSize ? 0 : totalData - macSize;
  312. }
  313. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  314. private int Process(byte b, Span<byte> output)
  315. {
  316. bufBlock[bufOff++] = b;
  317. if (bufOff == bufBlock.Length)
  318. {
  319. Check.OutputLength(output, blockSize, "output buffer too short");
  320. // TODO Could move the ProcessByte(s) calls to here
  321. //InitCipher();
  322. int size;
  323. if (forEncryption)
  324. {
  325. size = cipher.ProcessBlock(bufBlock, output);
  326. mac.BlockUpdate(output[..blockSize]);
  327. }
  328. else
  329. {
  330. mac.BlockUpdate(bufBlock.AsSpan(0, blockSize));
  331. size = cipher.ProcessBlock(bufBlock, output);
  332. }
  333. bufOff = 0;
  334. if (!forEncryption)
  335. {
  336. Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize);
  337. bufOff = macSize;
  338. }
  339. return size;
  340. }
  341. return 0;
  342. }
  343. #else
  344. private int Process(byte b, byte[] outBytes, int outOff)
  345. {
  346. bufBlock[bufOff++] = b;
  347. if (bufOff == bufBlock.Length)
  348. {
  349. Check.OutputLength(outBytes, outOff, blockSize, "Output buffer is too short");
  350. // TODO Could move the ProcessByte(s) calls to here
  351. // InitCipher();
  352. int size;
  353. if (forEncryption)
  354. {
  355. size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
  356. mac.BlockUpdate(outBytes, outOff, blockSize);
  357. }
  358. else
  359. {
  360. mac.BlockUpdate(bufBlock, 0, blockSize);
  361. size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
  362. }
  363. bufOff = 0;
  364. if (!forEncryption)
  365. {
  366. Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize);
  367. bufOff = macSize;
  368. }
  369. return size;
  370. }
  371. return 0;
  372. }
  373. #endif
  374. private bool VerifyMac(byte[] mac, int off)
  375. {
  376. int nonEqual = 0;
  377. for (int i = 0; i < macSize; i++)
  378. {
  379. nonEqual |= (macBlock[i] ^ mac[off + i]);
  380. }
  381. return nonEqual == 0;
  382. }
  383. }
  384. }
  385. #pragma warning restore
  386. #endif