mirror of
https://git.tartarus.org/simon/putty.git
synced 2025-07-02 20:12:48 -05:00
Fix RSA key gen at awkward sizes mod BIGNUM_INT_BITS.
If you try to generate (say) a 2049-bit RSA key, then primegen will try to generate a 1025-bit prime. It will do it by making a random 1024-bit mp_int (that is, one strictly _less_ than 2^1024), and then trying to set bit 1024. But that will fail an assertion in mp_set_bit, because the number of random bits is a multiple of BIGNUM_INT_BITS, so an mp_int of the minimum size that can hold the random bits is not quite big enough to hold the extra bit at the top. Fix: change the strategy in primegen so that we allocate the mp_int large enough to hold even the top bit, and copy in the random numbers via mp_or_into. There's a second bug hiding behind that one. If the key has odd size, then the two primes are generated with different bit lengths. If the overall key size is congruent to 1 mod (2*BIGNUM_INT_BITS), then the two primes will be allocated as mp_ints with different numbers of words, leading to another assertion failure in the mp_cond_swap that sorts the primes into a consistent order. Fix for that one: if the primes are being generated different bit lengths, then we arrange those lengths to be already in the right order, and replace the mp_cond_swap with an assert() that checks the ordering is already correct. Combined effect: now you should be able to successfully generate a 2049-bit key without assertion failures.
This commit is contained in:
@ -194,10 +194,12 @@ mp_int *primegen(
|
||||
* random number with the top bit set and the bottom bit clear,
|
||||
* multiply it by `factor', and add one.
|
||||
*/
|
||||
mp_int *p = mp_random_bits(bits - 1);
|
||||
mp_int *p = mp_power_2(bits - 1); /* ensure top bit is 1 */
|
||||
mp_int *r = mp_random_bits(bits - 1);
|
||||
mp_or_into(p, p, r);
|
||||
mp_free(r);
|
||||
mp_set_bit(p, 0, factor ? 0 : 1); /* set bottom bit appropriately */
|
||||
|
||||
mp_set_bit(p, 0, factor ? 0 : 1); /* bottom bit */
|
||||
mp_set_bit(p, bits-1, 1); /* top bit */
|
||||
for (size_t i = 0; i < fbsize; i++)
|
||||
mp_set_bit(p, bits-fbsize + i, 1 & (firstbits >> i));
|
||||
|
||||
|
Reference in New Issue
Block a user