From 34d78286e6d096695d731428022bd42ea46df05d Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Thu, 3 Jan 2019 13:10:26 +0000 Subject: [PATCH] modsqrt: return success if taking square root of 0. My test for whether x has a square root was based on testing whether a large power of x was congruent to 1 mod p, which is a fine test provided x is in the multiplicative group of p, but would give a false negative on the one possible input value that _isn't_ - namely zero. The actual number returned from the function is fine (because that too is a large power of the input, and when the input is 0 that's foolproof). So I just needed to add a special case for the returned 'success' flag. --- mpint.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mpint.c b/mpint.c index 0285346b..bc587049 100644 --- a/mpint.c +++ b/mpint.c @@ -2286,7 +2286,10 @@ mp_int *monty_modsqrt(ModsqrtContext *sc, mp_int *x, unsigned *success) unsigned eq1 = mp_cmp_eq(&tmp, monty_identity(sc->mc)); if (i == 0) { - *success = eq1; + /* One special case: if x=0, then no power of x will ever + * equal 1, but we should still report success on the + * grounds that 0 does have a square root mod p. */ + *success = eq1 | mp_eq_integer(x, 0); } else { monty_mul_into(sc->mc, &tmp, toret, &power_of_zk); mp_select_into(toret, &tmp, toret, eq1);