Bayes’ theorem provides a rigorous probabilistic framework for cryptanalysis of ECDSA under incomplete information. While Bayesian inference alone doesn’t “break” ECDSA (the discrete logarithm problem remains computationally difficult), it allows for the effective exploitation of indirect leaks —nonce biases, side channels, and reuse—to narrow the search space for the private key.
Bayes’ theorem is a fundamental result of probability theory that allows us to revise the probabilities of hypotheses as new data becomes available. In its classical formulation for discrete hypotheses H and observations E:
P(H | E) = [ P(E | H) · P(H) ] / P(E)
where P(H) is the a priori probability of the hypothesis, P(E | H) is the likelihood of an observation under the given hypothesis, P(H | E) is the a posteriori probability, and P(E) is the total probability of an observation (normalizing constant).
In the context of the Elliptic Curve Digital Signature Algorithm (ECDSA) , used in Bitcoin secp256k1, Bayesian inference can be used to refine the distribution of hidden values —primarily the nonce k and private key d. While the Bayesian approach is not a “silver bullet” for breaking ECDSA (the discrete logarithm problem remains computationally difficult), it represents a powerful statistical layer on top of other cryptanalytic methods, allowing one to extract information from incomplete, noisy, or indirect data.
1. Mathematical foundations of ECDSA and points of vulnerability
1.1 A Brief Reminder of the ECDSA Algorithm
Let be E an elliptic curve over a finite field F_p, G be a base point of order n. Let be a private key d ∈ [1, n-1], and let be a public key Q = dG.
To sign a message with a hash z:
- A random nonce
k ∈ [1, n-1]is generated . - The point is calculated
R = kGand takenr = R.x mod n. - Calculated .
s = k-1(z + r·d) mod n - Signature – pair
(r, s).
The signature equation can be rewritten as:
k ≡ s-1 · z + s-1 · r · d (mod n)
This linear relationship relates the known quantities ( r, s, z) to the unknowns k and d. If k is known for at least one signature, the private key is recovered immediately: . This is why the nonce is a critical vulnerability.d = (s·k − z) · r-1 mod n
1.2 Why is the Bayesian approach relevant?
In practice, an attacker rarely knows k exactly. However, they may have partial information :
- Bias in generation
k(e.g. some bits are always zero)[reference:0]. - Side-channel leakage, such as execution time or power consumption[reference:1].
- Reuse
kor linear relationship between nonces of different signatures[reference:2].
In such settings, Bayesian inference allows one to formally combine prior knowledge about the distribution k (e.g., a bias assumption) with the observed data (the signatures) to obtain a posterior distribution from which one can extract an estimate of d or k.
2. Bayesian model for nonce and private key recovery
2.1. Task statement
Suppose an attacker has collected N ECDSA signatures: (r_i, s_i, z_i), i = 1..N. For each signature, there is an unknown nonce k_i. The attacker has some leakage model : for example, they know that the high-order b bits of each k_i are zero (the offset)[reference:3].
The goal is to find a value dthat maximizes the posterior probability:
P(d | Data) ∝ P(Data | d) · P(d)
where P(d) is the prior distribution of the private key (usually assumed to be uniform on [1, n-1]if there is no additional information), and P(Данные | d) is the likelihood of observing signatures given d.
2.2. Likelihood function
For each signature i from the equation, can be calculated for a given . Then the likelihood of the observation depends on the leakage model. For example, if it is known that is in the interval (the least significant bits are free and the most significant bits are zero), then:k_i = s_i-1(z_i + r_i·d) mod nk_idk_ik_i[0, 2t)t
P(k_i | d) = 1 if 0 ≤ k_i < 2 t ; otherwise 0
If the leak is probabilistic (e.g., k_i it falls within the interval with probability p, and outside it with probability 1-p), then the likelihood takes the form of a mixture of distributions. More generally, when the distribution function f(k) for the nonce is known, the likelihood is written as P(k_i | d) = f(k_i).
2.3. A posteriori inference
For N independent signatures, the posterior distribution d is proportional to:
P(d | Data) ∝ P(d) · ∏ i=1 N P(k_i(d) | d)
where . Maximizing this expression over (the MAP estimate) yields the most probable value of the private key. In practice, the space is huge ( ), so a straightforward search is impossible. However, the Bayesian framework can be combined with lattice methods (lattice reduction) for efficient search.k_i(d) = s_i-1(z_i + r_i·d) mod nddn ≈ 2256
2.4 Relationship with the Hidden Number Problem (HNP)
As is well known, recovering an ECDSA key when a portion of the nonce is leaked reduces to the Hidden Number Problem (HNP) [reference:4]. The Bayesian approach can be viewed as a probabilistic superstructure over HNP: instead of hard constraints on , k_i we specify a distribution and seek d, which maximizes the joint probability.
3. Practical implementation: Bayesian analysis of biased nonces
3.1 Scenario: Known High-Bit Offset
Let’s consider a simplified but illustrative example. Assume the attacker knows that all nonces are generated with the upper 8 bits cleared (i.e. ). This is a realistic situation with PRNG bugs or hardware vulnerabilities [reference:5].k_i < 2248
A Bayesian algorithm might look like this:
import hashlib
from ecdsa import SigningKey, SECP256k1
import numpy as np
# Параметры кривой secp256k1
n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
def sign(msg_hash, private_key, nonce_bias_bits=8):
"""
Генерация подписи ECDSA с искусственно смещённым nonce.
nonce_bias_bits — количество обнулённых старших бит.
"""
sk = SigningKey.from_secret_exponent(private_key, curve=SECP256k1)
# Генерируем смещённый nonce: берём случайное число и сдвигаем
raw_nonce = int.from_bytes(hashlib.sha256(str(np.random.rand()).encode()).digest(), 'big')
# Обнуляем старшие биты, чтобы nonce был меньше 2^(256 - bias)
k = raw_nonce >> nonce_bias_bits
if k == 0:
k = 1
# Подписываем с этим nonce (упрощённо: перехватываем k)
# В реальности нужно использовать ECDSA с фиксированным k,
# но для демонстрации покажем уравнение.
sig = sk.sign_digest(msg_hash, sigencode=lambda r, s: (r, s), k=k)
r, s = sig
return r, s, k
def bayesian_score(d_guess, signatures, bias_bits):
"""
Вычисляет логарифм правдоподобия для данного d_guess.
signatures: список (r, s, z)
bias_bits: сколько старших бит обнулено
"""
log_likelihood = 0.0
threshold = 2 ** (256 - bias_bits) # максимально возможное значение k
for (r, s, z) in signatures:
# k = s^{-1} * (z + r * d) mod n
s_inv = pow(s, -1, n)
k_candidate = (s_inv * (z + r * d_guess)) % n
# Правдоподобие: 1 если k_candidate < threshold, иначе очень мало
if k_candidate < threshold:
log_likelihood += 0.0 # log(1)
else:
log_likelihood -= 100.0 # штраф за несоответствие модели
return log_likelihood
# --- Демонстрация ---
# Задаём истинный приватный ключ (для теста)
true_d = 0x1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF
# Собираем несколько подписей с смещёнными nonce
msg_hash = hashlib.sha256(b"test message").digest()
signatures = []
for _ in range(5):
r, s, k = sign(msg_hash, true_d, nonce_bias_bits=8)
z = int.from_bytes(msg_hash, 'big') % n
signatures.append((r, s, z))
# Байесовский поиск: перебираем кандидатов d в окрестности
# (в реальности используется решётка или MCMC, здесь — упрощённо)
best_d = None
best_score = -np.inf
# Для демонстрации переберём небольшой диапазон (в реальности — миллионы)
for delta in range(-1000, 1000):
d_candidate = (true_d + delta) % n
score = bayesian_score(d_candidate, signatures, bias_bits=8)
if score > best_score:
best_score = score
best_d = d_candidate
print(f"Истинный d: {hex(true_d)}")
print(f"Найденный d: {hex(best_d)}")
print(f"Совпадение: {best_d == true_d}")
print(f"Лучший скор: {best_score}")
In this simplified example, the Bayesian score is used to select the most likely d. In a real attack, the search space requires the use of lattice algorithms (LLL, BKZ) or Markov Chain Monte Carlo (MCMC) methods to efficiently navigate the posterior distribution.2256
3.2. Bayesian Inference for Nonces with Probabilistic Leakage (LadderLeak)
The LadderLeak attack demonstrates that leaking even less than one bit of nonce information can lead to key recovery [reference:6]. In this scenario, the most significant bit k is known with probability p < 1.
The Bayesian model takes the form:
P(observation | k) = p if the most significant bit matches the predicted one; (1-p) otherwise
The posterior distribution d is refined with each new signature. Combining this with lattice methods, it is possible to recover the key even with p ≈ 0.5 (i.e., with almost no information)[reference:7].
4. Limitations and challenges of the Bayesian approach
- Computational complexity. The private key space does not allow for direct computation of the posterior distribution. Approximate methods are required: MCMC, variational inference, or lattice algorithms.
2256 - Quality of the prior model. If the nonce leakage model is incorrect, Bayesian inference may produce biased estimates. Careful likelihood calibration is necessary.
- Data volume dependence. Reliable key recovery may require thousands to millions of signatures, depending on the severity of the leak[reference:8].
- Attacker adaptability. Modern Bitcoin implementations (e.g., those with RFC 6979) use deterministic nonce generation, making Bayesian bias-based attacks ineffective without additional leaks.
5. Extensions: Bayesian inference in lattice attacks
The most promising direction is hybrid methods , where Bayesian inference is used for pre-filtering or weighting candidates in lattice attacks.
Idea: The lattice algorithm (LLL/BKZ) finds short vectors corresponding to possible values of (k_1, ..., k_N, d). The Bayesian score ranks these vectors by likelihood, given the nonce prior. This is especially useful when the lattice yields several vectors of similar lengths, and the most probable one needs to be selected.
# Псевдокод гибридного байесовско-решёточного подхода
def hybrid_attack(signatures, bias_model):
# 1. Построение решётки HNP
lattice = build_hnp_lattice(signatures)
# 2. Редукция решётки (LLL/BKZ)
reduced_basis = bkz_reduce(lattice)
# 3. Извлечение кандидатов (k_i, d)
candidates = extract_candidates(reduced_basis)
# 4. Байесовское ранжирование
scored = []
for (k_vec, d) in candidates:
log_lik = sum(log(bias_model(k_i)) for k_i in k_vec)
scored.append((log_lik, d))
# 5. Выбор MAP-оценки
best_d = max(scored, key=lambda x: x[0])[1]
return best_d
6. Conclusion
Conclusion
Bayes’ theorem provides a rigorous probabilistic framework for cryptanalysis of ECDSA under incomplete information. While Bayesian inference alone doesn’t “break” ECDSA (the discrete logarithm problem remains computationally difficult), it allows for the effective exploitation of indirect leaks —nonce biases, side channels, and reuse—to narrow the search space for the private key.
Key advantages of the Bayesian approach:
- Formal unification of a priori knowledge and observed data.
- Natural handling of probabilistic (noisy) leaks.
- Compatibility with lattice methods for practical implementation.
The practical significance is particularly high for the analysis of real blockchain transactions , where signatures are publicly available and errors in nonce generation have historically led to the compromise of hundreds of Bitcoin and Ethereum private keys[reference:9].
Directions for further research for cryptanalysis based on this area
- Developing efficient MCMC algorithms for a posteriori inference in space .
2256Traditional Monte Carlo methods scale poorly to such large spaces. Hamiltonian MCMC and variational inference with neural approximations show promise. - Bayesian calibration of nonce leakage models. In practice, the nonce distribution may be unknown. Developing methods for online training of a priori models as new signatures are acquired (hierarchical Bayesian models) will enable adaptation to unknown types of vulnerabilities.
- Hybridization with machine learning. Using neural networks to approximate the posterior distribution
P(d | Данные)or to generate “hot” starting points for lattice algorithms. - Nonce time series analysis. If nonces are generated with temporal correlation (e.g., due to a weak PRNG), Bayesian time series models (hidden Markov models, Bayesian filters) can extract additional information.
- Application to threshold-ECDSA and MPC wallets. In distributed schemes, leaked signatures can be distributed among participants. Bayesian inference allows for the merging of incomplete information from different nodes.
- Quantum-Resistant Bayesian Cryptanalysis. Investigation of how Bayesian methods can be adapted to analyze post-quantum signature schemes (e.g., on lattices), where statistical leaks are also possible.
- Automated vulnerability detection in ECDSA implementations. Development of tools that analyze blockchain signature streams in real time and apply Bayesian tests to identify anomalies in nonce distributions.
This document is prepared for educational and research purposes. Applying the described methods to someone else’s cryptographic keys without permission is illegal.
