commit de3a5e60b2aad533b2efe4d43d6487eccda79ad2
parent c129e51d4f27e1cd68d893ca8e5dc5b68339b7d0
Author: Shivakumar <[email protected]>
Date: Sat, 28 Jun 2025 02:15:04 +0530
make keys.py to generate private and public keys
Diffstat:
4 files changed, 70 insertions(+), 2 deletions(-)
diff --git a/ecc/__init__.py b/ecc/__init__.py
@@ -1,7 +1,8 @@
from .field import FieldElement
from .point import Point
from .curve import Curve
+from .keys import generate_keypair, PublicKey, PrivateKey
from .curves.secp256k1 import secp256k1
-__all__ = ["FieldElement", "Point", "Curve", "secp256k1"]
+__all__ = ["FieldElement", "Point", "Curve", "secp256k1", "generate_keypair", "PublicKey", "PrivateKey"]
diff --git a/ecc/field.py b/ecc/field.py
@@ -56,6 +56,7 @@ class FieldElement:
return self.num == other.num and self.prime == other.prime
+
def __rmul__(self, coefficient):
res = (coefficient * self.num) % self.prime
return FieldElement(res, self.prime)
diff --git a/ecc/keys.py b/ecc/keys.py
@@ -0,0 +1,58 @@
+from secrets import randbelow
+from .point import Point
+
+
+class PublicKey:
+ def __init__(self, point: Point, curve):
+ if not isinstance(point, Point):
+ raise TypeError("Public Key must be a Point.")
+
+ self.point = point
+ self.curve = curve
+
+
+ def __repr__(self):
+ return f"PublicKey(\n\tx={hex(self.point.x.num)}, \n\ty={hex(self.point.y.num)}\n)"
+
+
+class PrivateKey:
+ def __init__(self, secret=None, curve=None):
+ if curve is None:
+ raise ValueError("Curve must be specified.")
+
+ self.curve = curve
+
+ if secret is None:
+ self.secret = randbelow(curve.n - 1) + 1
+
+ else:
+ if secret not in range(1, curve.n + 1):
+ raise ValueError(f"PrivateKey must be in between 1 and {curve.n - 1}.")
+
+ self.secret = secret
+
+ self._public_key = None
+
+
+ def public_key(self):
+ if self._public_key is None:
+
+ Gx, Gy = self.curve.G
+ G = Point(Gx, Gy, self.curve)
+ p = self.secret * G
+
+ self._public_key = PublicKey(p, self.curve)
+
+ return self._public_key
+
+
+ def __repr__(self):
+ return f"PrivateKey=({self.secret})"
+
+
+def generate_keypair(curve):
+ """Generates a (private_key, public_key) pair for a given curve. """
+ private_key = PrivateKey(curve=curve)
+ public_key = private_key.public_key()
+
+ return private_key, public_key
diff --git a/ecc/point.py b/ecc/point.py
@@ -47,7 +47,15 @@ from .field import FieldElement
class Point:
- def __init__(self, x, y, curve):
+ """
+ Point(x, y, curve) is a point (x, y) on the 'curve'.
+
+ Arguments:
+ x, y : (x, y) on the curve over the Field E(Z/pZ)
+ curve : Elliptic curve over the Field E(Z/pZ)
+
+ """
+ def __init__(self, x: int, y: int, curve):
self.curve = curve
self.prime = curve.P