smallprimes.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * smallprimes.c: implementation of the array of small primes defined
  3. * in sshkeygen.h.
  4. */
  5. #include <assert.h>
  6. #include "ssh.h"
  7. #include "sshkeygen.h"
  8. /* The real array that stores the primes. It has to be writable in
  9. * this module, but outside this module, we only expose the
  10. * const-qualified pointer 'smallprimes' so that nobody else can
  11. * accidentally overwrite it. */
  12. static unsigned short smallprimes_array[NSMALLPRIMES];
  13. const unsigned short *const smallprimes = smallprimes_array;
  14. void init_smallprimes(void)
  15. {
  16. if (smallprimes_array[0])
  17. return; /* already done */
  18. bool A[65536];
  19. for (size_t i = 2; i < lenof(A); i++)
  20. A[i] = true;
  21. for (size_t i = 2; i < lenof(A); i++) {
  22. if (!A[i])
  23. continue;
  24. for (size_t j = 2*i; j < lenof(A); j += i)
  25. A[j] = false;
  26. }
  27. size_t pos = 0;
  28. for (size_t i = 2; i < lenof(A); i++) {
  29. if (A[i]) {
  30. assert(pos < NSMALLPRIMES);
  31. smallprimes_array[pos++] = i;
  32. }
  33. }
  34. assert(pos == NSMALLPRIMES);
  35. }