DsaParametersGenerator.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
  10. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
  11. {
  12. /**
  13. * Generate suitable parameters for DSA, in line with FIPS 186-2, or FIPS 186-3.
  14. */
  15. public class DsaParametersGenerator
  16. {
  17. private IDigest digest;
  18. private int L, N;
  19. private int certainty;
  20. private SecureRandom random;
  21. private bool use186_3;
  22. private int usageIndex;
  23. public DsaParametersGenerator()
  24. : this(new Sha1Digest())
  25. {
  26. }
  27. public DsaParametersGenerator(IDigest digest)
  28. {
  29. this.digest = digest;
  30. }
  31. /// <summary>Initialise the generator</summary>
  32. /// <remarks>This form can only be used for older DSA (pre-DSA2) parameters</remarks>
  33. /// <param name="size">the size of keys in bits (from 512 up to 1024, and a multiple of 64)</param>
  34. /// <param name="certainty">measure of robustness of primes (at least 80 for FIPS 186-2 compliance)</param>
  35. /// <param name="random">the source of randomness to use</param>
  36. public virtual void Init(
  37. int size,
  38. int certainty,
  39. SecureRandom random)
  40. {
  41. if (!IsValidDsaStrength(size))
  42. throw new ArgumentException("size must be from 512 - 1024 and a multiple of 64", "size");
  43. this.use186_3 = false;
  44. this.L = size;
  45. this.N = GetDefaultN(size);
  46. this.certainty = certainty;
  47. this.random = random;
  48. }
  49. /// <summary>Initialise the generator for DSA 2</summary>
  50. /// <remarks>You must use this Init method if you need to generate parameters for DSA 2 keys</remarks>
  51. /// <param name="parameters">An instance of <c>DsaParameterGenerationParameters</c> used to configure this generator</param>
  52. public virtual void Init(DsaParameterGenerationParameters parameters)
  53. {
  54. // TODO Should we enforce the minimum 'certainty' values as per C.3 Table C.1?
  55. this.use186_3 = true;
  56. this.L = parameters.L;
  57. this.N = parameters.N;
  58. this.certainty = parameters.Certainty;
  59. this.random = parameters.Random;
  60. this.usageIndex = parameters.UsageIndex;
  61. if ((L < 1024 || L > 3072) || L % 1024 != 0)
  62. throw new ArgumentException("Values must be between 1024 and 3072 and a multiple of 1024", "L");
  63. if (L == 1024 && N != 160)
  64. throw new ArgumentException("N must be 160 for L = 1024");
  65. if (L == 2048 && (N != 224 && N != 256))
  66. throw new ArgumentException("N must be 224 or 256 for L = 2048");
  67. if (L == 3072 && N != 256)
  68. throw new ArgumentException("N must be 256 for L = 3072");
  69. if (digest.GetDigestSize() * 8 < N)
  70. throw new InvalidOperationException("Digest output size too small for value of N");
  71. }
  72. /// <summary>Generates a set of <c>DsaParameters</c></summary>
  73. /// <remarks>Can take a while...</remarks>
  74. public virtual DsaParameters GenerateParameters()
  75. {
  76. return use186_3
  77. ? GenerateParameters_FIPS186_3()
  78. : GenerateParameters_FIPS186_2();
  79. }
  80. protected virtual DsaParameters GenerateParameters_FIPS186_2()
  81. {
  82. byte[] seed = new byte[20];
  83. byte[] part1 = new byte[20];
  84. byte[] part2 = new byte[20];
  85. byte[] u = new byte[20];
  86. int n = (L - 1) / 160;
  87. byte[] w = new byte[L / 8];
  88. if (!(digest is Sha1Digest))
  89. throw new InvalidOperationException("can only use SHA-1 for generating FIPS 186-2 parameters");
  90. for (;;)
  91. {
  92. random.NextBytes(seed);
  93. Hash(digest, seed, part1);
  94. Array.Copy(seed, 0, part2, 0, seed.Length);
  95. Inc(part2);
  96. Hash(digest, part2, part2);
  97. for (int i = 0; i != u.Length; i++)
  98. {
  99. u[i] = (byte)(part1[i] ^ part2[i]);
  100. }
  101. u[0] |= (byte)0x80;
  102. u[19] |= (byte)0x01;
  103. BigInteger q = new BigInteger(1, u);
  104. if (!q.IsProbablePrime(certainty))
  105. continue;
  106. byte[] offset = Arrays.Clone(seed);
  107. Inc(offset);
  108. for (int counter = 0; counter < 4096; ++counter)
  109. {
  110. for (int k = 0; k < n; k++)
  111. {
  112. Inc(offset);
  113. Hash(digest, offset, part1);
  114. Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
  115. }
  116. Inc(offset);
  117. Hash(digest, offset, part1);
  118. Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);
  119. w[0] |= (byte)0x80;
  120. BigInteger x = new BigInteger(1, w);
  121. BigInteger c = x.Mod(q.ShiftLeft(1));
  122. BigInteger p = x.Subtract(c.Subtract(BigInteger.One));
  123. if (p.BitLength != L)
  124. continue;
  125. if (p.IsProbablePrime(certainty))
  126. {
  127. BigInteger g = CalculateGenerator_FIPS186_2(p, q, random);
  128. return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
  129. }
  130. }
  131. }
  132. }
  133. protected virtual BigInteger CalculateGenerator_FIPS186_2(BigInteger p, BigInteger q, SecureRandom r)
  134. {
  135. BigInteger e = p.Subtract(BigInteger.One).Divide(q);
  136. BigInteger pSub2 = p.Subtract(BigInteger.Two);
  137. for (;;)
  138. {
  139. BigInteger h = BigIntegers.CreateRandomInRange(BigInteger.Two, pSub2, r);
  140. BigInteger g = h.ModPow(e, p);
  141. if (g.BitLength > 1)
  142. return g;
  143. }
  144. }
  145. /**
  146. * generate suitable parameters for DSA, in line with
  147. * <i>FIPS 186-3 A.1 Generation of the FFC Primes p and q</i>.
  148. */
  149. protected virtual DsaParameters GenerateParameters_FIPS186_3()
  150. {
  151. // A.1.1.2 Generation of the Probable Primes p and q Using an Approved Hash Function
  152. IDigest d = digest;
  153. int outlen = d.GetDigestSize() * 8;
  154. // 1. Check that the (L, N) pair is in the list of acceptable (L, N pairs) (see Section 4.2). If
  155. // the pair is not in the list, then return INVALID.
  156. // Note: checked at initialisation
  157. // 2. If (seedlen < N), then return INVALID.
  158. // FIXME This should be configurable (must be >= N)
  159. int seedlen = N;
  160. byte[] seed = new byte[seedlen / 8];
  161. // 3. n = ceiling(L ⁄ outlen) – 1.
  162. int n = (L - 1) / outlen;
  163. // 4. b = L – 1 – (n ∗ outlen).
  164. int b = (L - 1) % outlen;
  165. byte[] output = new byte[d.GetDigestSize()];
  166. for (;;)
  167. {
  168. // 5. Get an arbitrary sequence of seedlen bits as the domain_parameter_seed.
  169. random.NextBytes(seed);
  170. // 6. U = Hash (domain_parameter_seed) mod 2^(N–1).
  171. Hash(d, seed, output);
  172. BigInteger U = new BigInteger(1, output).Mod(BigInteger.One.ShiftLeft(N - 1));
  173. // 7. q = 2^(N–1) + U + 1 – ( U mod 2).
  174. BigInteger q = U.SetBit(0).SetBit(N - 1);
  175. // 8. Test whether or not q is prime as specified in Appendix C.3.
  176. // TODO Review C.3 for primality checking
  177. if (!q.IsProbablePrime(certainty))
  178. {
  179. // 9. If q is not a prime, then go to step 5.
  180. continue;
  181. }
  182. // 10. offset = 1.
  183. // Note: 'offset' value managed incrementally
  184. byte[] offset = Arrays.Clone(seed);
  185. // 11. For counter = 0 to (4L – 1) do
  186. int counterLimit = 4 * L;
  187. for (int counter = 0; counter < counterLimit; ++counter)
  188. {
  189. // 11.1 For j = 0 to n do
  190. // Vj = Hash ((domain_parameter_seed + offset + j) mod 2^seedlen).
  191. // 11.2 W = V0 + (V1 ∗ 2^outlen) + ... + (V^(n–1) ∗ 2^((n–1) ∗ outlen)) + ((Vn mod 2^b) ∗ 2^(n ∗ outlen)).
  192. // TODO Assemble w as a byte array
  193. BigInteger W = BigInteger.Zero;
  194. for (int j = 0, exp = 0; j <= n; ++j, exp += outlen)
  195. {
  196. Inc(offset);
  197. Hash(d, offset, output);
  198. BigInteger Vj = new BigInteger(1, output);
  199. if (j == n)
  200. {
  201. Vj = Vj.Mod(BigInteger.One.ShiftLeft(b));
  202. }
  203. W = W.Add(Vj.ShiftLeft(exp));
  204. }
  205. // 11.3 X = W + 2^(L–1). Comment: 0 ≤ W < 2L–1; hence, 2L–1 ≤ X < 2L.
  206. BigInteger X = W.Add(BigInteger.One.ShiftLeft(L - 1));
  207. // 11.4 c = X mod 2q.
  208. BigInteger c = X.Mod(q.ShiftLeft(1));
  209. // 11.5 p = X - (c - 1). Comment: p ≡ 1 (mod 2q).
  210. BigInteger p = X.Subtract(c.Subtract(BigInteger.One));
  211. // 11.6 If (p < 2^(L - 1)), then go to step 11.9
  212. if (p.BitLength != L)
  213. continue;
  214. // 11.7 Test whether or not p is prime as specified in Appendix C.3.
  215. // TODO Review C.3 for primality checking
  216. if (p.IsProbablePrime(certainty))
  217. {
  218. // 11.8 If p is determined to be prime, then return VALID and the values of p, q and
  219. // (optionally) the values of domain_parameter_seed and counter.
  220. // TODO Make configurable (8-bit unsigned)?
  221. if (usageIndex >= 0)
  222. {
  223. BigInteger g = CalculateGenerator_FIPS186_3_Verifiable(d, p, q, seed, usageIndex);
  224. if (g != null)
  225. return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter, usageIndex));
  226. }
  227. {
  228. BigInteger g = CalculateGenerator_FIPS186_3_Unverifiable(p, q, random);
  229. return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
  230. }
  231. }
  232. // 11.9 offset = offset + n + 1. Comment: Increment offset; then, as part of
  233. // the loop in step 11, increment counter; if
  234. // counter < 4L, repeat steps 11.1 through 11.8.
  235. // Note: 'offset' value already incremented in inner loop
  236. }
  237. // 12. Go to step 5.
  238. }
  239. }
  240. protected virtual BigInteger CalculateGenerator_FIPS186_3_Unverifiable(BigInteger p, BigInteger q,
  241. SecureRandom r)
  242. {
  243. return CalculateGenerator_FIPS186_2(p, q, r);
  244. }
  245. protected virtual BigInteger CalculateGenerator_FIPS186_3_Verifiable(IDigest d, BigInteger p, BigInteger q,
  246. byte[] seed, int index)
  247. {
  248. // A.2.3 Verifiable Canonical Generation of the Generator g
  249. BigInteger e = p.Subtract(BigInteger.One).Divide(q);
  250. byte[] ggen = Hex.DecodeStrict("6767656E");
  251. // 7. U = domain_parameter_seed || "ggen" || index || count.
  252. byte[] U = new byte[seed.Length + ggen.Length + 1 + 2];
  253. Array.Copy(seed, 0, U, 0, seed.Length);
  254. Array.Copy(ggen, 0, U, seed.Length, ggen.Length);
  255. U[U.Length - 3] = (byte)index;
  256. byte[] w = new byte[d.GetDigestSize()];
  257. for (int count = 1; count < (1 << 16); ++count)
  258. {
  259. Inc(U);
  260. Hash(d, U, w);
  261. BigInteger W = new BigInteger(1, w);
  262. BigInteger g = W.ModPow(e, p);
  263. if (g.CompareTo(BigInteger.Two) >= 0)
  264. return g;
  265. }
  266. return null;
  267. }
  268. private static bool IsValidDsaStrength(
  269. int strength)
  270. {
  271. return strength >= 512 && strength <= 1024 && strength % 64 == 0;
  272. }
  273. protected static void Hash(IDigest d, byte[] input, byte[] output)
  274. {
  275. d.BlockUpdate(input, 0, input.Length);
  276. d.DoFinal(output, 0);
  277. }
  278. private static int GetDefaultN(int L)
  279. {
  280. return L > 1024 ? 256 : 160;
  281. }
  282. protected static void Inc(byte[] buf)
  283. {
  284. for (int i = buf.Length - 1; i >= 0; --i)
  285. {
  286. byte b = (byte)(buf[i] + 1);
  287. buf[i] = b;
  288. if (b != 0)
  289. break;
  290. }
  291. }
  292. }
  293. }
  294. #pragma warning restore
  295. #endif