bn_mp_prime_fermat.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_PRIME_FERMAT_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* performs one Fermat test.
  6. *
  7. * If "a" were prime then b**a == b (mod a) since the order of
  8. * the multiplicative sub-group would be phi(a) = a-1. That means
  9. * it would be the same as b**(a mod (a-1)) == b**1 == b (mod a).
  10. *
  11. * Sets result to 1 if the congruence holds, or zero otherwise.
  12. */
  13. mp_err mp_prime_fermat(const mp_int *a, const mp_int *b, mp_bool *result)
  14. {
  15. mp_int t;
  16. mp_err err;
  17. /* default to composite */
  18. *result = MP_NO;
  19. /* ensure b > 1 */
  20. if (mp_cmp_d(b, 1uL) != MP_GT) {
  21. return MP_VAL;
  22. }
  23. /* init t */
  24. if ((err = mp_init(&t)) != MP_OKAY) {
  25. return err;
  26. }
  27. /* compute t = b**a mod a */
  28. if ((err = mp_exptmod(b, a, a, &t)) != MP_OKAY) {
  29. goto LBL_T;
  30. }
  31. /* is it equal to b? */
  32. if (mp_cmp(&t, b) == MP_EQ) {
  33. *result = MP_YES;
  34. }
  35. err = MP_OKAY;
  36. LBL_T:
  37. mp_clear(&t);
  38. return err;
  39. }
  40. #endif