Montgomery ladder and Curve25519
Curve25519 is the most widely used curve today (Signal, WhatsApp, TLS 1.3, SSH, WireGuard). It is not written in Weierstrass, but in Montgomery form:
E: v^2 = u^3 + 486662*u^2 + u (mod p), p = 2^255 - 19
The main advantage of the Montgomery form is that you can work with only the u coordinate of a point — v is not needed at all. For this, the Montgomery ladder is used: for each bit of the scalar, exactly one doubling and one addition are performed. Because of this, the execution time does not depend on the private scalar — which prevents timing side-channel attacks.
Full scheme of the ladder (in projective u/z coordinates):
p, a24 = 2**255 - 19, 121665
def ladder(k, u, bits=255):
x1 = u % p
x2, z2 = 1, 0 # O (cheksizlik)
x3, z3 = x1, 1 # P
swap = 0
for t in range(bits - 1, -1, -1):
kt = (k >> t) & 1
swap ^= kt
if swap:
x2, x3 = x3, x2
z2, z3 = z3, z2
swap = kt
A = (x2 + z2) % p; AA = A*A % p
B = (x2 - z2) % p; BB = B*B % p
E = (AA - BB) % p
C = (x3 + z3) % p; D = (x3 - z3) % p
DA = D*A % p; CB = C*B % p
x3 = (DA + CB)**2 % p
z3 = x1 * ((DA - CB)**2 % p) % p
x2 = AA*BB % p
z2 = E * ((AA + a24*E) % p) % p
if swap:
x2, x3 = x3, x2
z2, z3 = z3, z2
return x2 * pow(z2, p - 2, p) % p
The base point is u = 9. Alice chose a private a and sent uA = ladder(a, 9). Bob's private number b is known to you. Calculate the shared secret — that is, ladder(b, uA).
b = 495874758508641769519505403916167797967757083664913341166349556061315860
u_A = 388392347141488514720443613096768135640654112063929692062232967113577114089
Test vectors to check your code:
ladder(2, 9) = 14847277145635483483963372537557091634710985132825781088887140890597596352251
ladder(3, 9) = 12697861248284385512127539163427099897745340918349830473877503196793995869202
Answer: number only — in decimal format, without spaces and without additional characters (for example 1234).
In real X25519, the scalar is additionally «clamped» (the lower 3 bits are set to zero, the 255th bit to zero, the 254th bit to one) and all values are transmitted in little-endian 32 bytes. In this challenge, these steps have been removed — only the mathematics itself is left.