libressl-BN_mod_sqrt(3)

libressl-BN_mod_sqrt3

Square root in a prime field

Usage

Crypto Library (libcrypto, -lcrypto)

#include <openssl/bn.h>

BIGNUM *

BN_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);

Overview

BN_mod_sqrt() solves

r sup 2 == a ( roman mod p )

for r in the prime field of characteristic p using the Tonelli-Shanks algorithm if needed and places one of the two solutions into r. The other solution is p - r.

The argument p is expected to be a prime number.

Return values

In case of success, BN_mod_sqrt() returns r, or a newly allocated BIGNUM object if the r argument is NULL.

In case of failure, NULL is returned. This for example happens if a is not a quadratic residue or if memory allocation fails.

Caveats

If p is not prime, BN_mod_sqrt() may succeed or fail. If it succeeds, the square of the returned value is congruent to a modulo p. If it fails, the reason reported by ERR_get_error(3) is often misleading. In particular, even if a is a perfect square, BN_mod_sqrt() often reports “not a square” instead of “p is not prime”.

History

BN_mod_sqrt() first appeared in OpenSSL 0.9.7 and has been available since OpenBSD 3.2.

From libressl 4.4.0-1 in Arch Linux 2026-11-01. Parsed by carta from the page's mdoc source.