BN_MOD_SQRT(3)
π NAME π
Okay so bestie, welcome to BN_MOD_SQRT(3) from the Library Functions Manual β the page for BN_mod_sqrt β and it's literally square root in a prime field. That's the whole vibe: find the modular square root, slay, go home. π
β¨
β¨ SYNOPSIS β¨
You're linking against libcrypto and pulling in <openssl/bn.h>, so the setup looks like this:
library βlibcryptoβ #include <openssl/bn.h>
BIGNUM *
BN_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
π DESCRIPTION π
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. So yeah, two roots, and one of them gets the main-character slot. π
The argument p is expected to be a prime number. Expected, bestie β we'll get to the caveat. π
π RETURN VALUES π
- On success?
BN_mod_sqrt()returnsr, or a newly allocatedBIGNUMobject if therargument isNULL. Slay. π«Ά - On failure?
NULLis returned. This for example happens ifais not a quadratic residue or if memory allocation fails. Not slay. π
π¦ SEE ALSO π¦
Also the reference to end all references: Henri Cohen, A Course in Computational Algebraic Number Theory, Springer, Berlin, 1993, Algorithm 1.5.1. Ngl, that's iconic behavior. π
πΈ HISTORY πΈ
BN_mod_sqrt() first appeared in OpenSSL 0.9.7 and has been available since OpenBSD 3.2. History lesson complete, periodt. β
π CAVEATS π
π¨ Bestie, listen: ifpis not prime,BN_mod_sqrt()may succeed or fail. That's the whole warning.
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β. So the error message is lowkey not giving what it needs to give. π
π Cute source/version sign-off: this page comes from Debian, dated June 8, 2025, and it's BN_MOD_SQRT(3). Bye bestie! π
π¦ where this page comes from
- alpine 3.24: libressl-doc 4.3.1-r0 Β· custom
- arch rolling: libressl 4.4.0-1 Β· ISC AND custom:OpenSSL
- Copyright (c) 2022 Ingo Schwarze <schwarze@openbsd.org>
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms