Mod p elliptic curve addition and scalar multiplication 
Math 302 Cryptography
March 17, 2025

T. Ratliff, Wheaton College
ratliff_thomas@wheatoncollege.edu

A few functions

Addition on the curve E: Y^2 = X^3 + aX + b mod p
Use {0} for the point at infinity
Assumes you’re a good citizen and have checked that p1 and p2 lie on the curve
Note that ecMultiply[ ] implements the double and add algorithm

ecAdd[p1_,p2_,a_,b_,p_]:=Module[{λ,x3,y3},
(* If p1 or p2 {0}== ∞ *)
If[p1 =={0}, Return[p2]];
If[p2=={0}, Return[p1]];

(* Check for additive inverses *)
If[ (p1[[1]] == p2[[1]]) && (Mod[p1[[2]]+p2[[2]],p]==0), Return[{0}]];

(* Otherwise, set λ *) 
If[p1 ==p2,
λ = Mod[ (3p1[[1]]^2 + a)*PowerMod[ 2p1[[2]],-1,p], p],
(*else p1 != p2 *)
λ = Mod[ (p2[[2]]-p1[[2]])*PowerMod[ p2[[1]]-p1[[1]],-1,p], p]
];
x3=Mod[λ^2 - p1[[1]]-p2[[1]],p];
y3=Mod[λ (p1[[1]]-x3)-p1[[2]],p];
Return[{x3,y3}]
];

ecMultiply[n_,p1_,a_,b_,p_]:=Module[{np, bin, k},
np=p1;
bin = IntegerDigits[n,2];

For[k=2, k<= Length[bin], k++,
np=ecAdd[np,np, a, b, p];
If[bin[[k]]==1, 
np=ecAdd[np,p1,a,b,p]
];
];

Return[np]
];

A few examples of using the functions

ecAdd[ {1,5},{4,2},18,6, 23]

ecMultiply[70903,{3,6},2,3,104729]