EAXBlockCipher.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
  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. * 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
  54. {
  55. get { return cipher.GetUnderlyingCipher().AlgorithmName + "/EAX"; }
  56. }
  57. public virtual IBlockCipher GetUnderlyingCipher()
  58. {
  59. return cipher;
  60. }
  61. public virtual int GetBlockSize()
  62. {
  63. return cipher.GetBlockSize();
  64. }
  65. public virtual void Init(
  66. bool forEncryption,
  67. ICipherParameters parameters)
  68. {
  69. this.forEncryption = forEncryption;
  70. byte[] nonce;
  71. ICipherParameters keyParam;
  72. if (parameters is AeadParameters)
  73. {
  74. AeadParameters param = (AeadParameters) parameters;
  75. nonce = param.GetNonce();
  76. initialAssociatedText = param.GetAssociatedText();
  77. macSize = param.MacSize / 8;
  78. keyParam = param.Key;
  79. }
  80. else if (parameters is ParametersWithIV)
  81. {
  82. ParametersWithIV param = (ParametersWithIV) parameters;
  83. nonce = param.GetIV();
  84. initialAssociatedText = null;
  85. macSize = mac.GetMacSize() / 2;
  86. keyParam = param.Parameters;
  87. }
  88. else
  89. {
  90. throw new ArgumentException("invalid parameters passed to EAX");
  91. }
  92. bufBlock = new byte[forEncryption ? blockSize : (blockSize + macSize)];
  93. byte[] tag = new byte[blockSize];
  94. // Key reuse implemented in CBC mode of underlying CMac
  95. mac.Init(keyParam);
  96. tag[blockSize - 1] = (byte)Tag.N;
  97. mac.BlockUpdate(tag, 0, blockSize);
  98. mac.BlockUpdate(nonce, 0, nonce.Length);
  99. mac.DoFinal(nonceMac, 0);
  100. // Same BlockCipher underlies this and the mac, so reuse last key on cipher
  101. cipher.Init(true, new ParametersWithIV(null, nonceMac));
  102. Reset();
  103. }
  104. private void InitCipher()
  105. {
  106. if (cipherInitialized)
  107. {
  108. return;
  109. }
  110. cipherInitialized = true;
  111. mac.DoFinal(associatedTextMac, 0);
  112. byte[] tag = new byte[blockSize];
  113. tag[blockSize - 1] = (byte)Tag.C;
  114. mac.BlockUpdate(tag, 0, blockSize);
  115. }
  116. private void CalculateMac()
  117. {
  118. byte[] outC = new byte[blockSize];
  119. mac.DoFinal(outC, 0);
  120. for (int i = 0; i < macBlock.Length; i++)
  121. {
  122. macBlock[i] = (byte)(nonceMac[i] ^ associatedTextMac[i] ^ outC[i]);
  123. }
  124. }
  125. public virtual void Reset()
  126. {
  127. Reset(true);
  128. }
  129. private void Reset(
  130. bool clearMac)
  131. {
  132. cipher.Reset(); // TODO Redundant since the mac will reset it?
  133. mac.Reset();
  134. bufOff = 0;
  135. Array.Clear(bufBlock, 0, bufBlock.Length);
  136. if (clearMac)
  137. {
  138. Array.Clear(macBlock, 0, macBlock.Length);
  139. }
  140. byte[] tag = new byte[blockSize];
  141. tag[blockSize - 1] = (byte)Tag.H;
  142. mac.BlockUpdate(tag, 0, blockSize);
  143. cipherInitialized = false;
  144. if (initialAssociatedText != null)
  145. {
  146. ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
  147. }
  148. }
  149. public virtual void ProcessAadByte(byte input)
  150. {
  151. if (cipherInitialized)
  152. {
  153. throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
  154. }
  155. mac.Update(input);
  156. }
  157. public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
  158. {
  159. if (cipherInitialized)
  160. {
  161. throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
  162. }
  163. mac.BlockUpdate(inBytes, inOff, len);
  164. }
  165. public virtual int ProcessByte(
  166. byte input,
  167. byte[] outBytes,
  168. int outOff)
  169. {
  170. InitCipher();
  171. return Process(input, outBytes, outOff);
  172. }
  173. public virtual int ProcessBytes(
  174. byte[] inBytes,
  175. int inOff,
  176. int len,
  177. byte[] outBytes,
  178. int outOff)
  179. {
  180. InitCipher();
  181. int resultLen = 0;
  182. for (int i = 0; i != len; i++)
  183. {
  184. resultLen += Process(inBytes[inOff + i], outBytes, outOff + resultLen);
  185. }
  186. return resultLen;
  187. }
  188. public virtual int DoFinal(
  189. byte[] outBytes,
  190. int outOff)
  191. {
  192. InitCipher();
  193. int extra = bufOff;
  194. byte[] tmp = new byte[bufBlock.Length];
  195. bufOff = 0;
  196. if (forEncryption)
  197. {
  198. Check.OutputLength(outBytes, outOff, extra + macSize, "Output buffer too short");
  199. cipher.ProcessBlock(bufBlock, 0, tmp, 0);
  200. Array.Copy(tmp, 0, outBytes, outOff, extra);
  201. mac.BlockUpdate(tmp, 0, extra);
  202. CalculateMac();
  203. Array.Copy(macBlock, 0, outBytes, outOff + extra, macSize);
  204. Reset(false);
  205. return extra + macSize;
  206. }
  207. else
  208. {
  209. if (extra < macSize)
  210. throw new InvalidCipherTextException("data too short");
  211. Check.OutputLength(outBytes, outOff, extra - macSize, "Output buffer too short");
  212. if (extra > macSize)
  213. {
  214. mac.BlockUpdate(bufBlock, 0, extra - macSize);
  215. cipher.ProcessBlock(bufBlock, 0, tmp, 0);
  216. Array.Copy(tmp, 0, outBytes, outOff, extra - macSize);
  217. }
  218. CalculateMac();
  219. if (!VerifyMac(bufBlock, extra - macSize))
  220. throw new InvalidCipherTextException("mac check in EAX failed");
  221. Reset(false);
  222. return extra - macSize;
  223. }
  224. }
  225. public virtual byte[] GetMac()
  226. {
  227. byte[] mac = new byte[macSize];
  228. Array.Copy(macBlock, 0, mac, 0, macSize);
  229. return mac;
  230. }
  231. public virtual int GetUpdateOutputSize(
  232. int len)
  233. {
  234. int totalData = len + bufOff;
  235. if (!forEncryption)
  236. {
  237. if (totalData < macSize)
  238. {
  239. return 0;
  240. }
  241. totalData -= macSize;
  242. }
  243. return totalData - totalData % blockSize;
  244. }
  245. public virtual int GetOutputSize(
  246. int len)
  247. {
  248. int totalData = len + bufOff;
  249. if (forEncryption)
  250. {
  251. return totalData + macSize;
  252. }
  253. return totalData < macSize ? 0 : totalData - macSize;
  254. }
  255. private int Process(
  256. byte b,
  257. byte[] outBytes,
  258. int outOff)
  259. {
  260. bufBlock[bufOff++] = b;
  261. if (bufOff == bufBlock.Length)
  262. {
  263. Check.OutputLength(outBytes, outOff, blockSize, "Output buffer is too short");
  264. // TODO Could move the ProcessByte(s) calls to here
  265. // InitCipher();
  266. int size;
  267. if (forEncryption)
  268. {
  269. size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
  270. mac.BlockUpdate(outBytes, outOff, blockSize);
  271. }
  272. else
  273. {
  274. mac.BlockUpdate(bufBlock, 0, blockSize);
  275. size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
  276. }
  277. bufOff = 0;
  278. if (!forEncryption)
  279. {
  280. Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize);
  281. bufOff = macSize;
  282. }
  283. return size;
  284. }
  285. return 0;
  286. }
  287. private bool VerifyMac(byte[] mac, int off)
  288. {
  289. int nonEqual = 0;
  290. for (int i = 0; i < macSize; i++)
  291. {
  292. nonEqual |= (macBlock[i] ^ mac[off + i]);
  293. }
  294. return nonEqual == 0;
  295. }
  296. }
  297. }
  298. #pragma warning restore
  299. #endif