bn_mp_prime_miller_rabin.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_PRIME_MILLER_RABIN_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* Miller-Rabin test of "a" to the base of "b" as described in
  6. * HAC pp. 139 Algorithm 4.24
  7. *
  8. * Sets result to 0 if definitely composite or 1 if probably prime.
  9. * Randomly the chance of error is no more than 1/4 and often
  10. * very much lower.
  11. */
  12. mp_err mp_prime_miller_rabin(const mp_int *a, const mp_int *b, mp_bool *result)
  13. {
  14. mp_int n1, y, r;
  15. mp_err err;
  16. int s, j;
  17. /* default */
  18. *result = MP_NO;
  19. /* ensure b > 1 */
  20. if (mp_cmp_d(b, 1uL) != MP_GT) {
  21. return MP_VAL;
  22. }
  23. /* get n1 = a - 1 */
  24. if ((err = mp_init_copy(&n1, a)) != MP_OKAY) {
  25. return err;
  26. }
  27. if ((err = mp_sub_d(&n1, 1uL, &n1)) != MP_OKAY) {
  28. goto LBL_N1;
  29. }
  30. /* set 2**s * r = n1 */
  31. if ((err = mp_init_copy(&r, &n1)) != MP_OKAY) {
  32. goto LBL_N1;
  33. }
  34. /* count the number of least significant bits
  35. * which are zero
  36. */
  37. s = mp_cnt_lsb(&r);
  38. /* now divide n - 1 by 2**s */
  39. if ((err = mp_div_2d(&r, s, &r, NULL)) != MP_OKAY) {
  40. goto LBL_R;
  41. }
  42. /* compute y = b**r mod a */
  43. if ((err = mp_init(&y)) != MP_OKAY) {
  44. goto LBL_R;
  45. }
  46. if ((err = mp_exptmod(b, &r, a, &y)) != MP_OKAY) {
  47. goto LBL_Y;
  48. }
  49. /* if y != 1 and y != n1 do */
  50. if ((mp_cmp_d(&y, 1uL) != MP_EQ) && (mp_cmp(&y, &n1) != MP_EQ)) {
  51. j = 1;
  52. /* while j <= s-1 and y != n1 */
  53. while ((j <= (s - 1)) && (mp_cmp(&y, &n1) != MP_EQ)) {
  54. if ((err = mp_sqrmod(&y, a, &y)) != MP_OKAY) {
  55. goto LBL_Y;
  56. }
  57. /* if y == 1 then composite */
  58. if (mp_cmp_d(&y, 1uL) == MP_EQ) {
  59. goto LBL_Y;
  60. }
  61. ++j;
  62. }
  63. /* if y != n1 then composite */
  64. if (mp_cmp(&y, &n1) != MP_EQ) {
  65. goto LBL_Y;
  66. }
  67. }
  68. /* probably prime now */
  69. *result = MP_YES;
  70. LBL_Y:
  71. mp_clear(&y);
  72. LBL_R:
  73. mp_clear(&r);
  74. LBL_N1:
  75. mp_clear(&n1);
  76. return err;
  77. }
  78. #endif