Feb 26, 2025

ECC Point Addition

Calculate the slope for two given coordinates and calculate the next point.

Source Code

import java.util.Scanner;

class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class ECCPointAddition {
    public static Point addPoints(Point P, Point Q) {
        // Example curve parameters (for simplicity)
        int p = 17; // prime number for the field
        int a = 2;  // curve parameter
        int b = 2;  // curve parameter

        if (P.x == Q.x && P.y == Q.y) {
            // Point doubling
            int m = (3 * P.x * P.x + a) * modInverse(2 * P.y, p) % p;
            int xR = (m * m - 2 * P.x) % p;
            int yR = (m * (P.x - xR) - P.y) % p;
            return new Point(xR, yR);
        } else {
            // Point addition
            int m = (Q.y - P.y) * modInverse(Q.x - P.x, p) % p;
            int xR = (m * m - P.x - Q.x) % p;
            int yR = (m * (P.x - xR) - P.y) % p;
            return new Point(xR, yR);
        }
    }

    private static int modInverse(int a, int p) {
        a = a % p;
        for (int x = 1; x < p; x++) {
            if ((a * x) % p == 1) {
                return x;
            }
        }
        return 1; // Should not reach here
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter coordinates of Point P (x y): ");
        Point P = new Point(scanner.nextInt(), scanner.nextInt());
        System.out.print("Enter coordinates of Point Q (x y): ");
        Point Q = new Point(scanner.nextInt(), scanner.nextInt());

        Point R = addPoints(P, Q);
        System.out.println("Resulting Point R: (" + R.x + ", " + R.y + ")");
    }
}

Output

Enter coordinates of Point P (x y): 2 3
Enter coordinates of Point Q (x y): 5 4
Resulting Point R: (12, -12)