EAXBlockCipher.cs 8.8 KB

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