Mathematical foundations, attack vectors, and practical implementation. The Chinese Remainder Theorem is a powerful mathematical tool that finds direct application in the cryptanalysis of ECDSA. Combined with attacks that exploit weaknesses in nonce generation (reuse, partial leakage, twist attacks), the CRT allows for the merging of disparate fragments of private key information into a coherent whole.
Content
- Introduction: ECDSA fragility
- Mathematical foundations of ECDSA
- Chinese Remainder Theorem: Formulation and Algorithm
- Nonce Reuse Attack
- Partial nonce leakage attacks and the hidden number problem (HNP)
- Twist Attack: Obtaining Private Key Remains Using Small Moduli
- Practical implementation: Python/SageMath code
- Protective measures
- Conclusion
1. Introduction: ECDSA fragility
ECDSA (Elliptic Curve Digital Signature Algorithm) is the cornerstone of Bitcoin transaction security. However, unlike many other cryptographic primitives, ECDSA’s security depends not only on the elliptic curve secp256k1 discrete logarithm problem (ECDLP) resistance but also on a critical assumption about the quality of the nonce generation .
ECDSA is known as a “fragile” signature scheme [reference:0]. If the nonce k is not cryptographically random, unique, and unpredictable for each signature, there is a whole class of attacks that can recover the long-term private key d in polynomial time, completely bypassing the complexity of ECDLP [reference:1].
In this paper, we detail how the Chinese Remainder Theorem (CRT) is used to combine partial private key leaks obtained from multiple vulnerable ECDSA signatures into a single recovered secret.
The key idea is that CRT allows one to recover a number d from its remainders d mod m₁, d mod m₂, …, d mod mₙif the moduli mᵢ are pairwise relatively prime and their product exceeds the bound of the target number. In the context of ECDSA, the remainders of a private key are extracted through analysis of vulnerable nonces.
2. Mathematical foundations of ECDSA
ECDSA operates on a group of points on an elliptic curve E over a finite field 𝔽ₚ, where p is a prime number. Bitcoin uses a curve secp256k1 with the following parameters:
The generator G produces a cyclic subgroup of prime order n, where n is also a 256-bit prime number. The signer’s private key is the integer d ∈ [1, n−1], and the corresponding public key is the dot Q = dG[reference:2].
2.1. Signature generation process
To sign a message with a hash, h the signer performs the following steps:
1
Generating a nonce
A secret random number k ∈ [1, n−1], called a nonce or ephemeral key , is chosen .
2
Calculating the R-point
The point is calculated R = kG. Let be r = Rₓ mod n the x-coordinate of this point, taken modulo n.
3
Calculating the s component
Calculates s = k⁻¹(h + r·d) mod n, where k⁻¹ is the inverse element of k modulo n.
The resulting signature is a pair (r, s). Signature verification is performed by checking for equality R' = (s⁻¹·h)G + (s⁻¹·r)Q and comparing the x-coordinate R' with r.
2.2. Vulnerability: Linear dependence on nonce
The key equation of ECDSA is:
Can be rewritten as a linear comparison with respect to the unknowns d and k:
It is this linearity that makes ECDSA vulnerable: if an attacker obtains any information about the nonce k (full, partial, or statistical), he can construct a system of equations for d.
3. Chinese Remainder Theorem: Formulation and Algorithm
3.1 Classical formulation
Let pairwise coprime modules be given m₁, m₂, …, mₙ (that is, gcd(mᵢ, mⱼ) = 1 for all i ≠ j). Then for any system of congruences:
there is a unique solution modulo M = m₁ · m₂ · … · mₙ.
3.2 Constructive proof (Gauss’s algorithm)
The solution can be constructed explicitly:
Where:
M = ∏ mᵢ— general module;Mᵢ = M / mᵢ— the product of all modules exceptmᵢ;yᵢ = Mᵢ⁻¹ mod mᵢ— the inverse element ofMᵢmodulomᵢ, calculated using the extended Euclidean algorithm.
3.3 Application to ECDSA
In the context of ECDSA, a private key d is a 256-bit number. If an attacker obtains the remainders d mod m₁, d mod m₂, …, d mod mₖ for a sufficiently large set of small coprime moduli such that:
This d can be recovered unambiguously using a CRT. This is the idea behind the Twist Attack on secp256k1[reference:3][reference:4].
Important: The modules mᵢ do not have to be prime—their pairwise coprimeness is sufficient. In practice, Twist Attack uses orders of points on quadratic twist curves secp256k1that are products of small prime numbers.
4. Nonce Reuse Attack
4.1. Attack Scenario
If the same nonce k is used to sign two different messages with hashes h₁ and h₂, two signatures are obtained (r, s₁) with (r, s₂) the same component r (since r depends only on kG).
We have a system:
Subtracting the equations, we get:
After recovery, k the private key is calculated directly:
4.2. The scale of the Bitcoin problem
Research on the Bitcoin blockchain has shown that the nonce reuse problem is not theoretical. Breitner and Heninger (2019) analyzed over 647 million ECDSA signatures and found 1,068 unique values r that occurred at least twice, affecting 4,433 keys [reference:5]. In total, the researchers were able to calculate approximately 300 Bitcoin private keys [reference:6].
Historical incidents: Nonce reuse led to the compromise of the Sony PlayStation 3 private key (2010), as well as mass thefts of funds from Android Bitcoin wallets due to bugs in SecureRandom[reference:7].
5. Partial nonce leakage attacks and the hidden number problem (HNP)
5.1 Hidden Number Problem (HNP)
In a more general case, an attacker may not have k complete knowledge of the nonce, but may have information about some bits. The recovery problem d from such partial data reduces to the Hidden Number Problem (HNP), first formulated by Boneh and Venkatesan in 1996.
Formally: let t₁, t₂, …, tₘ ∈ ℤₙ the approximations be given and known aᵢ such that:
Then d it can be recovered using lattice reduction (LLL algorithm)[reference:8].
5.2. Communication with ECDSA
Let’s rewrite the ECDSA equation:
If the attacker knows the high-order or low-order bits of kᵢ, this yields linear relations on d, which can be combined into a lattice problem. Lattice reduction (LLL/BKZ) allows one to solve HNP and recover the private key [reference:9].
5.3 Why is CRT here?
Although HNP is solved using lattice theory methods, CRT plays an important role in additional attacks , especially when the nonce information has a specific structure. For example, if nonces are generated by a weak PRNG with a short period, CRT allows one to reconstruct the generator’s state, and then [the nonce] d…
6. Twist Attack: Obtaining the Remaining Private Key Using Small Moduli
6.1. The essence of the attack
The Twist Attack (quadratic twist attack) exploits the implementation features of operations on elliptic curve points secp256k1, when the check for membership of a point on the curve is either absent or performed incorrectly[reference:10].
The idea is to force the victim to perform a scalar multiplication with a point Pthat does not belong to the main curve secp256k1, but lies on one of its quadratic twists – curves of the form y² = x³ + b' with a different value b'[reference:11].
6.2. Twist orders
The curve secp256k1 has a cofactor h = 1, but its twists have composite orders that factor into small primes. For example, for one of the twists, the group order is:
By factoring the twist order into prime factors, an attacker can solve the discrete logarithm problem (DLP) in each small subgroup separately (Pollard rho method, Pohlig-Hellman algorithm) and obtain a value d mod ℓᵢ for each prime factor ℓᵢ[reference:12].
6.3. Key recovery via CRT
After obtaining remainders d mod ℓ₁, d mod ℓ₂, …, d mod ℓₖ for a sufficiently large set of primes ℓᵢ (such that ∏ ℓᵢ > n), the attacker uses the Chinese Remainder Theorem to recover the full 256-bit private key[reference:13].
Timeframe: According to published research, a full Bitcoin wallet recovery using this technique can take between 5 and 15 minutes on standard hardware[reference:14].
6.4 An example of twist order factorization
Below is a fragment of the order decomposition of one of the twists secp256k1used in practical attacks:
cofactor = 3 * 13^2 * 3319 * 22639 * 1013176677300131846900870239606035638738100997248092069256697437031
# Дополнительные простые множители из разных твистов:
E1: 20412485227
E2: 3319, 22639
E3: 109903, 12977017, 383229727
E4: 18979
E6: 10903, 5290657, 10833080827, 22921299619447
The product of these factors exceeds n ≈ 2²⁵⁶, which makes unambiguous recovery possible d using CRT[reference:15].
7. Practical implementation: Python/SageMath code
7.1. Implementing a CRT from Scratch
Below is a classic CRT implementation using the extended Euclidean algorithm:
def extended_gcd(a, b):
"""Расширенный алгоритм Евклида: возвращает (g, x, y), где a*x + b*y = g = gcd(a, b)."""
if a == 0:
return b, 0, 1
g, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return g, x, y
def mod_inverse(a, m):
"""Обратный элемент к a по модулю m."""
g, x, _ = extended_gcd(a, m)
if g != 1:
raise ValueError(f"Обратный элемент не существует: gcd({a}, {m}) = {g}")
return x % m
def crt(remainders, moduli):
"""
Китайская теорема об остатках.
Аргументы:
remainders: список остатков [a_1, a_2, ..., a_n]
moduli: список модулей [m_1, m_2, ..., m_n]
Возвращает:
x mod M, где M = ∏ m_i
"""
if len(remainders) != len(moduli):
raise ValueError("Количество остатков и модулей должно совпадать")
M = 1
for m in moduli:
M *= m
x = 0
for a_i, m_i in zip(remainders, moduli):
M_i = M // m_i
y_i = mod_inverse(M_i, m_i)
x += a_i * M_i * y_i
return x % M
7.2 Example: Key recovery from Twist Attack remnants
Suppose the attacker obtained the following private key residues d in moduli that are prime divisors of twist orders:
# Пример остатков d mod m_i (гипотетические данные)
remainders = [
0x1a2b3c, # d mod 3319
0x4d5e6f, # d mod 22639
0x789abc, # d mod 18979
0xdef012, # d mod 10903
0x345678, # d mod 5290657
]
moduli = [3319, 22639, 18979, 10903, 5290657]
# Восстановление d
d_recovered = crt(remainders, moduli)
print(f"Восстановленный приватный ключ (частичный): {hex(d_recovered)}")
print(f"Модуль: {hex(prod(moduli))}")
7.3 Complete Attack Pipeline (Proof of Concept)
Below is a proof-of-concept script demonstrating a complete key recovery cycle using Twist Attack and CRT:
from sage.all import *
def twist_attack_recover_private_key(victim_public_key, curve_params):
"""
Концептуальная реализация Twist Attack на secp256k1.
Шаги:
1. Для каждого квадратичного твиста кривой secp256k1:
a. Построить точку P на твисте.
b. Решить ECDLP в малых подгруппах (Pollard rho / Pohlig-Hellman).
c. Получить d mod ℓ для каждого простого делителя ℓ порядка твиста.
2. Собрать все остатки и применить CRT для восстановления d.
"""
# Параметры secp256k1
p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
# Твисты и их порядки (упрощённо)
twists = {
'E1': {'b': 1, 'order': 20412485227},
'E2': {'b': 2, 'order': 3319 * 22639},
'E3': {'b': 3, 'order': 109903 * 12977017 * 383229727},
'E4': {'b': 4, 'order': 18979},
'E6': {'b': 6, 'order': 10903 * 5290657 * 10833080827 * 22921299619447},
}
remainders = []
moduli = []
for twist_name, twist_data in twists.items():
# Шаг 1: Построение точки на твисте
# (в реальной атаке точка выбирается так, чтобы её порядок делил порядок твиста)
# ...
# Шаг 2: Решение ECDLP в подгруппах малого порядка
# Используется Sagemath: discrete_log_rho или встроенный discrete_log
# partial_d = discrete_log(P, Q, ord=small_prime)
# Шаг 3: Добавление остатка и модуля
# remainders.append(partial_d)
# moduli.append(small_prime)
pass
# Шаг 4: Восстановление d через CRT
d = crt(remainders, moduli)
# Проверка: d * G == victim_public_key
# assert(d * G == victim_public_key)
return d
Note: The full Twist Attack code requires detailed work with elliptic curve arithmetic, constructing isomorphisms between twists and the underlying curve, and using efficient algorithms for solving ECDLP in small subgroups (Pollard rho, Pohlig-Hellman). The code provided is a conceptual illustration.
8. Protective measures
Understanding CRT-based attacks and partial nonce leakage allows us to formulate a set of practical security measures for developers of cryptographic libraries and wallets:
8.1 Deterministic Nonce Generation (RFC 6979)
RFC 6979 defines deterministic nonce generation based on a message hash and a private key using HMAC-SHA256. This completely eliminates the possibility of reuse k and eliminates dependence on RNG quality [reference:16].
8.2. Validation of points on the curve
Always verify that input points belong to the expected elliptic curve. This prevents twist attacks and invalid curve attacks [reference:17].
8.3 Using cryptographically strong RNGs
If random nonce generation is used, a CSPRNG (Cryptographically Secure Pseudorandom Number Generator) such as the /dev/urandom one getrandom() in Linux or hardware entropy sources must be used.
8.4. Verifying signatures before sending
Some RSA-CRT and ECDSA implementations must verify the correctness of the generated signature before sending it. This allows for early detection of nonce generation errors [reference:18].
8.5 Monitoring the blockchain for nonce reuse
Wallets can scan the blockchain for duplicate values r in signatures associated with their addresses. If such an event is detected, funds should be immediately moved to a new address with a new private key.
9. Conclusion
The Chinese Remainder Theorem is a powerful mathematical tool that finds direct application in ECDSA cryptanalysis. Combined with attacks that exploit weaknesses in nonce generation (such as reuse, partial leakage, and twist attacks), the CRT allows for the unification of disparate fragments of private key information into a coherent whole.
Key findings:
- ECDSA is extremely sensitive to the quality of the nonce. Even a partial leak of information
kcan lead to a complete compromise of the key. - The CRT is the “glue” that holds the residues together. If an attacker obtains
d mod mᵢrelatively prime modules for a sufficiently large set, recoverydbecomes trivial. - The Twist Attack demonstrates practical feasibility. Quadratic twist attacks
secp256k1allow one to obtain key residues using small moduli, which can then be assembled using a CRT in minutes. - Protection exists. Deterministic nonce generation (RFC 6979), endpoint validation, and the use of a CSPRNG completely neutralize the attack vectors discussed.
Understanding these mathematical mechanisms is critical for both cryptographic library developers and blockchain security specialists.
The document is based on an analysis of open academic sources and practical research in the field of ECDSA cryptanalysis.
The material is intended for educational and research purposes only.
