FastPoly1305.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  8. namespace BestHTTP.Connections.TLS.Crypto.Impl
  9. {
  10. /// <summary>
  11. /// Poly1305 message authentication code, designed by D. J. Bernstein.
  12. /// </summary>
  13. /// <remarks>
  14. /// Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key
  15. /// consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106
  16. /// effective key bits) used in the authenticator.
  17. ///
  18. /// The polynomial calculation in this implementation is adapted from the public domain <a
  19. /// href="https://github.com/floodyberry/poly1305-donna">poly1305-donna-unrolled</a> C implementation
  20. /// by Andrew M (@floodyberry).
  21. /// </remarks>
  22. /// <seealso cref="BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators.Poly1305KeyGenerator"/>
  23. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)]
  24. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)]
  25. [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)]
  26. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  27. public sealed class FastPoly1305 : IMac
  28. {
  29. private const int BlockSize = 16;
  30. private readonly IBlockCipher cipher;
  31. private readonly byte[] singleByte = new byte[1];
  32. // Initialised state
  33. /** Polynomial key */
  34. private uint r0, r1, r2, r3, r4;
  35. /** Precomputed 5 * r[1..4] */
  36. private uint s1, s2, s3, s4;
  37. /** Encrypted nonce */
  38. private uint k0, k1, k2, k3;
  39. // Accumulating state
  40. /** Current block of buffered input */
  41. private byte[] currentBlock = new byte[BlockSize];
  42. /** Current offset in input buffer */
  43. private int currentBlockOffset = 0;
  44. /** Polynomial accumulator */
  45. private uint h0, h1, h2, h3, h4;
  46. /**
  47. * Constructs a Poly1305 MAC, where the key passed to init() will be used directly.
  48. */
  49. public FastPoly1305()
  50. {
  51. this.cipher = null;
  52. }
  53. /**
  54. * Constructs a Poly1305 MAC, using a 128 bit block cipher.
  55. */
  56. public FastPoly1305(IBlockCipher cipher)
  57. {
  58. if (cipher.GetBlockSize() != BlockSize)
  59. {
  60. throw new ArgumentException("Poly1305 requires a 128 bit block cipher.");
  61. }
  62. this.cipher = cipher;
  63. }
  64. /// <summary>
  65. /// Initialises the Poly1305 MAC.
  66. /// </summary>
  67. /// <param name="parameters">a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with
  68. /// a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}.</param>
  69. public void Init(ICipherParameters parameters)
  70. {
  71. byte[] nonce = null;
  72. if (cipher != null)
  73. {
  74. if (!(parameters is FastParametersWithIV))
  75. throw new ArgumentException("Poly1305 requires an IV when used with a block cipher.", "parameters");
  76. FastParametersWithIV ivParams = (FastParametersWithIV)parameters;
  77. nonce = ivParams.GetIV();
  78. parameters = ivParams.Parameters;
  79. }
  80. if (!(parameters is NoCopyKeyParameter))
  81. throw new ArgumentException("Poly1305 requires a key.");
  82. NoCopyKeyParameter keyParams = (NoCopyKeyParameter)parameters;
  83. SetKey(keyParams.GetKey(), nonce);
  84. Reset();
  85. }
  86. private void SetKey(byte[] key, byte[] nonce)
  87. {
  88. if (key.Length != 32)
  89. throw new ArgumentException("Poly1305 key must be 256 bits.");
  90. if (cipher != null && (nonce == null || nonce.Length != BlockSize))
  91. throw new ArgumentException("Poly1305 requires a 128 bit IV.");
  92. // Extract r portion of key (and "clamp" the values)
  93. uint t0 = Pack.LE_To_UInt32(key, 0);
  94. uint t1 = Pack.LE_To_UInt32(key, 4);
  95. uint t2 = Pack.LE_To_UInt32(key, 8);
  96. uint t3 = Pack.LE_To_UInt32(key, 12);
  97. // NOTE: The masks perform the key "clamping" implicitly
  98. r0 = t0 & 0x03FFFFFFU;
  99. r1 = ((t0 >> 26) | (t1 << 6)) & 0x03FFFF03U;
  100. r2 = ((t1 >> 20) | (t2 << 12)) & 0x03FFC0FFU;
  101. r3 = ((t2 >> 14) | (t3 << 18)) & 0x03F03FFFU;
  102. r4 = (t3 >> 8) & 0x000FFFFFU;
  103. // Precompute multipliers
  104. s1 = r1 * 5;
  105. s2 = r2 * 5;
  106. s3 = r3 * 5;
  107. s4 = r4 * 5;
  108. byte[] kBytes;
  109. int kOff;
  110. if (cipher == null)
  111. {
  112. kBytes = key;
  113. kOff = BlockSize;
  114. }
  115. else
  116. {
  117. // Compute encrypted nonce
  118. kBytes = new byte[BlockSize];
  119. kOff = 0;
  120. cipher.Init(true, new KeyParameter(key, BlockSize, BlockSize));
  121. cipher.ProcessBlock(nonce, 0, kBytes, 0);
  122. }
  123. k0 = Pack.LE_To_UInt32(kBytes, kOff + 0);
  124. k1 = Pack.LE_To_UInt32(kBytes, kOff + 4);
  125. k2 = Pack.LE_To_UInt32(kBytes, kOff + 8);
  126. k3 = Pack.LE_To_UInt32(kBytes, kOff + 12);
  127. }
  128. public string AlgorithmName
  129. {
  130. get { return cipher == null ? "Poly1305" : "Poly1305-" + cipher.AlgorithmName; }
  131. }
  132. public int GetMacSize()
  133. {
  134. return BlockSize;
  135. }
  136. public void Update(byte input)
  137. {
  138. singleByte[0] = input;
  139. BlockUpdate(singleByte, 0, 1);
  140. }
  141. public void BlockUpdate(byte[] input, int inOff, int len)
  142. {
  143. int copied = 0;
  144. while (len > copied)
  145. {
  146. if (currentBlockOffset == BlockSize)
  147. {
  148. ProcessBlock();
  149. currentBlockOffset = 0;
  150. }
  151. int toCopy = System.Math.Min((len - copied), BlockSize - currentBlockOffset);
  152. Array.Copy(input, copied + inOff, currentBlock, currentBlockOffset, toCopy);
  153. copied += toCopy;
  154. currentBlockOffset += toCopy;
  155. }
  156. }
  157. private void ProcessBlock()
  158. {
  159. if (currentBlockOffset < BlockSize)
  160. {
  161. currentBlock[currentBlockOffset] = 1;
  162. for (int i = currentBlockOffset + 1; i < BlockSize; i++)
  163. {
  164. currentBlock[i] = 0;
  165. }
  166. }
  167. ulong t0 = Pack.LE_To_UInt32(currentBlock, 0);
  168. ulong t1 = Pack.LE_To_UInt32(currentBlock, 4);
  169. ulong t2 = Pack.LE_To_UInt32(currentBlock, 8);
  170. ulong t3 = Pack.LE_To_UInt32(currentBlock, 12);
  171. h0 += (uint)(t0 & 0x3ffffffU);
  172. h1 += (uint)((((t1 << 32) | t0) >> 26) & 0x3ffffff);
  173. h2 += (uint)((((t2 << 32) | t1) >> 20) & 0x3ffffff);
  174. h3 += (uint)((((t3 << 32) | t2) >> 14) & 0x3ffffff);
  175. h4 += (uint)(t3 >> 8);
  176. if (currentBlockOffset == BlockSize)
  177. {
  178. h4 += (1 << 24);
  179. }
  180. ulong tp0 = mul32x32_64(h0, r0) + mul32x32_64(h1, s4) + mul32x32_64(h2, s3) + mul32x32_64(h3, s2) + mul32x32_64(h4, s1);
  181. ulong tp1 = mul32x32_64(h0, r1) + mul32x32_64(h1, r0) + mul32x32_64(h2, s4) + mul32x32_64(h3, s3) + mul32x32_64(h4, s2);
  182. ulong tp2 = mul32x32_64(h0, r2) + mul32x32_64(h1, r1) + mul32x32_64(h2, r0) + mul32x32_64(h3, s4) + mul32x32_64(h4, s3);
  183. ulong tp3 = mul32x32_64(h0, r3) + mul32x32_64(h1, r2) + mul32x32_64(h2, r1) + mul32x32_64(h3, r0) + mul32x32_64(h4, s4);
  184. ulong tp4 = mul32x32_64(h0, r4) + mul32x32_64(h1, r3) + mul32x32_64(h2, r2) + mul32x32_64(h3, r1) + mul32x32_64(h4, r0);
  185. h0 = (uint)tp0 & 0x3ffffff; tp1 += (tp0 >> 26);
  186. h1 = (uint)tp1 & 0x3ffffff; tp2 += (tp1 >> 26);
  187. h2 = (uint)tp2 & 0x3ffffff; tp3 += (tp2 >> 26);
  188. h3 = (uint)tp3 & 0x3ffffff; tp4 += (tp3 >> 26);
  189. h4 = (uint)tp4 & 0x3ffffff;
  190. h0 += (uint)(tp4 >> 26) * 5;
  191. h1 += (h0 >> 26); h0 &= 0x3ffffff;
  192. }
  193. public int DoFinal(byte[] output, int outOff)
  194. {
  195. Check.DataLength(output, outOff, BlockSize, "Output buffer is too short.");
  196. if (currentBlockOffset > 0)
  197. {
  198. // Process padded block
  199. ProcessBlock();
  200. }
  201. h1 += (h0 >> 26); h0 &= 0x3ffffff;
  202. h2 += (h1 >> 26); h1 &= 0x3ffffff;
  203. h3 += (h2 >> 26); h2 &= 0x3ffffff;
  204. h4 += (h3 >> 26); h3 &= 0x3ffffff;
  205. h0 += (h4 >> 26) * 5; h4 &= 0x3ffffff;
  206. h1 += (h0 >> 26); h0 &= 0x3ffffff;
  207. uint g0, g1, g2, g3, g4, b;
  208. g0 = h0 + 5; b = g0 >> 26; g0 &= 0x3ffffff;
  209. g1 = h1 + b; b = g1 >> 26; g1 &= 0x3ffffff;
  210. g2 = h2 + b; b = g2 >> 26; g2 &= 0x3ffffff;
  211. g3 = h3 + b; b = g3 >> 26; g3 &= 0x3ffffff;
  212. g4 = h4 + b - (1 << 26);
  213. b = (g4 >> 31) - 1;
  214. uint nb = ~b;
  215. h0 = (h0 & nb) | (g0 & b);
  216. h1 = (h1 & nb) | (g1 & b);
  217. h2 = (h2 & nb) | (g2 & b);
  218. h3 = (h3 & nb) | (g3 & b);
  219. h4 = (h4 & nb) | (g4 & b);
  220. ulong f0, f1, f2, f3;
  221. f0 = ((h0) | (h1 << 26)) + (ulong)k0;
  222. f1 = ((h1 >> 6) | (h2 << 20)) + (ulong)k1;
  223. f2 = ((h2 >> 12) | (h3 << 14)) + (ulong)k2;
  224. f3 = ((h3 >> 18) | (h4 << 8)) + (ulong)k3;
  225. Pack.UInt32_To_LE((uint)f0, output, outOff);
  226. f1 += (f0 >> 32);
  227. Pack.UInt32_To_LE((uint)f1, output, outOff + 4);
  228. f2 += (f1 >> 32);
  229. Pack.UInt32_To_LE((uint)f2, output, outOff + 8);
  230. f3 += (f2 >> 32);
  231. Pack.UInt32_To_LE((uint)f3, output, outOff + 12);
  232. Reset();
  233. return BlockSize;
  234. }
  235. public void Reset()
  236. {
  237. currentBlockOffset = 0;
  238. h0 = h1 = h2 = h3 = h4 = 0;
  239. }
  240. private static ulong mul32x32_64(uint i1, uint i2)
  241. {
  242. return ((ulong)i1) * i2;
  243. }
  244. }
  245. }
  246. #pragma warning restore
  247. #endif