Commit fe382afd820d05f7287959067680b3e1c043bb04

Steffen Jaeckel 2020-03-05T22:37:59

Merge pull request #478 from MasterDuke17/make_exptmod_with_modulus_1_always_0 Give correct values for invmod with modulus of 1

diff --git a/demo/test.c b/demo/test.c
index 98a8499..2d1d774 100644
--- a/demo/test.c
+++ b/demo/test.c
@@ -135,10 +135,7 @@ static int test_trivial_stuff(void)
    mp_set(&b, 1u);
    DO(mp_neg(&b, &b));
    mp_set(&c, 1u);
-   /* I expected this works, but somehow the computer sez no
-    * DO(mp_exptmod(&a, &b, &c, &d));
-    */
-   EXPECT(mp_exptmod(&a, &b, &c, &d) != MP_OKAY);
+   DO(mp_exptmod(&a, &b, &c, &d));
 
    mp_set(&c, 7u);
    /* same here */
diff --git a/mp_invmod.c b/mp_invmod.c
index e19c067..2494acb 100644
--- a/mp_invmod.c
+++ b/mp_invmod.c
@@ -6,6 +6,12 @@
 /* hac 14.61, pp608 */
 mp_err mp_invmod(const mp_int *a, const mp_int *b, mp_int *c)
 {
+   /* for all n in N and n > 0, n = 0 mod 1 */
+   if (!mp_isneg(a) && mp_cmp_d(b, 1uL) == MP_EQ) {
+      mp_zero(c);
+      return MP_OKAY;
+   }
+
    /* b cannot be negative and has to be >1 */
    if (mp_isneg(b) || (mp_cmp_d(b, 1uL) != MP_GT)) {
       return MP_VAL;
diff --git a/tommath_class.h b/tommath_class.h
index 5e76e6a..0fe046f 100644
--- a/tommath_class.h
+++ b/tommath_class.h
@@ -440,6 +440,7 @@
 
 #if defined(MP_INVMOD_C)
 #   define MP_CMP_D_C
+#   define MP_ZERO_C
 #   define S_MP_INVMOD_C
 #   define S_MP_INVMOD_ODD_C
 #endif