bn_mp_prime_is_prime.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <tommath.h>
  2. #ifdef BN_MP_PRIME_IS_PRIME_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis
  4. *
  5. * LibTomMath is a library that provides multiple-precision
  6. * integer arithmetic as well as number theoretic functionality.
  7. *
  8. * The library was designed directly after the MPI library by
  9. * Michael Fromberger but has been written from scratch with
  10. * additional optimizations in place.
  11. *
  12. * The library is free for all purposes without any express
  13. * guarantee it works.
  14. *
  15. * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
  16. */
  17. /* performs a variable number of rounds of Miller-Rabin
  18. *
  19. * Probability of error after t rounds is no more than
  20. *
  21. * Sets result to 1 if probably prime, 0 otherwise
  22. */
  23. int mp_prime_is_prime (mp_int * a, int t, int *result)
  24. {
  25. mp_int b;
  26. int ix, err, res;
  27. /* default to no */
  28. *result = MP_NO;
  29. /* valid value of t? */
  30. if (t <= 0 || t > PRIME_SIZE) {
  31. return MP_VAL;
  32. }
  33. /* is the input equal to one of the primes in the table? */
  34. for (ix = 0; ix < PRIME_SIZE; ix++) {
  35. if (mp_cmp_d(a, ltm_prime_tab[ix]) == MP_EQ) {
  36. *result = 1;
  37. return MP_OKAY;
  38. }
  39. }
  40. /* first perform trial division */
  41. if ((err = mp_prime_is_divisible (a, &res)) != MP_OKAY) {
  42. return err;
  43. }
  44. /* return if it was trivially divisible */
  45. if (res == MP_YES) {
  46. return MP_OKAY;
  47. }
  48. /* now perform the miller-rabin rounds */
  49. if ((err = mp_init (&b)) != MP_OKAY) {
  50. return err;
  51. }
  52. for (ix = 0; ix < t; ix++) {
  53. /* set the prime */
  54. mp_set (&b, ltm_prime_tab[ix]);
  55. if ((err = mp_prime_miller_rabin (a, &b, &res)) != MP_OKAY) {
  56. goto LBL_B;
  57. }
  58. if (res == MP_NO) {
  59. goto LBL_B;
  60. }
  61. }
  62. /* passed the test */
  63. *result = MP_YES;
  64. LBL_B:mp_clear (&b);
  65. return err;
  66. }
  67. #endif
  68. /* $Source: /cvs/libtom/libtommath/bn_mp_prime_is_prime.c,v $ */
  69. /* $Revision: 1.3 $ */
  70. /* $Date: 2006/03/31 14:18:44 $ */