Skip to main content
Cipher Visualizers home

Breaking ECDSA with Biased Nonces: The Hidden Number Problem

ECDSA stays secure only while every nonce is uniform and secret. If each nonce is slightly biased, even with no repeats, a handful of signatures leak the private key. This guide turns biased secp256k1 signatures into a lattice problem and recovers the key with LLL.

Pashalis Laoutaris 16 min read

Try it

Interactive ECDSA Biased-Nonce Lattice Attack

🔐 ECDSA Biased-Nonce Lattice Attack (HNP)

Real ECDSA on secp256k1 (the Bitcoin curve). The private key and nonces are the signer's secrets. The attacker uses only the public signatures and the known bias.
Enter text and click a button to start!
1. Captured signatures with biased nonces
2. Each signature is a line: k = A + B·d (mod n)
3. The small nonces are a short lattice vector (LLL)
4. The private key falls out
Click the button to recover an ECDSA key from signatures with biased nonces.

Breaking ECDSA with Biased Nonces: The Hidden Number Problem

Introduction

ECDSA signs with a fresh random number for every signature, the nonce k. The reused-nonce attack shows what happens when two signatures share a nonce: the key falls out of one subtraction. That is the dramatic failure. This guide is about the quiet one.

Suppose the nonce is never reused, but it is slightly biased: a few of its top bits are always zero, or always known, because of a truncated random source or a timing leak. No single signature looks wrong, and every one verifies. Yet a handful of them together leak the whole private key. The trick is to cast the problem as the Hidden Number Problem and solve it with lattice reduction. This is the attack behind real breaks like Minerva and LadderLeak, and it reuses the LLL algorithm from the Merkle-Hellman breaker.

Table of Contents

From a Signature to a Line

An ECDSA signature on a message with hash h is a pair (r, s), where r is the x-coordinate of k·G reduced mod the group order n, and:

s = k^-1 * (h + r*d) mod n

Here d is the private key and k is the nonce. Multiply through by k and solve for it:

k = s^-1*h + s^-1*r*d  (mod n)

Write A = s^-1*h mod n and B = s^-1*r mod n. Both are computed from public values, the signature and the hash. So each signature gives one equation:

k = A + B*d  (mod n)

A line through the unknowns k and d, modulo n. With d the single secret shared by every signature, and a different k each time.

The Hidden Number Problem

Normally this helps no one, because k is a full-size random number, as unknown as d. The attack needs one extra fact: the nonce is small, or more precisely, the attacker knows some of its high bits. Say a buggy generator always leaves the top bits zero, so every k is below some bound K = 2^L that is much smaller than n.

Now the equation k = A + B*d mod n says that A + B*d, reduced mod n, lands in the tiny range [0, K). The secret d is the “hidden number”, and each biased signature is an approximation to a multiple of it. This is exactly the Hidden Number Problem of Boneh and Venkatesan, and Nguyen and Shparlinski showed it breaks DSA and ECDSA with partially known nonces. The way to solve it is a lattice.

Building the Lattice

Collect m signatures, each giving k_i = A_i + B_i*d mod n with 0 <= k_i < K. Consider the lattice spanned by these rows (everything is scaled by n so the integer LLL stays exact):

row i (i=1..m):  n^2 on the diagonal, 0 elsewhere
row m+1:         (B_1*n, B_2*n, ..., B_m*n,  K,   0)
row m+2:         (A_1*n, A_2*n, ..., A_m*n,  0,   K*n)

Take row(m+2) + d·row(m+1) and subtract the right multiples of the first m rows to reduce each coordinate modulo n. That combination comes out as:

(n*k_1, n*k_2, ..., n*k_m,  d*K,  K*n)

Every entry is around n*K in size, because the small k_i are scaled up by n, the key d is scaled down by K/n, and the last entry is fixed. So this vector is unusually short, far shorter than a typical lattice point, which is around n times larger. LLL reduction finds it. The row it returns has ±K*n in its last slot, and the second-to-last slot holds ±d*K, so dividing by K gives the private key. A quick check that d·G equals the public key confirms it, and fixes the sign.

