bn_mp_exptmod.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_EXPTMOD_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* this is a shell function that calls either the normal or Montgomery
  6. * exptmod functions. Originally the call to the montgomery code was
  7. * embedded in the normal function but that wasted alot of stack space
  8. * for nothing (since 99% of the time the Montgomery code would be called)
  9. */
  10. mp_err mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y)
  11. {
  12. int dr;
  13. /* modulus P must be positive */
  14. if (P->sign == MP_NEG) {
  15. return MP_VAL;
  16. }
  17. /* if exponent X is negative we have to recurse */
  18. if (X->sign == MP_NEG) {
  19. mp_int tmpG, tmpX;
  20. mp_err err;
  21. if (!MP_HAS(MP_INVMOD)) {
  22. return MP_VAL;
  23. }
  24. if ((err = mp_init_multi(&tmpG, &tmpX, NULL)) != MP_OKAY) {
  25. return err;
  26. }
  27. /* first compute 1/G mod P */
  28. if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
  29. goto LBL_ERR;
  30. }
  31. /* now get |X| */
  32. if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
  33. goto LBL_ERR;
  34. }
  35. /* and now compute (1/G)**|X| instead of G**X [X < 0] */
  36. err = mp_exptmod(&tmpG, &tmpX, P, Y);
  37. LBL_ERR:
  38. mp_clear_multi(&tmpG, &tmpX, NULL);
  39. return err;
  40. }
  41. /* modified diminished radix reduction */
  42. if (MP_HAS(MP_REDUCE_IS_2K_L) && MP_HAS(MP_REDUCE_2K_L) && MP_HAS(S_MP_EXPTMOD) &&
  43. (mp_reduce_is_2k_l(P) == MP_YES)) {
  44. return s_mp_exptmod(G, X, P, Y, 1);
  45. }
  46. /* is it a DR modulus? default to no */
  47. dr = (MP_HAS(MP_DR_IS_MODULUS) && (mp_dr_is_modulus(P) == MP_YES)) ? 1 : 0;
  48. /* if not, is it a unrestricted DR modulus? */
  49. if (MP_HAS(MP_REDUCE_IS_2K) && (dr == 0)) {
  50. dr = (mp_reduce_is_2k(P) == MP_YES) ? 2 : 0;
  51. }
  52. /* if the modulus is odd or dr != 0 use the montgomery method */
  53. if (MP_HAS(S_MP_EXPTMOD_FAST) && (MP_IS_ODD(P) || (dr != 0))) {
  54. return s_mp_exptmod_fast(G, X, P, Y, dr);
  55. } else if (MP_HAS(S_MP_EXPTMOD)) {
  56. /* otherwise use the generic Barrett reduction technique */
  57. return s_mp_exptmod(G, X, P, Y, 0);
  58. } else {
  59. /* no exptmod for evens */
  60. return MP_VAL;
  61. }
  62. }
  63. #endif