rand_prime.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis
  2. *
  3. * LibTomCrypt is a library that provides various cryptographic
  4. * algorithms in a highly modular and flexible manner.
  5. *
  6. * The library is free for all purposes without any express
  7. * guarantee it works.
  8. *
  9. * Tom St Denis, [email protected], http://libtomcrypt.org
  10. */
  11. #include "mycrypt.h"
  12. #ifdef MPI
  13. struct rng_data {
  14. prng_state *prng;
  15. int wprng;
  16. };
  17. static int rand_prime_helper(unsigned char *dst, int len, void *dat)
  18. {
  19. return (int)prng_descriptor[((struct rng_data *)dat)->wprng].read(dst, len, ((struct rng_data *)dat)->prng);
  20. }
  21. int rand_prime(mp_int *N, long len, prng_state *prng, int wprng)
  22. {
  23. struct rng_data rng;
  24. int type, err;
  25. _ARGCHK(N != NULL);
  26. /* allow sizes between 2 and 256 bytes for a prime size */
  27. if (len < 16 || len > 4096) {
  28. return CRYPT_INVALID_PRIME_SIZE;
  29. }
  30. /* valid PRNG? Better be! */
  31. if ((err = prng_is_valid(wprng)) != CRYPT_OK) {
  32. return err;
  33. }
  34. /* setup our callback data, then world domination! */
  35. rng.prng = prng;
  36. rng.wprng = wprng;
  37. /* get type */
  38. if (len < 0) {
  39. type = LTM_PRIME_BBS;
  40. len = -len;
  41. } else {
  42. type = 0;
  43. }
  44. /* New prime generation makes the code even more cryptoish-insane. Do you know what this means!!!
  45. -- Gir: Yeah, oh wait, er, no.
  46. */
  47. return mpi_to_ltc_error(mp_prime_random_ex(N, mp_prime_rabin_miller_trials(len), len, type, rand_prime_helper, &rng));
  48. }
  49. #endif