1
0
mirror of https://git.tartarus.org/simon/putty.git synced 2025-07-02 20:12:48 -05:00

Move init_primes_array out into its own file.

Mostly because I just had a neat idea about how to expose that large
mutable array without it being a mutable global variable: make it a
static in its own module, and expose only a _pointer_ to it, which is
const-qualified.

While I'm there, changed the name to something more descriptive.
This commit is contained in:
Simon Tatham
2020-02-23 14:08:57 +00:00
parent 82df83719a
commit 9af72ca1e8
4 changed files with 73 additions and 40 deletions

View File

@ -5,6 +5,7 @@
#include <assert.h>
#include "ssh.h"
#include "mpint.h"
#include "sshkeygen.h"
/*
* This prime generation algorithm is pretty much cribbed from
@ -107,34 +108,6 @@
* but 1s.)
*/
static unsigned short primes[6542]; /* # primes < 65536 */
#define NPRIMES (lenof(primes))
static void init_primes_array(void)
{
if (primes[0])
return; /* already done */
bool A[65536];
for (size_t i = 2; i < lenof(A); i++)
A[i] = true;
for (size_t i = 2; i < lenof(A); i++) {
if (!A[i])
continue;
for (size_t j = 2*i; j < lenof(A); j += i)
A[j] = false;
}
size_t pos = 0;
for (size_t i = 2; i < lenof(A); i++)
if (A[i])
primes[pos++] = i;
assert(pos == NPRIMES);
}
static unsigned short mp_mod_short(mp_int *x, unsigned short modulus)
{
/*
@ -176,7 +149,7 @@ mp_int *primegen(
int bits, int modulus, int residue, mp_int *factor,
int phase, progfn_t pfn, void *pfnparam, unsigned firstbits)
{
init_primes_array();
init_smallprimes();
int progress = 0;
@ -220,16 +193,16 @@ mp_int *primegen(
*/
/* List the moduli */
unsigned long moduli[NPRIMES + 1];
for (size_t i = 0; i < NPRIMES; i++)
moduli[i] = primes[i];
moduli[NPRIMES] = modulus;
unsigned long moduli[NSMALLPRIMES + 1];
for (size_t i = 0; i < NSMALLPRIMES; i++)
moduli[i] = smallprimes[i];
moduli[NSMALLPRIMES] = modulus;
/* Find the residue of our starting number mod each of them. Also
* set up the multipliers array which tells us how each one will
* change when we increment the number (which isn't just 1 if
* we're incrementing by multiples of factor). */
unsigned long residues[NPRIMES + 1], multipliers[NPRIMES + 1];
unsigned long residues[NSMALLPRIMES + 1], multipliers[NSMALLPRIMES + 1];
for (size_t i = 0; i < lenof(moduli); i++) {
residues[i] = mp_mod_short(p, moduli[i]);
if (factor)
@ -239,7 +212,8 @@ mp_int *primegen(
}
/* Adjust the last entry so that it avoids a residue other than zero */
residues[NPRIMES] = (residues[NPRIMES] + modulus - residue) % modulus;
residues[NSMALLPRIMES] = (residues[NSMALLPRIMES] + modulus
- residue) % modulus;
/*
* Now loop until no residue in that list is zero, to find a