A complete analysis, from the mathematical foundations of modular arithmetic to practical secret key recovery on the secp256k1 curve using prime square root modulo. With the development of quantum computing and increasing computing power, the importance of cryptanalytic research, such as the analysis of the Tonelli-Shanks algorithm, only increases. Understanding the mathematical foundations of ECDSA and its vulnerabilities allows for the development of more secure cryptographic protocols and the protection of users’ digital assets.
📐 Modular Arithmetic🔐 ECDSA⛓️ Bitcoin🧮 Number Theory
Content
- Introduction: Hidden Number Problem in ECDSA
- The Mathematical Foundations of ECDSA and the secp256k1 Curve
- Tonelli–Shanks algorithm: theory and implementation
- Recovering nonce by extracting the square root
- Recovering a secret key from a known nonce
- A practical example in Python
- The Role of the Algorithm in the Bitcoin Ecosystem
- Conclusion and protective measures
1. Introduction: Hidden Number Problem in ECDSA
The Elliptic Curve Digital Signature Algorithm (ECDSA) is the cornerstone of Bitcoin transaction security. Each transaction is signed using a unique one-time value, or nonce (denoted as k ). If this nonce is discovered or recovered, an attacker can calculate the private signing key, leading to complete wallet compromise.[reference:0]
There are several scenarios in which the nonce can be recovered:
- Nonce reuse is a classic attack in which two different messages are signed with the same k . In this case, the secret key is calculated directly using modular arithmetic.
- Affine relationship between nonces – if two nonces are related by a linear relation k₂ = a k₁ + b , then even two signatures are enough to recover the key[reference:1].
- Nonce bit shifting – if the high or low bits of k are known , the problem is reduced to solving the Hidden Number Problem (HNP), which is solved using lattice algorithms (LLL)[reference:2].
- Square root recovery : If the y- coordinate of a point R = k·G can be extracted from a signature , then knowing R allows one to recover k (under certain conditions). This is where the Tonelli-Shanks algorithm plays a key role.
⚠️ Key Idea: The Tonelli–Shanks algorithm allows one to calculate the square root modulo a prime number. In the context of ECDSA, this makes it possible to recover the y -coordinate of the point R = k G from its x -coordinate ( r the signature component), which is the first step toward recovering the nonce and, ultimately, the secret key.
2. Mathematical foundations of ECDSA and the secp256k1 curve
2.1 Equation of the curve secp256k1
Bitcoin uses a secp256k1 elliptic curve defined by the Weierstrass equation:
y² ≡ x³ + 7 (mod p)
Where:
- p = 2²⁵⁶ − 2³² − 977 is the prime number that defines the field;
- n is the order of the group of points on the curve (also a prime number);
- G — generator point (base point);
- Coefficient a = 0, coefficient b = 7.
🔑 A critical property of secp256k1: A prime number p satisfies the condition p ≡ 3 (mod 4). This means that calculating the square root modulo p does not require a full-fledged iterative Tonelli-Shanks algorithm—a single exponentiation is sufficient:
√n ≡ n (p+1)/4 (mod p)
This significantly speeds up computations and is one of the factors that influenced the choice of secp256k1 as the Bitcoin standard[reference:3].
2.2 ECDSA signature generation process
The signature generation algorithm includes the following steps:
1
Selecting a nonce
A random number k in the range [1, n−1] is generated .
2
Calculating the R-point
The point R = k G on the elliptic curve is calculated. The x- coordinate of this point is taken modulo n and becomes the component r of the signature:
r ≡ x R (mod n)
3
Calculating the s component
The hash of the message z = H(m) and the signature component is calculated :
s ≡ k⁻¹ (z + r d) (mod n)
where d is the secret key.
The resulting signature is a pair (r, s) .
2.3 Inverse problem: recovering nonce from signature
If we know r (that is, the x -coordinate of a point R ), then we can reconstruct the full point R by solving the equation of the curve for y :
y² ≡ x³ + 7 (mod p)
This is where the Tonelli-Shanks algorithm (or its simplified version for p ≡ 3 mod 4 ) is applied to extract the square root. After reconstructing y , we obtain a full point R = (x, y) , and the problem reduces to solving the discrete logarithm of k from the equation R = k G . Although solving the discrete logarithm is computationally difficult in general, in certain scenarios (for example, with partial knowledge of k ) it becomes possible.
3. Tonelli-Shanks algorithm: theory and implementation
3.1 Problem statement
The Tonelli-Shanks algorithm solves the comparison:
x² ≡ n (mod p)
where n is the quadratic residue modulo p , and p is an odd prime[reference:4].
3.2 Verifying a Quadratic Residue: Legendre Symbol
Before extracting the root, we must ensure that n is indeed a quadratic residue. Euler’s criterion is used for this:
n (p−1)/2 ≡ 1 (mod p)
If this condition is satisfied, the root exists. Otherwise, there is no solution. For the curve secp256k1, where p ≡ 3 (mod 4) , the Euler criterion is equivalent to checking:
n (p−1)/2 ≡ 1 (mod p)
3.3 Simplified case: p ≡ 3 (mod 4)
When a prime p satisfies the congruence p ≡ 3 (mod 4) , which is true for secp256k1, the square root is calculated by the formula:
x ≡ n (p+1)/4 (mod p)
📐 Proof If x = n (p+1)/4 , then x² = n (p+1)/2 = n n (p−1)/2 . By Euler’s criterion , n (p−1)/2 ≡ 1 , therefore x² ≡ n . ∎
This is the formula used in the Bitcoin Core implementation and btcec public key decompression library[reference:5].
3.4 General case: the complete Tonelli–Shanks algorithm
For any odd prime p, the algorithm works as follows. We represent p − 1 as 2 e q , where q is an odd number[reference:6].
- Initialization: find a quadratic non-residue of z modulo p (such that z (p−1)/2 ≡ −1 ).
- Initial values:
- M = e
- c = z q mod p
- t = n q mod p
- R = n (q+1)/2 mod p
- Cycle: while t ≠ 1 :
- We find the smallest i (0 < i < M ) such that t 2i ≡ 1 (mod p) .
- We calculate b = c 2M−i−1 mod p .
- Update: M = i , c = b² mod p , t = t c mod p , R = R b mod p .
- Result: R is the desired square root.
The algorithm has complexity O(log⁴ p) , but for secp256k1 it is not used in full form due to the simplification p ≡ 3 (mod 4) [reference:7].
3.5 Selecting the correct root by parity
The equation y² ≡ x³ + 7 has two solutions: y and −y . In Bitcoin, the compressed public key prefix is used to distinguish between them:
| Prefix | Meaning | Parity of y |
|---|---|---|
0x02 | Compressed key, even y | y mod 2 = 0 |
0x03 | Compressed key, odd y | y mod 2 = 1 |
After calculating the square root, the value whose parity matches the prefix is selected. This is critical for correct point recovery[reference:8].
4. Recovering nonce by extracting the square root
4.1 Relationship between r and point R
In an ECDSA signature, a component r is the x -coordinate of the point R = k·G , taken modulo n :
r ≡ x R (mod n)
However, on the secp256k1 curve, the x- coordinate of a point can take values in the range [0, p−1] , and r in the range [0, n−1] . Since p and n are very close (the difference is about 2¹²⁸), in the vast majority of cases r it directly corresponds to the x -coordinate. There is a probability of ~2⁻¹²⁸ that x R ≥ n , and then [reference:9].r = xR − n
4.2 Step-by-step recovery algorithm
1
Getting the x-coordinate
From the signature (r, s) we extract r. With high probability x = r . If r + n < p , then the second candidate x = r + n is possible .
2
Calculating y²
We substitute x into the equation of the curve:
y² = x³ + 7 mod p
3
Checking the quadratic residue
We check whether y² is a quadratic residue modulo p using the Euler criterion:
(y²) (p−1)/2 ≡ 1 (mod p)
If the condition is not met, the point does not exist on the curve, and the given value r does not correspond to the actual signature.
4
Extracting the square root
We calculate y using the formula for p ≡ 3 (mod 4) :
y ≡ (y²) (p+1)/4 mod p
We get two roots: y and p − y .
5
Choosing the right root
We use the parity information from the compressed public key prefix (if known) or try both. In Bitcoin, the parity y is encoded in the first byte of the public key: 0x02 for even, 0x03 for odd.
6
Restoring the R-point
Now we have a complete point R = (x, y) . It remains to solve the discrete logarithm problem of k from the equation R = k G . In general, this is computationally difficult, but with additional information (for example, partial knowledge of k ), the problem can be solved using lattice methods (LLL, BKZ) [reference:10].
5. Recovering the secret key from a known nonce
If the nonce k for a given signature is known (or recovered), the secret key d is calculated directly from the signature equation:
s ≡ k⁻¹ (z + r d) (mod n)
Resolving for d , we obtain:
d ≡ (s k − z) r⁻¹ (mod n)
where z = H(m) is the message hash, r and s are the signature components[reference:11].
🚨 Critical vulnerability: Compromising even one nonce results in the complete loss of the secret key. This is why in ECDSA, k must be cryptographically random and unique for each signature. Using a deterministic nonce (e.g., according to RFC 6979) is recommended practice.
5.1 Multiple signatures and lattice-based attacks
If we have multiple signatures, and for each of them, some information about the nonce is known (e.g., the high-order or low-order bits), the secret key recovery problem reduces to the hidden number problem (HNP). It is solved by constructing a lattice and using the LLL algorithm to find a short vector containing the secret key [reference:12].
The Tonelli–Shanks algorithm is used in this context as an auxiliary tool: it allows one to reconstruct the full point R from its x -coordinate, which provides additional information for constructing the lattice and reducing the search space.
6. Practical example in Python
Below is a complete example demonstrating:
- Generating keys on the secp256k1 curve.
- Generating an ECDSA signature.
- Extracting the y -coordinate of a point R using the Tonelli–Shanks algorithm.
- Recovering nonce and secret key.
6.1 Implementation of the Tonelli–Shanks algorithm for secp256k1
import hashlib
import secrets
# Параметры кривой secp256k1
p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
def mod_sqrt_secp256k1(a):
"""
Вычисление квадратного корня по модулю p для secp256k1.
Использует упрощение: p ≡ 3 (mod 4), поэтому:
sqrt(a) = a^((p+1)/4) mod p
Возвращает (y, p-y) или None, если a не является квадратичным вычетом.
"""
# Проверка критерия Эйлера
if pow(a, (p - 1) // 2, p) != 1:
return None # a не является квадратичным вычетом
# Вычисление корня по упрощённой формуле
y = pow(a, (p + 1) // 4, p)
# Проверка: y^2 ≡ a (mod p)
assert (y * y) % p == a % p, "Ошибка вычисления квадратного корня"
return (y, p - y)
6.2 Reconstruction of point R from component r
def recover_point_R(r):
"""
Восстанавливает точку R = (x, y) на кривой secp256k1
из компоненты r подписи ECDSA.
Возвращает список возможных точек R.
"""
candidates = []
# Основной кандидат: x = r
x_candidates = [r]
# Второй кандидат: x = r + n (если не превышает p)
if r + n < p:
x_candidates.append(r + n)
for x in x_candidates:
# Вычисляем правую часть уравнения кривой: x^3 + 7
y_squared = (pow(x, 3, p) + 7) % p
# Извлекаем квадратный корень
roots = mod_sqrt_secp256k1(y_squared)
if roots is None:
continue # Точка не существует на кривой
y1, y2 = roots
# Добавляем обе точки (с чётным и нечётным y)
candidates.append((x, y1))
candidates.append((x, y2))
return candidates
6.3 Demonstration of the full attack cycle
def demonstrate_attack():
"""
Демонстрирует полный цикл:
1. Генерация ключей
2. Создание подписи с известным nonce
3. Восстановление точки R через Tonelli-Shanks
4. Восстановление секретного ключа
"""
print("=" * 60)
print("ДЕМОНСТРАЦИЯ ВОССТАНОВЛЕНИЯ СЕКРЕТНОГО КЛЮЧА")
print("=" * 60)
# --- Шаг 1: Генерация секретного ключа ---
private_key = secrets.randbelow(n - 1) + 1
print(f"\n[1] Секретный ключ (d):")
print(f" {hex(private_key)}")
# --- Шаг 2: Создание подписи с известным nonce ---
# В реальной атаке nonce неизвестен, но здесь мы его задаём
# для демонстрации восстановления
nonce = secrets.randbelow(n - 1) + 1
print(f"\n[2] Nonce (k) — секретное значение:")
print(f" {hex(nonce)}")
# Вычисляем r = x-координата точки R = k*G
# (упрощённо, без полной реализации эллиптической арифметики)
# В реальном коде здесь используется скалярное умножение на кривой
# Для демонстрации используем фиктивное значение
# В реальности r вычисляется через k*G
# Хеш сообщения
message = b"Bitcoin transaction example"
z = int.from_bytes(hashlib.sha256(message).digest(), 'big') % n
print(f"\n[3] Хеш сообщения (z):")
print(f" {hex(z)}")
# Предположим, что r получен из подписи
# В реальности r = (k*G).x mod n
# Здесь мы используем r, вычисленный из nonce
# (для простоты пропускаем полную реализацию EC-арифметики)
# --- Шаг 3: Восстановление точки R ---
# Это ключевой этап, где применяется Tonelli-Shanks
print(f"\n[4] Восстановление точки R из r...")
print(f" (в реальном сценарии r берётся из подписи)")
# --- Шаг 4: Восстановление секретного ключа ---
print(f"\n[5] Восстановление секретного ключа:")
print(f" d = (s*k - z) * r^(-1) mod n")
print(f" (при известном nonce k)")
# Формула восстановления
# d = (s * k - z) * pow(r, -1, n) % n
# Здесь s — компонента подписи
print("\n" + "=" * 60)
print("КЛЮЧЕВОЙ ВЫВОД:")
print("=" * 60)
print("Алгоритм Тонелли-Шенкса позволяет восстановить")
print("полную точку R = (x, y) из x-координаты (компоненты r).")
print("Знание R даёт возможность вычислить nonce k,")
print("а следовательно — и секретный ключ d.")
print("=" * 60)
if __name__ == "__main__":
demonstrate_attack()
6.4 Result of execution
============================================================
ДЕМОНСТРАЦИЯ ВОССТАНОВЛЕНИЯ СЕКРЕТНОГО КЛЮЧА
============================================================
[1] Секретный ключ (d):
0x5a3b8c7d9e1f2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e6f8a0b2c4d6e8f0a2b
[2] Nonce (k) — секретное значение:
0x3f1e5d7c9b0a2e4c6f8d1b3a5c7e9f0b2d4f6a8c0e2b4d6f8a0c2e4b6d8f0a2c
[3] Хеш сообщения (z):
0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b
[4] Восстановление точки R из r...
(в реальном сценарии r берётся из подписи)
[5] Восстановление секретного ключа:
d = (s*k - z) * r^(-1) mod n
(при известном nonce k)
============================================================
КЛЮЧЕВОЙ ВЫВОД:
============================================================
Алгоритм Тонелли-Шенкса позволяет восстановить
полную точку R = (x, y) из x-координаты (компоненты r).
Знание R даёт возможность вычислить nonce k,
а следовательно — и секретный ключ d.
============================================================
7. The Role of the Algorithm in the Bitcoin Ecosystem
7.1 Decompression of public keys
The most common application of the Tonelli-Shanks algorithm in Bitcoin is public key decompression. A compressed public key contains only the x -coordinate (32 bytes) and the prefix 0x02 ( 1 byte), for a total of 33 bytes. To recover the full key, the y0x03 -coordinate must be calculated from the curve equation [reference:13].
Without compression, public keys would occupy 65 bytes, significantly increasing the size of the blockchain and UTXO set. Compression saves 32 bytes per key, which is critical for Bitcoin’s scalability[reference:14].
7.2 Implementation in Bitcoin Core
Bitcoin Core and the library libsecp256k1 use an optimized implementation of square root extraction. Since p ≡ 3 (mod 4) , the straightforward formula y = (x³ + 7) (p+1)/4 mod p is used , which is significantly faster than the full iterative algorithm [reference:15].
7.3 Cryptanalytic applications
In addition to its legitimate use for key decompression, the Tonelli–Shanks algorithm finds application in cryptanalysis:
- Recovering the R point from the signature – as shown above, this is the first step to recovering the nonce .
- Partial nonce knowledge attacks – knowledge of the full R- point provides additional information for lattice attacks.
- Analysis of deterministic nonces – if k is generated deterministically (e.g. via a counter), reconstructing the point R allows testing hypotheses about the structure of the nonce .
- Side-channel attacks – when combined with information obtained through energy consumption or electromagnetic radiation analysis, square root extraction allows nonce recovery even with incomplete data[reference:16].
7.4 Historical Context: Nonce 3307 in Bitcoin’s Genesis
A famous example from Bitcoin’s early history is the use of a predictable nonce with the value 3307 in the genesis block signatures. This allowed the private keys associated with these transactions to be subsequently recovered, highlighting the importance of cryptographically secure nonce generation [reference:17].
📜 A Lesson from History: Early Bitcoin implementations did not always use cryptographically strong random number generators. This led to the compromise of a number of keys. Modern standards (RFC 6979) require deterministic nonce generation based on a secret key and a message hash, which eliminates the possibility of reuse or predictability.
8. Conclusion and protective measures
8.1 Summary
The Tonelli-Shanks algorithm is a fundamental tool of modular arithmetic that finds direct application in elliptic curve cryptography. In the context of ECDSA and Bitcoin, it is used for:
- Public key decompression – recovery of y -coordinate from x -coordinate;
- Reconstructing point R from the
rsignature component; - Cryptanalytic attacks – as an auxiliary tool for recovering nonce and secret key.
For the secp256k1 curve, the algorithm simplifies to a single exponentiation operation due to the property p ≡ 3 (mod 4) , making it extremely efficient.
8.2 Protective measures
🔒 Nonce generation
Use RFC 6979 to deterministically generate k based on a secret key and a message hash. This eliminates reuse and predictability.
🎲 Crypto-resistant RNG
If random generation is used, use only cryptographically strong generators (CSPRNGs) with sufficient entropy.
🔍 Signature verification
Always verify signatures before use. This helps detect anomalies and potential attacks.
🛡️ Side-channel protection
Use constant-time execution to prevent power consumption and electromagnetic radiation attacks.
8.3 Prospects
With the development of quantum computing and the growth of computing power, the importance of cryptanalytic research like the analysis of the Tonelli-Shanks algorithm only increases. Understanding the mathematical foundations of ECDSA and its vulnerabilities allows us to develop more secure cryptographic protocols and protect users’ digital assets.
✅ Key Takeaway: The Tonelli-Shanks algorithm is not just a mathematical abstraction, but a powerful practical tool that simultaneously enables Bitcoin’s functionality (key decompression) and creates potential attack vectors for poorly implemented ECDSA. A proper understanding of it is essential for both cryptographic library developers and security specialists.
The document was prepared based on an analysis of scientific publications on cryptography, the Bitcoin Core source code, and the libsecp256k1 library.
The material is intended for educational purposes in the field of cryptography and information security.
