Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

The arithmetic of elliptic curves

By the end of this chapter, you'll be able to

  • Describe an elliptic curve over a finite field and check that a point belongs to it
  • Implement point addition, doubling and scalar multiplication
  • Carry out an ECDH key exchange on the secp256k1 curve
  • Validate received points to defeat the invalid-curve attack

A curve over a finite field

An elliptic curve is the set of points (x, y) satisfying y² = x³ + a·x + b. In cryptography, we compute modulo a prime p: the points then form a discrete cloud, and we add a special point, the point at infinity (written None in our code), which plays the role of zero.

We define an addition of points: the line through P and Q meets the curve at a third point; its mirror image is P + Q. For P + P (doubling), we take the tangent. These geometric rules become formulas, with modular inverses instead of divisions.

The reverse path, the elliptic-curve discrete logarithm, is out of reach for a 256-bit curve.

Step 5 of 5
Text description of the animation
  1. We read the bits of k, from least to most significant.
  2. At each step, we double the current point: 256 doublings are enough for a 256-bit k.
  3. When the bit is 1, we add the current point to the result.
  4. A few hundred operations instead of k − 1 additions.
  5. The reverse path, the elliptic-curve discrete logarithm, is out of reach for a 256-bit curve.
p, a, b = 97, 2, 14                 # toy curve: y² = x³ + 2x + 14 (mod 97), 101 points

def on_curve(P):
    return P is None or (P[1] ** 2 - P[0] ** 3 - a * P[0] - b) % p == 0

def add(P, Q):
    if P is None: return Q
    if Q is None: return P
    if P[0] == Q[0] and (P[1] + Q[1]) % p == 0:
        return None                                   # P + (−P) = point at infinity
    if P == Q:
        slope = (3 * P[0] ** 2 + a) * pow(2 * P[1], -1, p)     # tangent
    else:
        slope = (Q[1] - P[1]) * pow(Q[0] - P[0], -1, p)       # secant
    x = (slope ** 2 - P[0] - Q[0]) % p
    return (x, (slope * (P[0] - x) - P[1]) % p)

def multiply(k, P):
    R = None
    while k:
        if k & 1:
            R = add(R, P)
        P, k = add(P, P), k >> 1
    return R

G = (3, 12)
print("G on the curve:", on_curve(G))
print("2G =", multiply(2, G), "| 13G =", multiply(13, G))
print("13G = 8G + 4G + G:", multiply(13, G) == add(add(multiply(8, G), multiply(4, G)), G))
print("101G =", multiply(101, G), "← the order of the group")
G on the curve: True
2G = (64, 80) | 13G = (4, 59)
13G = 8G + 4G + G: True
101G = None ← the order of the group

The group has 101 elements, a prime number: every point (except infinity) generates the whole group, and 101·G comes back to the point at infinity. This number is called the order of the group, written n.

A real key exchange: ECDH on secp256k1

The secp256k1 curve (y² = x³ + 7, over a 256-bit p) is Bitcoin's curve. The ECDH key exchange follows Diffie-Hellman exactly: each side chooses a secret k, publishes k·G, and multiplies the point received by its secret.

import hashlib

p = 2**256 - 2**32 - 977
a, b = 0, 7
n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
     0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)

def add(P, Q):
    if P is None: return Q
    if Q is None: return P
    if P[0] == Q[0] and (P[1] + Q[1]) % p == 0: return None
    if P == Q: slope = (3 * P[0] ** 2 + a) * pow(2 * P[1], -1, p)
    else: slope = (Q[1] - P[1]) * pow(Q[0] - P[0], -1, p)
    x = (slope ** 2 - P[0] - Q[0]) % p
    return (x, (slope * (P[0] - x) - P[1]) % p)

def multiply(k, P):
    R = None
    while k:
        if k & 1: R = add(R, P)
        P, k = add(P, P), k >> 1
    return R

print("G on the curve :", (G[1] ** 2 - G[0] ** 3 - 7) % p == 0)
print("n·G = infinity :", multiply(n, G) is None)

