Using dynamic programming with a small parameter, a limited sum, and a low treewidth to recover the hidden nonce and private key. Dynamic programming is not a universal replacement for lattice methods, but a specialized tool for cryptanalysis of ECDSA under combinatorial nonce leaks:
- small parameter – DP by Hamming weight bits;
- limited amount – knapsack-DP modulo;
- low treewidth — tree-decomposition of DP by the equation graph;
- MITM – “DP in half” of the search space.
By combining these approaches with LLL/BKZ, one can solve problems inaccessible to either pure lattices or brute force. It is at the intersection of these methods that the cutting edge of modern ECDSA cryptanalysis lies.
Content
- Introduction: ECDSA and the Hidden Number Problem
- Formalizing HNP for Bitcoin Signatures
- DP with small parameter: nonce of low Hamming weight
- Limited-amount DP: The knapsack approach
- DP at low treewidth: decomposition of the system of equations
- Meet-in-the-Middle as “DP at the Half”
- Practical implementation in Python
- Limitations, countermeasures and conclusions
1. Introduction: ECDSA and the Hidden Number Problem
The ECDSA (Elliptic Curve Digital Signature Algorithm) scheme over a curve secp256k1 is the foundation of Bitcoin transaction security. Each signature for a message with a hash and a private key is formed as follows:
Here — generator of the order group (for secp256k1 ), A — a one-time secret (nonce) . It is the weakness of generation — the main cause of catastrophic private key leaks in Bitcoin (Sony PS3, Android SecureRandom attacks, wallet weaknesses, etc.).
The key idea is that if an attacker knows anything about the structure
(small Hamming weight, limited range, linear dependence on previous values), recovery problem
turns into a combinatorial one – and this is where dynamic programming comes into play.
2. Formalization of HNP for Bitcoin signatures
From the main equation we express :
If known signatures with a common , we obtain the system:
The classical Hidden Number Problem (HNP) (Boneh–Venkatesan, 1996) assumes that the most significant bits are known : , Where . Error vector — the “hidden” part, and it needs to be found. Lattice methods (LLL/BKZ) solve this problem if is quite small. But DP provides an alternative in combinatorial scenarios.
Why is DP applicable at all?
Because in many real leaks there is uncertainty in has a discrete combinatorial structure rather than a continuous interval:
| Leakage model | Parameter | What does DP give? |
|---|---|---|
| Low Hamming Weight Nonce | small | DP by bits |
| The nonce amount is limited | Knapsack DP | |
| Linear dependence (LCG) | low treewidth graph | Tree-decomposition DP |
| Nonce small in absolute value | etc. | Meet-in-the-Middle DP |
3. DP with a small parameter: nonce with low Hamming weight
3.1 Leakage Model
Let’s assume that the nonce generator is “economical”: (For example, or ). Then – sum powers of two:
Candidate space: . At This — still a lot to go through, but structured.
3.2 The idea of dynamic programming
State:
– Boolean, is it achievable using bits
, dial evenly
units and get a partial sum
.
Transition (transition): on the beat
either 0 or 1:
Answer: we are looking for
, satisfying
for some
.
An obvious problem: dimensionality equal Pure DP modulo is impossible. But there are three saving graces:
- Truncation modulo : if we know how to test a hypothesis on the least significant bits, it is possible to carry out DP by .
- Connection with signature equation : we do not iterate blindly, but we conduct the DP by imposing a constraint from the equation.
- Cryptographic reduction : instead of complete we work with a derivative quantity ; then that’s all .
3.3. A practical bit-wise DP scheme with two signatures
Let’s take two signatures And . Of these:
Both have a Hamming weight This imposes a joint constraint on , which can be processed by DP:
- For each bit position we add to the partial value (in least significant bits) term affecting the bit V And .
- State: , Where — the number of units already set, carry — carries from additions .
- Final check: , , and modulo a consistent value is obtained .
Complexity.
, Where
— the number of possible carry states, usually exponentially small for small
This is a quality win against
.
3.4. Multi-signature version (m signatures)
If there is signatures with a known upper weight for each, you can build a DP table based on signature indices and bit positions:
dp[j1][j2][...][jm] -> множество достижимых битовых масок d
At And the method becomes statistically stable: random false solutions are filtered out.
4. Limited Amount DP: The Knapsack Approach
4.1. Model
Let’s assume the attacker knows that are small and their amount is limited: , Where Then the problem is reduced to the knapsack problem .
4.2. Reduction to knapsack
Let’s express the sum through :
Where , (both quantities ). Condition means that the value falls into a narrow window This is a linear congruence with a small right-hand side, to which the modulo DP applies – if we work in the “centered” representation.
4.3. DP diagram
- Split the range on blocks by bit (for example, ): .
- Build a table : the number of ways in which the first bytes give a partial sum and carry .
- At each step, update the states: , .
- At the end, select the states where the final value is lies in .
4.4. Hybrid with lattices
Knapsack-DP combines well with LLL: the lattice provides candidates for , and the DP filters them. This is especially effective when the window too narrow for a pure grid, but too wide for direct enumeration.
5. DP at low treewidth: decomposition of the system of equations
5.1 Where does treewidth come from?
In real wallets, nonces are often generated deterministically (RFC 6979, Deterministic Wallets) or pseudo-randomly with a linear dependence : or
If is a linear function, then the variables are related by a system of equations whose graph has low treewidth . Classic examples:
| Generation scheme | Graph | Treewidth |
|---|---|---|
| Independent | Star (center – ) | 1 |
| LCG: | Chain + | 2 |
| LCG + high-order bit leakage | Chain with “noise” | 3–4 |
| Fibonacci-like generator | Stripe width 2 | 3 |
5.2 Formal Definition
Tree decomposition of a graph – this is a couple , Where — a tree, and to each node “bag” is associated , such that:
- ,
- for each edge exists With ,
- set forms a connected subtree in .
Width = Treewidth — minimum for all decompositions.
5.3. Tree DP algorithm
Input: graph of variables and equations, tree decomposition
Step 1. Select the root in
Step 2. For each leaf , construct a table of bag variable values consistent with local equations.
Step 3. Bottom-up: merge child tables, project to the intersection of bags (join), filter by equations at the node.
Step 4. At the root, obtain the set of admissible values for
Difficulty :
, Where
— the size of the variable domain.
5.4 Example: LCG with leaky low-order bits
Let and for each signature the junior ones are known bit : Then the variables are related by the system:
The graph has treewidth 2 (chain ). The DP along this chain works for – at This is entirely practical , whereas lattice methods would require more complex setup.
6. Meet-in-the-Middle as “DP at half”
A special case of DP is Meet-in-the-Middle (MITM) : partitioning the space in half and merging the tables. For a low-Hamming-weight nonce:
Building a hash table , then for each let’s check if there is in the table. Complexity – at This , still a lot, but with a few captions and a filter – realistic.
7. Practical implementation in Python
7.1 ECDSA signature framework over secp256k1
import hashlib
from ecdsa import SECP256k1, SigningKey # pip install ecdsa
n = SECP256k1.order
G = SECP256k1.generator
def sign(sk: SigningKey, msg: bytes):
z = int.from_bytes(hashlib.sha256(msg).digest(), "big") % n
# ВНИМАНИЕ: используем слабый nonce для демонстрации
k = 0b100000010000001000000100000010 # wt=5
R = k * G
r = R.x() % n
s = pow(k, -1, n) * (z + r * sk.privkey.secret_multiplier) % n
return z, r, s
7.2. DP for nonce with low Hamming weight (illustration)
from functools import lru_cache
def recover_d_dp(sigs, w_max=8, bits=256):
"""
sigs: список (z, r, s)
Ищем d, при котором все k_i = s_i^{-1}(z_i + r_i d) mod n
имеют вес Хэмминга <= w_max.
"""
inv = [(pow(s, -1, n), z, r) for (z, r, s) in sigs]
@lru_cache(maxsize=None)
def weight_matches(d):
return all(
bin((si * (zi + ri * d)) % n).count("1") <= w_max
for (si, zi, ri) in inv
)
# Простейший перебор по структуре "низкого веса" (учебный пример)
from itertools import combinations
for bitset in combinations(range(bits), w_max):
d = sum(1 << b for b in bitset) % n
if weight_matches(d):
return d
return None
7.3. Knapsack-DP by nonce amount
def knapsack_dp(alpha, beta, S, B=8):
"""
Ищем d такое, что (A + B*d) mod n <= S.
alpha, beta: списки коэффициентов; A = sum(alpha), B = sum(beta) mod n
ДП по байтам d_j.
"""
A = sum(alpha) % n
Bsum = sum(beta) % n
K = 256 // B
# dp: словарь (partial_sum_hi, carry) -> list of d_low
# Упрощённая схема: перебираем байты, храним (sum mod n, d_so_far)
states = {0: [0]} # sum mod n -> список d
mask = (1 << B) - 1
for j in range(K):
new_states = {}
for s_val, ds in states.items():
for dj in range(256):
nv = (s_val + dj * Bsum * pow(2, B*j, n)) % n
new_states.setdefault(nv, [])
if len(new_states[nv]) < 64: # prune
new_states[nv].extend([(d << B) | dj for d in ds[:4]])
states = new_states
# финальный фильтр
results = []
for s_val, ds in states.items():
for d in ds:
if ((A + Bsum * d) % n) <= S:
results.append(d)
return results
7.4. Tree-decomposition of DP (conceptual example)
def tree_dp_lcg(kappas, alpha, beta, a, b, L=16):
"""
k_{i+1} = a*k_i + b mod n; известны младшие L бит kappas[i] = k_i mod 2^L.
Возвращаем d, согласованное со всеми подписями.
"""
m = len(kappas)
mask = (1 << L) - 1
# Таблицы для каждого узла: (k_i_low, d_low) -> set of (k_i mod n) candidates
# Здесь — упрощённая схема для illustration.
candidates = {}
for i in range(m):
si, zi, ri = alpha[i], beta[i], 0 # заглушка для демонстрации структуры
# ... заполнение таблиц ДП по цепи ...
return candidates # список d-кандидатов
Note: The fragments shown are for training purposes. In real attacks, the amount of computation required requires C++/Rust and optimized structures (Bloom filters, partitioning, GPU). However, the principle is the same: replace exponential search with a structured DP table.
8. Limitations, Countermeasures, and Conclusions
8.1 Comparison with Lattice Methods
| Method | Leakage | Complexity | Comment |
|---|---|---|---|
| LLL/BKZ (Boneh–Venkatesan) | Most significant bits | Polynomial with small total leakage | De facto standard |
| DP by bits | Low Hamming weight | Exponential by , but with little basis | Works where lattices do not model discreteness well |
| Knapsack-DP | Limited amount | Effective at low And | |
| Tree-DP | Linear dependencies | Breakthrough at |
8.2. When DP won’t help
- Nonce is cryptographically strong (CSPRNG) – DP is useless.
- Leakage of high bits at large — LLL faster.
- High treewidth (random dependencies) – DP tables explode.
- Domain size does not allow storing tables directly.
8.3. Practical countermeasures (for the defending party)
- RFC 6979 – Deterministic nonce based on HMAC-SHA256; eliminates “random” weaknesses.
- Hamming weight validation – reject With .
- Range Check – cuts out many DP scenarios.
- Elimination of linear dependencies – LCG for nonce is prohibited.
- Schnorr/BIP-340 is a simpler and more secure signature scheme where HNP attacks are more difficult.
8.4. Summary
Dynamic programming is not a universal replacement for lattice methods, but a specialized tool for cryptanalysis of ECDSA under combinatorial nonce leaks:
- small parameter – DP by Hamming weight bits;
- limited amount – knapsack-DP modulo;
- low treewidth — tree-decomposition of DP by the equation graph;
- MITM – “DP in half” of the search space.
By combining these approaches with LLL/BKZ, one can solve problems inaccessible to either pure lattices or brute force. It is at the intersection of these methods that the cutting edge of modern ECDSA cryptanalysis lies.
Disclaimer: This material is provided for educational and research purposes only: to audit proprietary cryptographic implementations, study HNP theory, and develop secure nonce generators. Applying the described methods to someone else’s keys without the owner’s express permission is punishable by law.
