TExcelTAD
Home › Number Theory & Cryptography › Square Roots Modulo a Prime

Square Roots Modulo a Prime

Euler's criterion says whether aa has a square root modulo pp. To find it, there is a one-liner when p≡3(mod4)p \equiv 3 \pmod 4 and the Tonelli-Shanks algorithm in general. Modulo a composite n=pqn = pq, by contrast, square roots are exactly as hard as factoring, a fact behind the Rabin cryptosystem.

The easy case: p≡3(mod4)p \equiv 3 \pmod 4

If aa is a QR and p≡3(mod4)p \equiv 3 \pmod 4, then x=a(p+1)/4x = a^{(p+1)/4} is a square root:

x2=a(p+1)/2=a⋅a(p−1)/2≡a⋅1=a(modp)x^2 = a^{(p+1)/2} = a \cdot a^{(p-1)/2} \equiv a \cdot 1 = a \pmod{p}

The exponent (p+1)/4(p + 1)/4 is an integer exactly because p≡3(mod4)p \equiv 3 \pmod 4.

python · try it yourself
p = 10007                          # 10007 = 3 (mod 4)
for a in (2, 3, 5):
    x = pow(a, (p + 1) // 4, p)
    print(a, "QR" if pow(a, (p - 1) // 2, p) == 1 else "QNR", x, x * x % p)
2 QR 2641 2
3 QR 8530 3
5 QNR 794 10002

For the non-residue 5, the formula returns a root of −5-5 instead; always check x2≡ax^2 \equiv a.

Tonelli-Shanks

For p≡1(mod4)p \equiv 1 \pmod 4 (like the P-224 prime, or p=2255−19p = 2^{255} - 19, which is ≡1(mod4)\equiv 1 \pmod 4), write p−1=2sqp - 1 = 2^s q with qq odd and take a non-residue zz. The algorithm starts with the guess x=a(q+1)/2x = a^{(q+1)/2}, whose error t=aqt = a^q has order a power of 2, and repeatedly multiplies by powers of c=zqc = z^q to shrink that order to 1.

python · try it yourself
def tonelli_shanks(a, p):
    a %= p
    if a == 0:
        return 0
    if pow(a, (p - 1) // 2, p) != 1:
        return None                                    # no square root
    q, s = p - 1, 0
    while q % 2 == 0:
        q, s = q // 2, s + 1
    z = next(z for z in range(2, p) if pow(z, (p - 1) // 2, p) == p - 1)
    m, c, t, x = s, pow(z, q, p), pow(a, q, p), pow(a, (q + 1) // 2, p)
    while t != 1:
        i, t2 = 0, t
        while t2 != 1:                                 # find the order 2^i of t
            t2, i = t2 * t2 % p, i + 1
        b = pow(c, 1 << (m - i - 1), p)
        m, c, t, x = i, b * b % p, t * b * b % p, x * b % p
    return x

for p, a in ((41, 5), (13, 10), (2**255 - 19, 4), (2**255 - 19, 5)):
    r = tonelli_shanks(a, p)
    print(p if p < 10**6 else "2^255-19", a, r if r is None or r < 10**6 else "big root", r is not None and r * r % p == a % p)
41 5 28 True
13 10 7 True
2^255-19 4 big root True
2^255-19 5 big root True

Every root comes in a pair ±x\pm x. The algorithm costs O(s2)O(s^2) multiplications on top of one exponentiation, fast for all primes used in practice.

Composite moduli: as hard as factoring

Modulo n=pqn = pq, a QR has four square roots: combine ±xp\pm x_p and ±xq\pm x_q with the CRT. Knowing pp and qq you find them easily. Conversely, anyone who can compute square roots mod nn can factor nn: pick random xx, ask for a root yy of x2x^2; with probability 1/2, y≢±xy \not\equiv \pm x, and then gcd⁡(x−y,n)\gcd(x - y, n) is a factor.

python · try it yourself
from math import gcd

p, q = 10007, 10039                          # both 3 mod 4
n = p * q

def sqrt_mod_n(a):                           # needs the factors
    rp, rq = pow(a, (p + 1) // 4, p), pow(a, (q + 1) // 4, q)
    roots = set()
    for sp in (rp, p - rp):
        for sq in (rq, q - rq):
            roots.add((sp * q * pow(q, -1, p) + sq * p * pow(p, -1, q)) % n)
    return sorted(roots)

x = 123456
roots = sqrt_mod_n(x * x % n)
print(roots, x in roots)
y = next(r for r in roots if r not in (x, n - x))
print("gcd(x - y, n) =", gcd(x - y, n))
[123456, 23122805, 77337468, 100336817] True
gcd(x - y, n) = 10039

The Rabin cryptosystem

Rabin encryption is c=m2 mod nc = m^2 \bmod n. Decryption with p,qp, q gives four candidates (so the message needs redundancy to pick the right one). Breaking it is provably as hard as factoring nn, a guarantee RSA lacks. It never became popular because of the four-root ambiguity and a chosen-ciphertext attack that is precisely the factoring argument above.

In software

  • Point decompression for P-256 and secp256k1 uses y=(x3+ax+b)(p+1)/4y = (x^3 + ax + b)^{(p+1)/4}, since those primes are ≡3(mod4)\equiv 3 \pmod 4. Ed25519 uses a variant of the p≡5(mod8)p \equiv 5 \pmod 8 formula.
  • sympy.sqrt_mod(a, p, all_roots=True) implements Tonelli-Shanks and the composite case.

Exercises

Exercise 1: Easy case

Find a square root of 2 modulo 7 using a(p+1)/4a^{(p+1)/4}.

Answer

4 (and −4≡3-4 \equiv 3).

Solution

(7+1)/4=2(7 + 1)/4 = 2, so x=22=4x = 2^2 = 4. Check: 16=14+216 = 14 + 2. The other root is 7−4=37 - 4 = 3, and 9≡29 \equiv 2 too.

Exercise 2: Four roots

How many square roots does 4 have modulo 77? List them.

Answer

Four: 2, 9, 68, 75.

Solution

Modulo 7 the roots are ±2\pm 2, modulo 11 they are ±2\pm 2. Combining gives 22, −2=75-2 = 75, and the mixed ones x≡2(mod7)x \equiv 2 \pmod 7, x≡−2(mod11)x \equiv -2 \pmod{11}, which is 99, and its negative 6868. Check: 81=77+481 = 77 + 4.

Exercise 3: Factor with a root (code)

Someone tells you that 1002100^2 and 142521425^2 leave the same remainder modulo n=3233n = 3233. Use this to factor nn.

Answer

3233=53⋅613233 = 53 \cdot 61, from gcd⁡(1425−100,3233)=53\gcd(1425 - 100, 3233) = 53.

Solution

1425≢±1001425 \not\equiv \pm 100, so n∣(1425−100)(1425+100)n \mid (1425 - 100)(1425 + 100) without dividing either factor, and each gcd picks out one prime.

python · try it yourself
from math import gcd
n = 3233
print(100 * 100 % n, 1425 * 1425 % n, gcd(1425 - 100, n), gcd(1425 + 100, n))
301 301 53 61

Test yourself

For p≡3(mod4)p \equiv 3 \pmod 4 and a QR aa, a square root of aa is…

  1. a(p−1)/2a^{(p-1)/2}
  2. a(p+1)/4a^{(p+1)/4}
  3. ap−2a^{p-2}
  4. a/2a/2

How many square roots does a quadratic residue have modulo n=pqn = pq (distinct odd primes)?

  1. 1
  2. 2
  3. 4
  4. nn

Computing square roots modulo n=pqn = pq without the factors is…

  1. easy
  2. equivalent to factoring nn
  3. impossible even with the factors
  4. the same as computing gcds