How Many Signatures

Each biased signature contributes the number of leaked bits per nonce, which is 256 - L on a 256-bit curve. The key has 256 bits, so you need roughly:

m  >  256 / (256 - L)

signatures, plus a small margin for LLL. If half of each nonce leaks, L = 128, that is about 2 to 3 signatures. If only the top 64 bits leak, L = 192, it is about 4 to 5. The measurements in the code match this: L = 96 needs 2, L = 128 and L = 160 need 3, and L = 192 needs 5. Fewer leaked bits per nonce need more signatures, which is why real attacks that leak just one or two bits collect thousands.

Interactive Visualizer

The visualizer above runs the attack on real secp256k1. Choose how biased the nonces are and how many signatures to capture. The signer uses a fixed private key and a buggy generator that leaves the nonces small; the attacker sees only the public key and the signatures.

The four cards show the captured signatures, the k = A + B·d equations, the lattice that LLL reduces, and the recovered key checked against the public key. Lower the signature count below what the bias needs and the attack reports that it needs more. The same arithmetic runs in the Python below, and the two agree on the signatures and the recovered key.

A Worked Example

The signer’s private key is fixed, and its generator leaves the top 128 bits of every nonce zero, so each k is below 2^128. The attacker captures five signatures on secp256k1. Each one verifies normally; the bias is invisible.

The attacker forms A_i and B_i from each signature, builds the seven-dimensional lattice above, and runs LLL. The reduced basis contains a row whose last entry is ±K·n, and the slot before it, divided by K, is the private key. Checking d·G against the public key confirms the match. Five biased signatures, one lattice reduction, and the full secp256k1 key is recovered, with no nonce ever reused.

Python Implementation

This is real secp256k1, ECDSA signing with small nonces, and the lattice attack. The first file is the attack; the second is the integer LLL from the Merkle-Hellman guide, which must sit beside it.

# ecdsa_hnp.py
#
# Recovering an ECDSA private key from signatures whose nonces are biased, via the Hidden Number Problem
# and LLL. Each signature gives k = A + B*d (mod n), where d is the secret key. If each nonce k is small
# (only its low bits are random, the top bits zero), the k values are a short vector in a lattice built
# from the public signatures, and LLL finds it, which reveals d. Real secp256k1. Needs lll.py alongside.

import hashlib

from lll import lll_reduce

# ---- secp256k1 ----
P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
A = 0
B = 7
GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
G = (GX, GY)


def inv(a, m):
    return pow(a, -1, m)


def point_add(p1, p2):
    if p1 is None:
        return p2
    if p2 is None:
        return p1
    x1, y1 = p1
    x2, y2 = p2
    if x1 == x2 and (y1 + y2) % P == 0:
        return None
    if p1 == p2:
        m = (3 * x1 * x1 + A) * inv(2 * y1, P) % P
    else:
        m = (y2 - y1) * inv(x2 - x1, P) % P
    x3 = (m * m - x1 - x2) % P
    y3 = (m * (x1 - x3) - y1) % P
    return (x3, y3)


def scalar_mul(k, pt):
    r = None
    addend = pt
    while k:
        if k & 1:
            r = point_add(r, addend)
        addend = point_add(addend, addend)
        k >>= 1
    return r


def h_of(message):
    return int.from_bytes(hashlib.sha256(message).digest(), "big") % N


def sign(message, k, d):
    r = scalar_mul(k, G)[0] % N
    s = inv(k, N) * (h_of(message) + r * d) % N
    return r, s


def verify(message, r, s, Q):
    w = inv(s, N)
    u1 = h_of(message) * w % N
    u2 = r * w % N
    pt = point_add(scalar_mul(u1, G), scalar_mul(u2, Q))
    return pt is not None and pt[0] % N == r


