ecc

Elliptic Curve Cryptograpy library from scratch in python.
Log | Files | Refs | README | LICENSE

commit 9837568594060afab2f93c10402211feff05be24
parent aa52146f8d3ee7de3e9c856093de7a0bc3ced28d
Author: Shivakumar <[email protected]>
Date:   Sat,  2 Aug 2025 01:59:21 +0530

format using ruff

Diffstat:
Mecc/__init__.py | 15+++++++++++++--
Mecc/curve.py | 29+++++++++++++++++++----------
Mecc/curves/secp256k1.py | 2+-
Mecc/field.py | 17++---------------
Mecc/point.py | 15+--------------
Mtests/test_curve.py | 10++++++----
Mtests/test_ecdsa.py | 89++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mtests/test_field.py | 4++--
Mtests/test_point.py | 38+++++++++++++++++++-------------------
9 files changed, 129 insertions(+), 90 deletions(-)

diff --git a/ecc/__init__.py b/ecc/__init__.py @@ -2,8 +2,19 @@ from .field import FieldElement from .point import Point from .curve import Curve from .keys import generate_keypair, PublicKey, PrivateKey -from .ecdsa import Signature, sign, verify +from .ecdsa import Signature from .curves.secp256k1 import secp256k1 -__all__ = ["FieldElement", "Point", "Curve", "secp256k1", "generate_keypair", "PublicKey", "PrivateKey", "Signature", "sign", "verify"] +__all__ = [ + "FieldElement", + "Point", + "Curve", + "secp256k1", + "generate_keypair", + "PublicKey", + "PrivateKey", + "Signature", + "sign", + "verify", +] diff --git a/ecc/curve.py b/ecc/curve.py @@ -9,9 +9,20 @@ from functools import cached_property from .field import FieldElement from .point import Point + class Curve: """Represents an elliptic curve y² = x³ + ax + b over a finite field Fp or E(Z/pZ).""" - def __init__(self, a: int, b: int, P: int, G: tuple[int, int], n: int, h: int = 1, name: str = None): + + def __init__( + self, + a: int, + b: int, + P: int, + G: tuple[int, int], + n: int, + h: int = 1, + name: str = None, + ): """ parameters: a, b : Curve parameters (y^2 = x^3 + ax + b). @@ -40,11 +51,7 @@ class Curve: @cached_property def G(self) -> Point: - return Point( - x = self._G[0], - y = self._G[1], - curve = self - ) + return Point(x=self._G[0], y=self._G[1], curve=self) def __repr__(self) -> str: if self.name: @@ -55,7 +62,9 @@ class Curve: if not isinstance(other, Curve): return NotImplemented - return (self.P == other.P and - self.a == other.a and - self.b == other.b and - self._G == other._G) + return ( + self.P == other.P + and self.a == other.a + and self.b == other.b + and self._G == other._G + ) diff --git a/ecc/curves/secp256k1.py b/ecc/curves/secp256k1.py @@ -8,7 +8,7 @@ prime = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F G = ( 55066263022277343669578718895168534326250603453777594175500187360389116729240, - 32670510020758816978083085130507043184471273380659243275938904335757337482424 + 32670510020758816978083085130507043184471273380659243275938904335757337482424, ) n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 diff --git a/ecc/field.py b/ecc/field.py @@ -2,26 +2,13 @@ This module provides a class to represent elements in a finite field E(Z/pZ). It overloads standard arithmetic operators (+, -, *, /, **). -Definition of Field E(Z/pZ) for the elliptic curve : y^2 = x^3 + ax + b +Definition of Field E(Z/pZ) for the elliptic curve : y² = x³ + ax + b The Group operation for the curve are under the Field E(Z/pZ). The operations like : - Addition (+) - Multiplication (*) - Subtraction (-) - -For the operation : - Power (^) - -We use the Fermat's Little Theorem. As we have to compute a^k for all -a and k are integers. We know that a^(p-1) = 1 (mod p) for all p = prime. -Then : - a^m(p-1) = 1 (mod p) - -Let k be some integer such that k = q(p-1) + r. - - a^k = a^(q(p-1) + r) (mod p) - a^k = (a^(p-1))^q * a^r (mod p) - a^k = a^r (mod p) - a^k = a^(k mod p-1) (mod p) + - Power (^) """ from __future__ import annotations diff --git a/ecc/point.py b/ecc/point.py @@ -5,7 +5,7 @@ It includes the implementation of elliptic curve group operations such as point addition and constant-time scalar multiplication using a Montgomery Ladder to protect against side-channel attacks. -Definition of Point on the curve : y^2 = x^3 + ax + b +Definition of Point on the curve : y² = x³ + ax + b Group operation for the elliptic curve. The operations are: @@ -54,24 +54,11 @@ class Point: Such that : P + Q = R - So, we find the slope of the line passing through P & Q. - - s = (yp - yq)/(xp - xq) - xr = s^2 - (xp + xq) - yr = s(xp - xr) - yp - But, if P and Q are the same point, then we have to find 2P. To find 2P, we have to find the slope of the tangent at the point P, we can do that by finding the derivative of the curve. 2P = P + P - - So, the derivative of the curve would be - - s = (3xp + a)/2yp - xr = s^2 - 2xp - yr = s(xp - xr) - yp - """ if self.curve != other.curve: raise TypeError("Points are not on the same curve.") diff --git a/tests/test_curve.py b/tests/test_curve.py @@ -3,6 +3,7 @@ from ecc import Curve, Point curve = Curve(P=17, a=2, b=2, G=(5, 1), n=19, h=1, name="toy_curve") + class TestCurve: """Tests the functionality of the Curve class.""" @@ -16,7 +17,7 @@ class TestCurve: def test_repr(self): """Test the __repr__ method for a clean representation.""" assert repr(curve) == "Curve(toy_curve)" - + # Test representation for a curve without a name unnamed_curve = Curve(P=17, a=2, b=2, G=(5, 1), n=19) assert repr(unnamed_curve) == "Curve(y² = x³ + 2x + 2 mod 17)" @@ -26,8 +27,8 @@ class TestCurve: curve1 = Curve(P=17, a=2, b=2, G=(5, 1), n=19) curve2 = Curve(P=17, a=2, b=2, G=(5, 1), n=19) assert curve1 == curve2 - - curve3 = Curve(P=19, a=2, b=2, G=(5, 1), n=19) # Different prime + + curve3 = Curve(P=19, a=2, b=2, G=(5, 1), n=19) assert curve1 != curve3 def test_generator_property(self): @@ -38,7 +39,8 @@ class TestCurve: assert G.curve == curve G2 = curve.G - assert id(G) == id(G2) + assert id(G) == id(G2) + class TestCurveErrors: """Tests the error handling of the Curve class.""" diff --git a/tests/test_ecdsa.py b/tests/test_ecdsa.py @@ -1,36 +1,79 @@ -from ecc import secp256k1 -from ecc import generate_keypair -from ecc import sign, verify, Signature +from hypothesis import given, strategies as st +from ecc.curves import secp256k1 +from ecc import PrivateKey, Signature, generate_keypair +# --- Official RFC 6979 Test Vector for secp256k1 --- +# Source: RFC 6979, Appendix A.2.5 +KAT_D = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 +KAT_MSG = b"sample" +KAT_R = 0x432310E32CB80EB6503A26CE83CC165C783B870845FB8AAD6D970889FCD7A6C8 +KAT_S = 0x530128B6B81C548874A6305D93ED071CA6E05074D85863D4056CE89B02BFAB69 -def test_sign_and_verify(): - priv, pub = generate_keypair(secp256k1) - message = b"Hello, World" - sig = sign(message, priv) - assert isinstance(sig, Signature) - assert verify(message, sig, pub) +class TestECDSACorrectness: + """Verifies the ECDSA implementation against the official RFC 6979 standard.""" + def test_known_answer_vector_rfc6979(self): + """ + Tests the implementation against the official test vector from + RFC 6979, Appendix A.2.5. This is the gold standard for correctness. + """ + private_key = PrivateKey(secret=KAT_D, curve=secp256k1) + public_key = private_key.public_key -def test_sign_with_different_priv(): - priv1, _ = generate_keypair(secp256k1) - priv2, _ = generate_keypair(secp256k1) + # 1. Test Signature Generation + signature = private_key.sign(KAT_MSG) + assert signature.r == KAT_R, ( + "The 'r' component does not match the official RFC 6979 vector." + ) + assert signature.s == KAT_S, ( + "The 's' component does not match the official RFC 6979 vector." + ) - message = b"test, :)" - sig1 = sign(message, priv1) - sig2 = sign(message, priv2) + # 2. Test Signature Verification + assert public_key.verify(KAT_MSG, signature) is True, ( + "A valid known signature failed to verify." + ) - assert sig1.r != sig2.r or sig1.s != sig2.s +class TestECDSASecurity: + """Tests for fundamental security properties.""" -def test_sign_with_different_pub(): - priv1, pub1 = generate_keypair(secp256k1) - priv2, pub2 = generate_keypair(secp256k1) + def test_sign_produces_low_s_signature(self): + """The sign function must enforce a low-s value to prevent malleability.""" + private_key = PrivateKey(curve=secp256k1) + signature = private_key.sign(b"test for low-s") + assert signature.s <= secp256k1.n // 2 - message = b"test, :D" - sig = sign(message, priv1) + def test_verify_accepts_high_s_signature(self): + """The verify function must accept a mathematically valid high-s signature.""" + priv, pub = generate_keypair(secp256k1) + message = b"test for malleability" + low_s_signature = priv.sign(message) - assert verify(message, sig, pub1) - assert not verify(message, sig, pub2) + high_s = secp256k1.n - low_s_signature.s + malleated_signature = Signature(r=low_s_signature.r, s=high_s) + assert pub.verify(message, malleated_signature) is True + +# --- Property-Based Testing --- + +private_keys = st.builds(PrivateKey, curve=st.just(secp256k1)) +messages = st.binary(min_size=1, max_size=256) + + +@given(private_key=private_keys, message=messages) +def test_sign_verify_property(private_key, message): + """Property: Any message signed by a key must be verifiable by its public key.""" + public_key = private_key.public_key + signature = private_key.sign(message) + assert public_key.verify(message, signature) is True + + +@given(private_key=private_keys, message=messages) +def test_deterministic_signature_property(private_key, message): + """Property: Signing the same message twice must produce the exact same signature.""" + sig1 = private_key.sign(message) + sig2 = private_key.sign(message) + assert sig1 == sig2 diff --git a/tests/test_field.py b/tests/test_field.py @@ -20,13 +20,13 @@ class TestFieldElementErrors: with pytest.raises( TypeError, match="Cannot operate on FieldElements from different fields." ): - c = a + b + a + b def test_division_by_zero(self): a = FieldElement(7, 13) b = FieldElement(0, 13) with pytest.raises((ValueError, ZeroDivisionError)): - c = a / b + a / b # --- Testing Edge Cases and Reflected Operations --- diff --git a/tests/test_point.py b/tests/test_point.py @@ -14,7 +14,7 @@ Gx, Gy = (5, 1) # A global curve object for our tests curve = Curve(P=P, a=A, b=B, G=(Gx, Gy), n=N) G = Point(Gx, Gy, curve) -I = Point(None, None, curve) +identity = Point(None, None, curve) # --- Testing for Expected Errors --- @@ -27,14 +27,14 @@ class TestPointErrors: def test_add_points_on_different_curves(self): """Adding points from different curves should raise a TypeError.""" p1 = G - p2 = Point(secp256k1.G[0], secp256k1.G[1], secp256k1) + p2 = secp256k1.G with pytest.raises(TypeError, match="Points are not on the same curve"): p1 + p2 def test_rmul_by_non_integer(self): """Scalar multiplication requires an integer scalar.""" with pytest.raises(TypeError, match="Scalar must be an integer"): - p = 2.5 * G + 2.5 * G # --- Testing Edge Cases and Core Operations --- @@ -51,13 +51,13 @@ class TestPointOperations: def test_identity_element(self): """Test that adding the point at infinity is an identity operation.""" - assert G + I == G - assert I + G == G + assert G + identity == G + assert identity + G == G def test_additive_inverse(self): """Test that adding a point to its inverse results in infinity.""" p_inv = Point(G.x.num, -G.y.num, curve) - assert G + p_inv == I + assert G + p_inv == identity # --- Property-Based Testing (with Hypothesis) --- @@ -68,8 +68,8 @@ points = st.integers(min_value=1, max_value=N - 1).map(lambda k: k * G) @given(P=points) def test_identity_property(P): """Property: P + O = P (where O is the identity/infinity point).""" - assert P + I == P - assert I + P == P + assert P + identity == P + assert identity + P == P @given(P=points) @@ -77,22 +77,22 @@ def test_inverse_property(P): """Property: P + (-P) = O.""" if P.y is not None: P_inv = Point(P.x.num, -P.y.num, curve) - assert P + P_inv == I + assert P + P_inv == identity -@given(k=integers, l=integers) -def test_scalar_distributivity(k, l): - """Property: (k + l) * P = k*P + l*P.""" - p1 = (k + l) * G - p2 = (k * G) + (l * G) +@given(k1=integers, k2=integers) +def test_scalar_distributivity(k1, k2): + """Property: (k1 + k2) * P = k1*P + k2*P.""" + p1 = ((k1 + k2) % N) * G + p2 = (k1 * G) + (k2 * G) assert p1 == p2 -@given(k=integers, l=integers) -def test_scalar_associativity(k, l): - """Property: k * (l * P) = (k * l) * P.""" - p1 = k * (l * G) - p2 = ((k * l) % N) * G # modulo N +@given(k1=integers, k2=integers) +def test_scalar_associativity(k1, k2): + """Property: k1 * (k2 * P) = (k1 * k2) * P.""" + p1 = k1 * (k2 * G) + p2 = ((k1 * k2) % N) * G assert p1 == p2