Poly1305.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Diagnostics;
  5. #if NETCOREAPP3_0_OR_GREATER
  6. using System.Runtime.CompilerServices;
  7. #endif
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  9. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  10. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
  11. {
  12. /// <summary>
  13. /// Poly1305 message authentication code, designed by D. J. Bernstein.
  14. /// </summary>
  15. /// <remarks>
  16. /// Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key
  17. /// consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106
  18. /// effective key bits) used in the authenticator.
  19. ///
  20. /// The polynomial calculation in this implementation is adapted from the public domain <a
  21. /// href="https://github.com/floodyberry/poly1305-donna">poly1305-donna-unrolled</a> C implementation
  22. /// by Andrew M (@floodyberry).
  23. /// </remarks>
  24. /// <seealso cref="Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators.Poly1305KeyGenerator"/>
  25. public class Poly1305
  26. : IMac
  27. {
  28. private const int BlockSize = 16;
  29. private readonly IBlockCipher cipher;
  30. // Initialised state
  31. /** Polynomial key */
  32. private uint r0, r1, r2, r3, r4;
  33. /** Precomputed 5 * r[1..4] */
  34. private uint s1, s2, s3, s4;
  35. /** Encrypted nonce */
  36. private uint k0, k1, k2, k3;
  37. // Accumulating state
  38. /** Current block of buffered input */
  39. private byte[] currentBlock = new byte[BlockSize];
  40. /** Current offset in input buffer */
  41. private int currentBlockOffset = 0;
  42. /** Polynomial accumulator */
  43. private uint h0, h1, h2, h3, h4;
  44. /**
  45. * Constructs a Poly1305 MAC, where the key passed to init() will be used directly.
  46. */
  47. public Poly1305()
  48. {
  49. this.cipher = null;
  50. }
  51. /**
  52. * Constructs a Poly1305 MAC, using a 128 bit block cipher.
  53. */
  54. public Poly1305(IBlockCipher cipher)
  55. {
  56. if (cipher.GetBlockSize() != BlockSize)
  57. {
  58. throw new ArgumentException("Poly1305 requires a 128 bit block cipher.");
  59. }
  60. this.cipher = cipher;
  61. }
  62. /// <summary>
  63. /// Initialises the Poly1305 MAC.
  64. /// </summary>
  65. /// <param name="parameters">a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with
  66. /// a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}.</param>
  67. public void Init(ICipherParameters parameters)
  68. {
  69. byte[] nonce = null;
  70. if (cipher != null)
  71. {
  72. if (!(parameters is ParametersWithIV))
  73. throw new ArgumentException("Poly1305 requires an IV when used with a block cipher.", "parameters");
  74. ParametersWithIV ivParams = (ParametersWithIV)parameters;
  75. nonce = ivParams.GetIV();
  76. parameters = ivParams.Parameters;
  77. }
  78. if (!(parameters is KeyParameter))
  79. throw new ArgumentException("Poly1305 requires a key.");
  80. KeyParameter keyParams = (KeyParameter)parameters;
  81. SetKey(keyParams.GetKey(), nonce);
  82. Reset();
  83. }
  84. private void SetKey(byte[] key, byte[] nonce)
  85. {
  86. if (key.Length != 32)
  87. throw new ArgumentException("Poly1305 key must be 256 bits.");
  88. if (cipher != null && (nonce == null || nonce.Length != BlockSize))
  89. throw new ArgumentException("Poly1305 requires a 128 bit IV.");
  90. // Extract r portion of key (and "clamp" the values)
  91. uint t0 = Pack.LE_To_UInt32(key, 0);
  92. uint t1 = Pack.LE_To_UInt32(key, 4);
  93. uint t2 = Pack.LE_To_UInt32(key, 8);
  94. uint t3 = Pack.LE_To_UInt32(key, 12);
  95. // NOTE: The masks perform the key "clamping" implicitly
  96. r0 = t0 & 0x03FFFFFFU;
  97. r1 = ((t0 >> 26) | (t1 << 6)) & 0x03FFFF03U;
  98. r2 = ((t1 >> 20) | (t2 << 12)) & 0x03FFC0FFU;
  99. r3 = ((t2 >> 14) | (t3 << 18)) & 0x03F03FFFU;
  100. r4 = (t3 >> 8) & 0x000FFFFFU;
  101. // Precompute multipliers
  102. s1 = r1 * 5;
  103. s2 = r2 * 5;
  104. s3 = r3 * 5;
  105. s4 = r4 * 5;
  106. byte[] kBytes;
  107. int kOff;
  108. if (cipher == null)
  109. {
  110. kBytes = key;
  111. kOff = BlockSize;
  112. }
  113. else
  114. {
  115. // Compute encrypted nonce
  116. kBytes = new byte[BlockSize];
  117. kOff = 0;
  118. cipher.Init(true, new KeyParameter(key, BlockSize, BlockSize));
  119. cipher.ProcessBlock(nonce, 0, kBytes, 0);
  120. }
  121. k0 = Pack.LE_To_UInt32(kBytes, kOff + 0);
  122. k1 = Pack.LE_To_UInt32(kBytes, kOff + 4);
  123. k2 = Pack.LE_To_UInt32(kBytes, kOff + 8);
  124. k3 = Pack.LE_To_UInt32(kBytes, kOff + 12);
  125. }
  126. public string AlgorithmName
  127. {
  128. get { return cipher == null ? "Poly1305" : "Poly1305-" + cipher.AlgorithmName; }
  129. }
  130. public int GetMacSize()
  131. {
  132. return BlockSize;
  133. }
  134. public void Update(byte input)
  135. {
  136. currentBlock[currentBlockOffset++] = input;
  137. if (currentBlockOffset == BlockSize)
  138. {
  139. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  140. ProcessBlock(currentBlock);
  141. #else
  142. ProcessBlock(currentBlock, 0);
  143. #endif
  144. currentBlockOffset = 0;
  145. }
  146. }
  147. public void BlockUpdate(byte[] input, int inOff, int len)
  148. {
  149. Check.DataLength(input, inOff, len, "input buffer too short");
  150. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  151. BlockUpdate(input.AsSpan(inOff, len));
  152. #else
  153. int available = BlockSize - currentBlockOffset;
  154. if (len < available)
  155. {
  156. Array.Copy(input, inOff, currentBlock, currentBlockOffset, len);
  157. currentBlockOffset += len;
  158. return;
  159. }
  160. int pos = 0;
  161. if (currentBlockOffset > 0)
  162. {
  163. Array.Copy(input, inOff, currentBlock, currentBlockOffset, available);
  164. pos = available;
  165. ProcessBlock(currentBlock, 0);
  166. }
  167. int remaining;
  168. while ((remaining = len - pos) >= BlockSize)
  169. {
  170. ProcessBlock(input, inOff + pos);
  171. pos += BlockSize;
  172. }
  173. Array.Copy(input, inOff + pos, currentBlock, 0, remaining);
  174. currentBlockOffset = remaining;
  175. #endif
  176. }
  177. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  178. public void BlockUpdate(ReadOnlySpan<byte> input)
  179. {
  180. int available = BlockSize - currentBlockOffset;
  181. if (input.Length < available)
  182. {
  183. input.CopyTo(currentBlock.AsSpan(currentBlockOffset));
  184. currentBlockOffset += input.Length;
  185. return;
  186. }
  187. int pos = 0;
  188. if (currentBlockOffset > 0)
  189. {
  190. input[..available].CopyTo(currentBlock.AsSpan(currentBlockOffset));
  191. pos = available;
  192. ProcessBlock(currentBlock);
  193. }
  194. int remaining;
  195. while ((remaining = input.Length - pos) >= BlockSize)
  196. {
  197. ProcessBlock(input[pos..]);
  198. pos += BlockSize;
  199. }
  200. input[pos..].CopyTo(currentBlock);
  201. currentBlockOffset = remaining;
  202. }
  203. #endif
  204. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  205. private void ProcessBlock(ReadOnlySpan<byte> block)
  206. {
  207. uint t0 = Pack.LE_To_UInt32(block);
  208. uint t1 = Pack.LE_To_UInt32(block[4..]);
  209. uint t2 = Pack.LE_To_UInt32(block[8..]);
  210. uint t3 = Pack.LE_To_UInt32(block[12..]);
  211. #else
  212. private void ProcessBlock(byte[] buf, int off)
  213. {
  214. uint t0 = Pack.LE_To_UInt32(buf, off + 0);
  215. uint t1 = Pack.LE_To_UInt32(buf, off + 4);
  216. uint t2 = Pack.LE_To_UInt32(buf, off + 8);
  217. uint t3 = Pack.LE_To_UInt32(buf, off + 12);
  218. #endif
  219. h0 += t0 & 0x3ffffffU;
  220. h1 += ((t1 << 6) | (t0 >> 26)) & 0x3ffffffU;
  221. h2 += ((t2 << 12) | (t1 >> 20)) & 0x3ffffffU;
  222. h3 += ((t3 << 18) | (t2 >> 14)) & 0x3ffffffU;
  223. h4 += ( 1 << 24) | (t3 >> 8);
  224. ulong tp0 = (ulong)h0 * r0 + (ulong)h1 * s4 + (ulong)h2 * s3 + (ulong)h3 * s2 + (ulong)h4 * s1;
  225. ulong tp1 = (ulong)h0 * r1 + (ulong)h1 * r0 + (ulong)h2 * s4 + (ulong)h3 * s3 + (ulong)h4 * s2;
  226. ulong tp2 = (ulong)h0 * r2 + (ulong)h1 * r1 + (ulong)h2 * r0 + (ulong)h3 * s4 + (ulong)h4 * s3;
  227. ulong tp3 = (ulong)h0 * r3 + (ulong)h1 * r2 + (ulong)h2 * r1 + (ulong)h3 * r0 + (ulong)h4 * s4;
  228. ulong tp4 = (ulong)h0 * r4 + (ulong)h1 * r3 + (ulong)h2 * r2 + (ulong)h3 * r1 + (ulong)h4 * r0;
  229. h0 = (uint)tp0 & 0x3ffffff; tp1 += (tp0 >> 26);
  230. h1 = (uint)tp1 & 0x3ffffff; tp2 += (tp1 >> 26);
  231. h2 = (uint)tp2 & 0x3ffffff; tp3 += (tp2 >> 26);
  232. h3 = (uint)tp3 & 0x3ffffff; tp4 += (tp3 >> 26);
  233. h4 = (uint)tp4 & 0x3ffffff;
  234. h0 += (uint)(tp4 >> 26) * 5;
  235. h1 += h0 >> 26; h0 &= 0x3ffffff;
  236. }
  237. public int DoFinal(byte[] output, int outOff)
  238. {
  239. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  240. return DoFinal(output.AsSpan(outOff));
  241. #else
  242. Check.OutputLength(output, outOff, BlockSize, "output buffer is too short.");
  243. if (currentBlockOffset > 0)
  244. {
  245. // Process padded block
  246. if (currentBlockOffset < BlockSize)
  247. {
  248. currentBlock[currentBlockOffset++] = 1;
  249. while (currentBlockOffset < BlockSize)
  250. {
  251. currentBlock[currentBlockOffset++] = 0;
  252. }
  253. h4 -= (1 << 24);
  254. }
  255. ProcessBlock(currentBlock, 0);
  256. }
  257. Debug.Assert(h4 >> 26 == 0);
  258. //h0 += (h4 >> 26) * 5U + 5U; h4 &= 0x3ffffff;
  259. h0 += 5U;
  260. h1 += h0 >> 26; h0 &= 0x3ffffff;
  261. h2 += h1 >> 26; h1 &= 0x3ffffff;
  262. h3 += h2 >> 26; h2 &= 0x3ffffff;
  263. h4 += h3 >> 26; h3 &= 0x3ffffff;
  264. long c = ((int)(h4 >> 26) - 1) * 5;
  265. c += (long)k0 + ((h0 ) | (h1 << 26));
  266. Pack.UInt32_To_LE((uint)c, output, outOff ); c >>= 32;
  267. c += (long)k1 + ((h1 >> 6) | (h2 << 20));
  268. Pack.UInt32_To_LE((uint)c, output, outOff + 4); c >>= 32;
  269. c += (long)k2 + ((h2 >> 12) | (h3 << 14));
  270. Pack.UInt32_To_LE((uint)c, output, outOff + 8); c >>= 32;
  271. c += (long)k3 + ((h3 >> 18) | (h4 << 8));
  272. Pack.UInt32_To_LE((uint)c, output, outOff + 12);
  273. Reset();
  274. return BlockSize;
  275. #endif
  276. }
  277. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  278. public int DoFinal(Span<byte> output)
  279. {
  280. Check.OutputLength(output, BlockSize, "output buffer is too short.");
  281. if (currentBlockOffset > 0)
  282. {
  283. // Process padded block
  284. if (currentBlockOffset < BlockSize)
  285. {
  286. currentBlock[currentBlockOffset++] = 1;
  287. while (currentBlockOffset < BlockSize)
  288. {
  289. currentBlock[currentBlockOffset++] = 0;
  290. }
  291. h4 -= (1 << 24);
  292. }
  293. ProcessBlock(currentBlock);
  294. }
  295. Debug.Assert(h4 >> 26 == 0);
  296. //h0 += (h4 >> 26) * 5U + 5U; h4 &= 0x3ffffff;
  297. h0 += 5U;
  298. h1 += h0 >> 26; h0 &= 0x3ffffff;
  299. h2 += h1 >> 26; h1 &= 0x3ffffff;
  300. h3 += h2 >> 26; h2 &= 0x3ffffff;
  301. h4 += h3 >> 26; h3 &= 0x3ffffff;
  302. long c = ((int)(h4 >> 26) - 1) * 5;
  303. c += (long)k0 + ((h0) | (h1 << 26));
  304. Pack.UInt32_To_LE((uint)c, output); c >>= 32;
  305. c += (long)k1 + ((h1 >> 6) | (h2 << 20));
  306. Pack.UInt32_To_LE((uint)c, output[4..]); c >>= 32;
  307. c += (long)k2 + ((h2 >> 12) | (h3 << 14));
  308. Pack.UInt32_To_LE((uint)c, output[8..]); c >>= 32;
  309. c += (long)k3 + ((h3 >> 18) | (h4 << 8));
  310. Pack.UInt32_To_LE((uint)c, output[12..]);
  311. Reset();
  312. return BlockSize;
  313. }
  314. #endif
  315. public void Reset()
  316. {
  317. currentBlockOffset = 0;
  318. h0 = h1 = h2 = h3 = h4 = 0;
  319. }
  320. }
  321. }
  322. #pragma warning restore
  323. #endif