bn_mp_prime_fermat.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <tommath.h>
  2. #ifdef BN_MP_PRIME_FERMAT_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 one Fermat test.
  18. *
  19. * If "a" were prime then b**a == b (mod a) since the order of
  20. * the multiplicative sub-group would be phi(a) = a-1. That means
  21. * it would be the same as b**(a mod (a-1)) == b**1 == b (mod a).
  22. *
  23. * Sets result to 1 if the congruence holds, or zero otherwise.
  24. */
  25. int mp_prime_fermat (mp_int * a, mp_int * b, int *result)
  26. {
  27. mp_int t;
  28. int err;
  29. /* default to composite */
  30. *result = MP_NO;
  31. /* ensure b > 1 */
  32. if (mp_cmp_d(b, 1) != MP_GT) {
  33. return MP_VAL;
  34. }
  35. /* init t */
  36. if ((err = mp_init (&t)) != MP_OKAY) {
  37. return err;
  38. }
  39. /* compute t = b**a mod a */
  40. if ((err = mp_exptmod (b, a, a, &t)) != MP_OKAY) {
  41. goto LBL_T;
  42. }
  43. /* is it equal to b? */
  44. if (mp_cmp (&t, b) == MP_EQ) {
  45. *result = MP_YES;
  46. }
  47. err = MP_OKAY;
  48. LBL_T:mp_clear (&t);
  49. return err;
  50. }
  51. #endif
  52. /* $Source: /cvs/libtom/libtommath/bn_mp_prime_fermat.c,v $ */
  53. /* $Revision: 1.3 $ */
  54. /* $Date: 2006/03/31 14:18:44 $ */