rsa.c 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. * RSA key generation.
  3. */
  4. #include <assert.h>
  5. #include "ssh.h"
  6. #include "sshkeygen.h"
  7. #include "mpint.h"
  8. #define RSA_EXPONENT 65537
  9. #define NFIRSTBITS 13
  10. static void invent_firstbits(unsigned *one, unsigned *two,
  11. unsigned min_separation);
  12. typedef struct RSAPrimeDetails RSAPrimeDetails;
  13. struct RSAPrimeDetails {
  14. bool strong;
  15. int bits, bitsm1m1, bitsm1, bitsp1;
  16. unsigned firstbits;
  17. ProgressPhase phase_main, phase_m1m1, phase_m1, phase_p1;
  18. };
  19. #define STRONG_MARGIN (20 + NFIRSTBITS)
  20. static RSAPrimeDetails setup_rsa_prime(
  21. int bits, bool strong, PrimeGenerationContext *pgc, ProgressReceiver *prog)
  22. {
  23. RSAPrimeDetails pd;
  24. pd.bits = bits;
  25. if (strong) {
  26. pd.bitsm1 = (bits - STRONG_MARGIN) / 2;
  27. pd.bitsp1 = (bits - STRONG_MARGIN) - pd.bitsm1;
  28. pd.bitsm1m1 = (pd.bitsm1 - STRONG_MARGIN) / 2;
  29. if (pd.bitsm1m1 < STRONG_MARGIN) {
  30. /* Absurdly small prime, but we should at least not crash. */
  31. strong = false;
  32. }
  33. }
  34. pd.strong = strong;
  35. if (pd.strong) {
  36. pd.phase_m1m1 = primegen_add_progress_phase(pgc, prog, pd.bitsm1m1);
  37. pd.phase_m1 = primegen_add_progress_phase(pgc, prog, pd.bitsm1);
  38. pd.phase_p1 = primegen_add_progress_phase(pgc, prog, pd.bitsp1);
  39. }
  40. pd.phase_main = primegen_add_progress_phase(pgc, prog, pd.bits);
  41. return pd;
  42. }
  43. static mp_int *generate_rsa_prime(
  44. RSAPrimeDetails pd, PrimeGenerationContext *pgc, ProgressReceiver *prog)
  45. {
  46. mp_int *m1m1 = NULL, *m1 = NULL, *p1 = NULL, *p = NULL;
  47. PrimeCandidateSource *pcs;
  48. if (pd.strong) {
  49. progress_start_phase(prog, pd.phase_m1m1);
  50. pcs = pcs_new_with_firstbits(pd.bitsm1m1, pd.firstbits, NFIRSTBITS);
  51. m1m1 = primegen_generate(pgc, pcs, prog);
  52. progress_report_phase_complete(prog);
  53. progress_start_phase(prog, pd.phase_m1);
  54. pcs = pcs_new_with_firstbits(pd.bitsm1, pd.firstbits, NFIRSTBITS);
  55. pcs_require_residue_1_mod_prime(pcs, m1m1);
  56. m1 = primegen_generate(pgc, pcs, prog);
  57. progress_report_phase_complete(prog);
  58. progress_start_phase(prog, pd.phase_p1);
  59. pcs = pcs_new_with_firstbits(pd.bitsp1, pd.firstbits, NFIRSTBITS);
  60. p1 = primegen_generate(pgc, pcs, prog);
  61. progress_report_phase_complete(prog);
  62. }
  63. progress_start_phase(prog, pd.phase_main);
  64. pcs = pcs_new_with_firstbits(pd.bits, pd.firstbits, NFIRSTBITS);
  65. pcs_avoid_residue_small(pcs, RSA_EXPONENT, 1);
  66. if (pd.strong) {
  67. pcs_require_residue_1_mod_prime(pcs, m1);
  68. mp_int *p1_minus_1 = mp_copy(p1);
  69. mp_sub_integer_into(p1_minus_1, p1, 1);
  70. pcs_require_residue(pcs, p1, p1_minus_1);
  71. mp_free(p1_minus_1);
  72. }
  73. p = primegen_generate(pgc, pcs, prog);
  74. progress_report_phase_complete(prog);
  75. if (m1m1)
  76. mp_free(m1m1);
  77. if (m1)
  78. mp_free(m1);
  79. if (p1)
  80. mp_free(p1);
  81. return p;
  82. }
  83. int rsa_generate(RSAKey *key, int bits, bool strong,
  84. PrimeGenerationContext *pgc, ProgressReceiver *prog)
  85. {
  86. key->sshk.vt = &ssh_rsa;
  87. /*
  88. * We don't generate e; we just use a standard one always.
  89. */
  90. mp_int *exponent = mp_from_integer(RSA_EXPONENT);
  91. /*
  92. * Generate p and q: primes with combined length `bits', not
  93. * congruent to 1 modulo e. (Strictly speaking, we wanted (p-1)
  94. * and e to be coprime, and (q-1) and e to be coprime, but in
  95. * general that's slightly more fiddly to arrange. By choosing
  96. * a prime e, we can simplify the criterion.)
  97. *
  98. * We give a min_separation of 2 to invent_firstbits(), ensuring
  99. * that the two primes won't be very close to each other. (The
  100. * chance of them being _dangerously_ close is negligible - even
  101. * more so than an attacker guessing a whole 256-bit session key -
  102. * but it doesn't cost much to make sure.)
  103. */
  104. int qbits = bits / 2;
  105. int pbits = bits - qbits;
  106. assert(pbits >= qbits);
  107. RSAPrimeDetails pd = setup_rsa_prime(pbits, strong, pgc, prog);
  108. RSAPrimeDetails qd = setup_rsa_prime(qbits, strong, pgc, prog);
  109. progress_ready(prog);
  110. invent_firstbits(&pd.firstbits, &qd.firstbits, 2);
  111. mp_int *p = generate_rsa_prime(pd, pgc, prog);
  112. mp_int *q = generate_rsa_prime(qd, pgc, prog);
  113. /*
  114. * Ensure p > q, by swapping them if not.
  115. *
  116. * We only need to do this if the two primes were generated with
  117. * the same number of bits (i.e. if the requested key size is
  118. * even) - otherwise it's already guaranteed!
  119. */
  120. if (pbits == qbits) {
  121. mp_cond_swap(p, q, mp_cmp_hs(q, p));
  122. } else {
  123. assert(mp_cmp_hs(p, q));
  124. }
  125. /*
  126. * Now we have p, q and e. All we need to do now is work out
  127. * the other helpful quantities: n=pq, d=e^-1 mod (p-1)(q-1),
  128. * and (q^-1 mod p).
  129. */
  130. mp_int *modulus = mp_mul(p, q);
  131. mp_int *pm1 = mp_copy(p);
  132. mp_sub_integer_into(pm1, pm1, 1);
  133. mp_int *qm1 = mp_copy(q);
  134. mp_sub_integer_into(qm1, qm1, 1);
  135. mp_int *phi_n = mp_mul(pm1, qm1);
  136. mp_free(pm1);
  137. mp_free(qm1);
  138. mp_int *private_exponent = mp_invert(exponent, phi_n);
  139. mp_free(phi_n);
  140. mp_int *iqmp = mp_invert(q, p);
  141. /*
  142. * Populate the returned structure.
  143. */
  144. key->modulus = modulus;
  145. key->exponent = exponent;
  146. key->private_exponent = private_exponent;
  147. key->p = p;
  148. key->q = q;
  149. key->iqmp = iqmp;
  150. key->bits = mp_get_nbits(modulus);
  151. key->bytes = (key->bits + 7) / 8;
  152. return 1;
  153. }
  154. /*
  155. * Invent a pair of values suitable for use as the 'firstbits' values
  156. * for the two RSA primes, such that their product is at least 2, and
  157. * such that their difference is also at least min_separation.
  158. *
  159. * This is used for generating RSA keys which have exactly the
  160. * specified number of bits rather than one fewer - if you generate an
  161. * a-bit and a b-bit number completely at random and multiply them
  162. * together, you could end up with either an (ab-1)-bit number or an
  163. * (ab)-bit number. The former happens log(2)*2-1 of the time (about
  164. * 39%) and, though actually harmless, every time it occurs it has a
  165. * non-zero probability of sparking a user email along the lines of
  166. * 'Hey, I asked PuTTYgen for a 2048-bit key and I only got 2047 bits!
  167. * Bug!'
  168. */
  169. static inline unsigned firstbits_b_min(
  170. unsigned a, unsigned lo, unsigned hi, unsigned min_separation)
  171. {
  172. /* To get a large enough product, b must be at least this much */
  173. unsigned b_min = (2*lo*lo + a - 1) / a;
  174. /* Now enforce a<b, optionally with minimum separation */
  175. if (b_min < a + min_separation)
  176. b_min = a + min_separation;
  177. /* And cap at the upper limit */
  178. if (b_min > hi)
  179. b_min = hi;
  180. return b_min;
  181. }
  182. static void invent_firstbits(unsigned *one, unsigned *two,
  183. unsigned min_separation)
  184. {
  185. /*
  186. * We'll pick 12 initial bits (number selected at random) for each
  187. * prime, not counting the leading 1. So we want to return two
  188. * values in the range [2^12,2^13) whose product is at least 2^25.
  189. *
  190. * Strategy: count up all the viable pairs, then select a random
  191. * number in that range and use it to pick a pair.
  192. *
  193. * To keep things simple, we'll ensure a < b, and randomly swap
  194. * them at the end.
  195. */
  196. const unsigned lo = 1<<12, hi = 1<<13, minproduct = 2*lo*lo;
  197. unsigned a, b;
  198. /*
  199. * Count up the number of prefixes of b that would be valid for
  200. * each prefix of a.
  201. */
  202. mp_int *total = mp_new(32);
  203. for (a = lo; a < hi; a++) {
  204. unsigned b_min = firstbits_b_min(a, lo, hi, min_separation);
  205. mp_add_integer_into(total, total, hi - b_min);
  206. }
  207. /*
  208. * Make up a random number in the range [0,2*total).
  209. */
  210. mp_int *mlo = mp_from_integer(0), *mhi = mp_new(32);
  211. mp_lshift_fixed_into(mhi, total, 1);
  212. mp_int *randval = mp_random_in_range(mlo, mhi);
  213. mp_free(mlo);
  214. mp_free(mhi);
  215. /*
  216. * Use the low bit of randval as our swap indicator, leaving the
  217. * rest of it in the range [0,total).
  218. */
  219. unsigned swap = mp_get_bit(randval, 0);
  220. mp_rshift_fixed_into(randval, randval, 1);
  221. /*
  222. * Now do the same counting loop again to make the actual choice.
  223. */
  224. a = b = 0;
  225. for (unsigned a_candidate = lo; a_candidate < hi; a_candidate++) {
  226. unsigned b_min = firstbits_b_min(a_candidate, lo, hi, min_separation);
  227. unsigned limit = hi - b_min;
  228. unsigned b_candidate = b_min + mp_get_integer(randval);
  229. unsigned use_it = 1 ^ mp_hs_integer(randval, limit);
  230. a ^= (a ^ a_candidate) & -use_it;
  231. b ^= (b ^ b_candidate) & -use_it;
  232. mp_sub_integer_into(randval, randval, limit);
  233. }
  234. mp_free(randval);
  235. mp_free(total);
  236. /*
  237. * Check everything came out right.
  238. */
  239. assert(lo <= a);
  240. assert(a < hi);
  241. assert(lo <= b);
  242. assert(b < hi);
  243. assert(a * b >= minproduct);
  244. assert(b >= a + min_separation);
  245. /*
  246. * Last-minute optional swap of a and b.
  247. */
  248. unsigned diff = (a ^ b) & (-swap);
  249. a ^= diff;
  250. b ^= diff;
  251. *one = a;
  252. *two = b;
  253. }