def attack(sigs, msgs, bound_bits, pubkey):
    """sigs: [(r, s)], msgs: matching messages, each nonce < 2^bound_bits. Returns d or None.

    k_i = A_i + B_i*d (mod n), with A_i = s_i^-1 h_i, B_i = s_i^-1 r_i. The vector of small k_i is short
    in the lattice below (everything scaled by n so the integral LLL stays exact). The row whose last
    entry is +-K*n carries d*K in its second-to-last slot.
    """
    m = len(sigs)
    K = 1 << bound_bits
    Avec, Bvec = [], []
    for (r, s), msg in zip(sigs, msgs):
        sinv = inv(s, N)
        Avec.append(sinv * h_of(msg) % N)
        Bvec.append(sinv * r % N)

    dim = m + 2
    basis = [[0] * dim for _ in range(dim)]
    for i in range(m):
        basis[i][i] = N * N                      # n^2 on the diagonal (scaled by n)
    for i in range(m):
        basis[m][i] = Bvec[i] * N                # the d row
    basis[m][m] = K
    for i in range(m):
        basis[m + 1][i] = Avec[i] * N            # the constant row
    basis[m + 1][m + 1] = K * N

    reduced, _ = lll_reduce(basis)
    for row in reduced:
        if abs(row[m + 1]) == K * N and row[m] % K == 0:
            for sign_ in (1, -1):
                d = (sign_ * row[m] // K) % N
                if scalar_mul(d, G) == pubkey:
                    return d
    return None


if __name__ == "__main__":
    # a fixed private key, known only to the signer
    d = 0x5f3c9a2b7e1d4068a9c3b5e70f2d8419c6a1b4e7d0938f52ac6e1b3d4f70825a % N
    PUBKEY = scalar_mul(d, G)
    print("secp256k1. The attacker sees only the public key and the biased signatures.")
    print("true private key d = %064x" % d)

    bound_bits = 128           # the buggy RNG leaves the top 128 bits of every nonce zero
    m = 5                      # a handful of signatures
    sigs, msgs = [], []
    for i in range(m):
        msg = ("transfer %d coins, memo %d" % (i * 10, i)).encode()
        # a small nonce: only the low bound_bits are set (deterministic here for reproducibility)
        k = (int.from_bytes(hashlib.sha256(b"nonce" + msg).digest(), "big") % (1 << bound_bits)) | 1
        sigs.append(sign(msg, k, d))
        msgs.append(msg)
    print("captured %d signatures, each with a nonce below 2^%d" % (m, bound_bits))
    print("every signature verifies:", all(verify(msg, r, s, PUBKEY) for (r, s), msg in zip(sigs, msgs)))

    recovered = attack(sigs, msgs, bound_bits, PUBKEY)
    print("\nrecovered d = %064x" % (recovered if recovered is not None else 0))
    print("recovered == true key:", recovered == d)
# lll.py
#
# The LLL lattice basis reduction algorithm of Lenstra, Lenstra and Lovasz,
# in the integral form of Cohen (Algorithm 2.6.7 of "A Course in
# Computational Algebraic Number Theory"). All numbers are whole numbers, so
# there is no rounding error. The basis is a list of rows of integers.


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def lll_reduce(basis, delta_num=3, delta_den=4):
    """Return an LLL-reduced copy of the basis (parameter 3/4 by default) and the number of swaps."""
    b = [list(row) for row in basis]
    n = len(b)
    if n == 0:
        return b, 0
    swaps = 0
    # d[i] = the product of the squared Gram-Schmidt norms of the first i vectors (d[0] = 1)
    d = [1] + [0] * n
    lam = [[0] * n for _ in range(n)]  # lam[i][j] for j < i: the integer d[j+1] * mu[i][j]
    d[1] = dot(b[0], b[0])
    k, kmax = 1, 0

    def reduce(k, l):
        # make |mu[k][l]| <= 1/2
        if 2 * abs(lam[k][l]) > d[l + 1]:
            q = (2 * lam[k][l] + d[l + 1]) // (2 * d[l + 1])
            b[k] = [x - q * y for x, y in zip(b[k], b[l])]
            lam[k][l] -= q * d[l + 1]
            for i in range(l):
                lam[k][i] -= q * lam[l][i]

    def swap(k):
        nonlocal swaps
        swaps += 1
        b[k], b[k - 1] = b[k - 1], b[k]
        for j in range(k - 1):
            lam[k][j], lam[k - 1][j] = lam[k - 1][j], lam[k][j]
        lmb = lam[k][k - 1]
        big_b = (d[k - 1] * d[k + 1] + lmb * lmb) // d[k]
        for i in range(k + 1, kmax + 1):
            t = lam[i][k]
            lam[i][k] = (d[k + 1] * lam[i][k - 1] - lmb * t) // d[k]
            lam[i][k - 1] = (big_b * t + lmb * lam[i][k]) // d[k + 1]
        d[k] = big_b

    while k < n:
        if k > kmax:
            kmax = k
            for j in range(k + 1):
                u = dot(b[k], b[j])
                for i in range(j):
                    u = (d[i + 1] * u - lam[k][i] * lam[j][i]) // d[i]
                if j < k:
                    lam[k][j] = u
                else:
                    d[k + 1] = u
                    if u == 0:
                        raise ValueError("the vectors are linearly dependent")
        reduce(k, k - 1)
        # Lovasz condition: |b*_k|^2 >= (delta - mu^2) |b*_(k-1)|^2, in integers
        if delta_den * d[k + 1] * d[k - 1] < delta_num * d[k] * d[k] - delta_den * lam[k][k - 1] ** 2:
            swap(k)
            k = max(1, k - 1)
        else:
            for l in range(k - 2, -1, -1):
                reduce(k, l)
            k += 1
    return b, swaps

Running the first file prints this:

secp256k1. The attacker sees only the public key and the biased signatures.
true private key d = 5f3c9a2b7e1d4068a9c3b5e70f2d8419c6a1b4e7d0938f52ac6e1b3d4f70825a
captured 5 signatures, each with a nonce below 2^128
every signature verifies: True

recovered d = 5f3c9a2b7e1d4068a9c3b5e70f2d8419c6a1b4e7d0938f52ac6e1b3d4f70825a
recovered == true key: True

I checked the code several ways. Every signature verifies with standard ECDSA verification before the attack runs, so the key and curve arithmetic are correct. The attack recovers the exact private key and confirms it by checking d·G against the public key. A sweep over bias sizes matched the signature-count rule: L = 96 needed 2 signatures, L = 128 and 160 needed 3, and L = 192 needed 5, each recovering the key in 10 of 10 random trials. The JavaScript in the visualizer agrees with the Python on all 16 shared cases, covering the signatures and the recovered key. This includes the cases with too few signatures, where both correctly report failure. Its from-scratch SHA-256 and secp256k1 match the Python too.

Limitations

The bias is a stand-in. The code uses nonces with zero high bits, a clean model of a biased or truncated generator. Real leaks are subtler: a timing side channel that reveals the nonce’s bit length (Minerva), or less than one bit of bias per signature (LadderLeak). Those need many more signatures and extra statistical work, but the lattice core is the same.

The attacker must know the bias. The lattice uses the bound K. The attacker has to know, or guess, how many top bits leak. A wrong bound makes the target vector too long or too short for LLL to find.

LLL, not BKZ. This uses plain LLL, which is enough for a generous bias and a small lattice. Attacks that squeeze the key out of a tiny leak use stronger reduction, like BKZ, and larger lattices. The method here does not scale to one-bit leaks on its own.

Teaching code. The lattice is small and the arithmetic favors clarity. The attack is the same at any curve size, since it is one LLL reduction.

Security Status

ECDSA is secure only when the nonce is uniform over [1, n-1] and secret. Any deviation is dangerous: a repeat gives the key instantly, and even a small bias gives it with a few signatures and a lattice. The failures are famous, from the 2010 PlayStation 3 break to the Android Bitcoin thefts of 2013, and the subtler Minerva and LadderLeak results that extract keys from tiny timing leaks.

The fix is to remove the randomness as a failure point. RFC 6979 derives the nonce deterministically from the message and the private key with HMAC, so it is reproducible, unbiased, and never repeated. Modern signature schemes like Ed25519 build this in by design. Where randomness is still used, it must be a cryptographic generator with full output, and constant-time code must avoid leaking the nonce’s size. The lesson is that in ECDSA the nonce is as sensitive as the key itself.

FAQ

Is this the same as the reused-nonce attack?

No, it is stronger in what it tolerates. The reused-nonce attack needs two signatures to share a nonce exactly. This one needs only that each nonce is biased, never repeated, and recovers the key from several such signatures with a lattice.

How biased does the nonce have to be?

Any consistent, known bias works, given enough signatures. If half of each nonce’s bits leak, two or three signatures suffice. If only a bit or two leak, you need thousands and stronger lattice reduction, which is what LadderLeak demonstrated.

Why does making the nonce small help the attacker?

Each signature says A + B·d mod n lands in a small range. That turns the key into a hidden number approximated by every signature, and the vector of those small nonces becomes the shortest vector in a lattice the attacker can build. LLL finds shortest vectors.

Does this affect Ed25519 or RFC 6979 ECDSA?

No, neither one is affected. Both derive the nonce deterministically from the message and the key, so it is unbiased and never repeated by construction. The attack needs a biased or leaky nonce, which deterministic generation removes.

What does the LLL step actually do here?

It takes the lattice built from the public signatures and returns a basis of short, nearly orthogonal vectors. The vector encoding the small secret nonces is far shorter than any other, so it appears in the reduced basis, and the private key is read directly from it.

References

  1. Boneh, Dan, and Ramarathnam Venkatesan. “Hardness of Computing the Most Significant Bits of Secret Keys in Diffie-Hellman and Related Schemes.” CRYPTO ’96 (the Hidden Number Problem).

  2. Nguyen, Phong Q., and Igor E. Shparlinski. “The Insecurity of the Elliptic Curve Digital Signature Algorithm with Partially Known Nonces.” Designs, Codes and Cryptography 30(2), 2003, pp. 201-217.

  3. Howgrave-Graham, Nick, and Nigel P. Smart. “Lattice Attacks on Digital Signature Schemes.” Designs, Codes and Cryptography 23(3), 2001, pp. 283-290.

  4. Jancar, Jan, Vladimir Sedlacek, Petr Svenda, and Marek Sys. “Minerva: The Curse of ECDSA Nonces.” CHES 2020.

  5. Aranha, Diego F., Felipe Rodrigues Novaes, Akira Takahashi, Mehdi Tibouchi, and Yuval Yarom. “LadderLeak: Breaking ECDSA with Less than One Bit of Nonce Leakage.” ACM CCS 2020.

  6. The LLL algorithm and its implementation on this site, reused by this attack: /blog/mh_guide/

A visual representation of recovering a Merkle-Hellman private key from the public key with lattice reduction
Modern & Applied Cryptography Breakers Advanced

Breaking Merkle-Hellman: Recovering the Key from the Public Key

Shamir broke the basic Merkle-Hellman knapsack in 1982 without seeing a single ciphertext. This guide rebuilds his key-recovery attack with a small LLL lattice, finds a working private key for the guide's 32-bit key in milliseconds, and measures it on keys of up to 256 bits.

21 min read

A visual representation of recovering an ECDSA private key from two signatures that reused the same nonce
Modern & Applied Cryptography Breakers Advanced

Recovering a DSA or ECDSA Key from a Reused Nonce

DSA and ECDSA stake everything on a secret random nonce that must never repeat. Sign two messages with the same nonce and the private key drops out with a little algebra. This guide runs the real attack against real DSA and secp256k1, the same flaw that broke the PS3 and drained Bitcoin wallets.

12 min read

A visual representation of a faulty RSA-CRT signature being factored by a single gcd
Modern & Applied Cryptography Breakers Advanced

The Bellcore Attack: One Fault Breaks RSA-CRT

Most RSA implementations sign with the Chinese Remainder Theorem for a 4x speedup. A single bit-flip during that computation produces a faulty signature that is correct modulo one prime and wrong modulo the other, and one gcd then factors the key. This guide runs the Bellcore attack on a real 128-byte RSA key.

12 min read