bn_mp_exteuclid.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_EXTEUCLID_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* Extended euclidean algorithm of (a, b) produces
  6. a*u1 + b*u2 = u3
  7. */
  8. mp_err mp_exteuclid(const mp_int *a, const mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3)
  9. {
  10. mp_int u1, u2, u3, v1, v2, v3, t1, t2, t3, q, tmp;
  11. mp_err err;
  12. if ((err = mp_init_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL)) != MP_OKAY) {
  13. return err;
  14. }
  15. /* initialize, (u1,u2,u3) = (1,0,a) */
  16. mp_set(&u1, 1uL);
  17. if ((err = mp_copy(a, &u3)) != MP_OKAY) goto LBL_ERR;
  18. /* initialize, (v1,v2,v3) = (0,1,b) */
  19. mp_set(&v2, 1uL);
  20. if ((err = mp_copy(b, &v3)) != MP_OKAY) goto LBL_ERR;
  21. /* loop while v3 != 0 */
  22. while (!MP_IS_ZERO(&v3)) {
  23. /* q = u3/v3 */
  24. if ((err = mp_div(&u3, &v3, &q, NULL)) != MP_OKAY) goto LBL_ERR;
  25. /* (t1,t2,t3) = (u1,u2,u3) - (v1,v2,v3)q */
  26. if ((err = mp_mul(&v1, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
  27. if ((err = mp_sub(&u1, &tmp, &t1)) != MP_OKAY) goto LBL_ERR;
  28. if ((err = mp_mul(&v2, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
  29. if ((err = mp_sub(&u2, &tmp, &t2)) != MP_OKAY) goto LBL_ERR;
  30. if ((err = mp_mul(&v3, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
  31. if ((err = mp_sub(&u3, &tmp, &t3)) != MP_OKAY) goto LBL_ERR;
  32. /* (u1,u2,u3) = (v1,v2,v3) */
  33. if ((err = mp_copy(&v1, &u1)) != MP_OKAY) goto LBL_ERR;
  34. if ((err = mp_copy(&v2, &u2)) != MP_OKAY) goto LBL_ERR;
  35. if ((err = mp_copy(&v3, &u3)) != MP_OKAY) goto LBL_ERR;
  36. /* (v1,v2,v3) = (t1,t2,t3) */
  37. if ((err = mp_copy(&t1, &v1)) != MP_OKAY) goto LBL_ERR;
  38. if ((err = mp_copy(&t2, &v2)) != MP_OKAY) goto LBL_ERR;
  39. if ((err = mp_copy(&t3, &v3)) != MP_OKAY) goto LBL_ERR;
  40. }
  41. /* make sure U3 >= 0 */
  42. if (u3.sign == MP_NEG) {
  43. if ((err = mp_neg(&u1, &u1)) != MP_OKAY) goto LBL_ERR;
  44. if ((err = mp_neg(&u2, &u2)) != MP_OKAY) goto LBL_ERR;
  45. if ((err = mp_neg(&u3, &u3)) != MP_OKAY) goto LBL_ERR;
  46. }
  47. /* copy result out */
  48. if (U1 != NULL) {
  49. mp_exch(U1, &u1);
  50. }
  51. if (U2 != NULL) {
  52. mp_exch(U2, &u2);
  53. }
  54. if (U3 != NULL) {
  55. mp_exch(U3, &u3);
  56. }
  57. err = MP_OKAY;
  58. LBL_ERR:
  59. mp_clear_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL);
  60. return err;
  61. }
  62. #endif