Poly1305.cs 11 KB

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