k_awa = 0x8F3A2C11D5E64B7A9C0D1E2F3A4B5C6D7E8F90A1B2C3D4E5F60718293A4B5C6D   # for real: secrets.randbelow(n)
k_kofi = 0x1C2D3E4F5A6B7C8D9E0F1A2B3C4D5E6F708192A3B4C5D6E7F8091A2B3C4D5E6F
A, B = multiply(k_awa, G), multiply(k_kofi, G)           # public keys exchanged
S1, S2 = multiply(k_awa, B), multiply(k_kofi, A)
print("same shared point:", S1 == S2)
print("derived key:", hashlib.sha256(S1[0].to_bytes(32, "big")).hexdigest()[:32], "…")
G on the curve : True
n·G = infinity : True
same shared point: True
derived key: 7607571797cb757c8ec65d2da615f988 …

A public key takes 33 bytes in compressed form (the x coordinate and one bit for the sign of y), against 384 for RSA-3072. Our code is deliberately naive: it is not constant-time, and a real library uses formulas and coordinates chosen for speed and leak resistance. In production, use X25519 for key exchange and Ed25519 for signatures.

Mini-lab: the cloud of pointsPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: point compression

A public key can be sent compressed: only x, plus one bit saying whether y is even. Write compress(P) that returns (x, y % 2) and decompress(x, parity) that recovers y on secp256k1. To compute a square root modulo p, use the fact that p % 4 == 3: then y = (x³ + 7)^((p + 1) / 4) mod p is a square root (if one exists). Check on G and on 2G, and that decompressing an x that is on no point raises an error.

Hint 1
Compute y = pow(x**3 + 7, (p + 1) // 4, p). If y * y % p != (x**3 + 7) % p, there is no point with this x-coordinate.
Hint 2
There are two roots, y and p - y, with opposite parities (since p is odd): choose the one with the right parity.
Show the solution and common mistakes
p = 2**256 - 2**32 - 977
G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
     0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)

def compress(P):
    return P[0], P[1] % 2

def decompress(x, parity):
    square = (x ** 3 + 7) % p
    y = pow(square, (p + 1) // 4, p)
    if y * y % p != square:
        raise ValueError("no point with this x-coordinate: invalid public key")
    return (x, y if y % 2 == parity else p - y)

def double(P):
    slope = 3 * P[0] ** 2 * pow(2 * P[1], -1, p)
    x = (slope ** 2 - 2 * P[0]) % p
    return (x, (slope * (P[0] - x) - P[1]) % p)

for name, P in [("G", G), ("2G", double(G))]:
    print(name, "recovered:", decompress(*compress(P)) == P)
try:
    decompress(5, 0)
except ValueError as e:
    print("x = 5:", e)
G recovered: True
2G recovered: True
x = 5: no point with this x-coordinate: invalid public key

The (p + 1) / 4 formula works because p ≡ 3 (mod 4); for other primes, the Tonelli-Shanks algorithm is used. Decompression is also a validation: an x that matches no point is rejected.

Common mistakes:

  • Forgetting to check that y² = x³ + 7 after the computation: you then build a "point" that is not on the curve, exactly what the invalid-curve attack exploits.
  • Confusing the parity of y with its sign: modulo p, there are no negative numbers, only y and p - y.
  • Using ** without a modulus for the root: (x**3 + 7) ** ((p + 1) // 4) is an astronomically large number.

Summary

  1. 1The points of an elliptic curve modulo p form a group, with the point at infinity as zero.
  2. 2Scalar multiplication is computed by doubling and adding; reversing it is the elliptic-curve discrete logarithm.
  3. 3ECDH follows Diffie-Hellman: each side multiplies the point received by its secret.
  4. 4Every received point must be validated (on the curve, not infinity), otherwise the invalid-curve attack reveals the key.
  5. 5In production: X25519 and Ed25519, through a proven constant-time library.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.