Danger

Nothing here should be used for any security purposes.

  • If you need cryptographic tools in a Python environment use pyca.

  • If you need efficient and reliable abstract math utilities in a Python-like environment consider using SageMath.

Elliptic curves

This module is imported with:

import toy_crypto.ec

I wrote this for the sole purposes of

  1. Providing a working context to illustrate the double-and-add algorithm in the Point.scaler_multiply() method.

  2. Doing calculations over floats that I could use for diagrams. (That code has been removed.)

from toy_crypto.ec import Curve
from toy_crypto.nt import Modulus


# Example curve from Serious Cryptography

curve = Curve(-4, 0, 191)
assert str(curve) == "y^2 = x^3 - 4x + 0 (mod 191)"

# set a generator (base-point), G
G = curve.point(146, 131)

assert G.on_curve() is True

five_G = G.scaler_multiply(5)
assert five_G.x == 61
assert five_G.y == 163

The ec classes

class toy_crypto.ec.Curve(a: int, b: int, p: int)

Define a curve of the form \(y^2 = x^3 + ax + b \pmod p\).

Parameters:
property PAI: Point

Point At Infinity: the additive identity.

property a: int

The ‘a’ of \(y^2 = x^3 + ax + b \pmod p\).

property b: int

The ‘b’ of \(y^2 = x^3 + ax + b \pmod p\).

compute_y(x: int) tuple[int, int] | None

Returns pair of y values for x on curve. None otherwise.

Parameters:

x (int)

Return type:

tuple[int, int] | None

property order: int

The order of the group.

property p: Modulus

The ‘p’ of \(y^2 = x^3 + ax + b \pmod p\).

class toy_crypto.ec.Point(x: int, y: int, curve: Curve)

Point on elliptic curve over finite field.

Create a mutable point on a curve.

Parameters:
add(Q: Self) Self

Add points.

Parameters:
Returns:

Sum of Q and self

Return type:

Point

cp() Self

Return a mutable copy

Parameters:

self (Self)

Return type:

Self

double() Self

Returns self + self

Parameters:

self (Self)

Return type:

Self

iadd(Q: Self) Self

add point to self in place.

The Point at Infinity is not mutable. But you can make a mutable copy with curve.PAI.cp(). Or you could just use Point.add().

Raises:
Parameters:
Return type:

Self

idouble() Self

Double point in place.

The Point at Infinity is not mutable. But you can make a mutable copy with curve.PAI.cp() or just use Point.double().

Raises:

NotImplementedError – if self is not a mutable point.

Return type:

Self

property is_zero: bool

True if point at infinity

neg() Self

Return additive inverse.

Returns:

Additive inverse

Return type:

Point

Parameters:

self (Self)

on_curve() bool

True if point is on the curve (including point at infinity).

Return type:

bool

scaler_multiply(n: int) Point

Returns n * self.

Warning:

This algorithm exposes n to timing attacks.

Parameters:

n (int)

Return type:

Point