Skip to content

Instantly share code, notes, and snippets.

@markburns
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markburns/0ab7036c27aa7a5a2e4c to your computer and use it in GitHub Desktop.
Save markburns/0ab7036c27aa7a5a2e4c to your computer and use it in GitHub Desktop.
package ec
import (
big "math/big"
)
type Point struct {
X *big.Int
Y *big.Int
}
//x^2 + y^2 == 1 + dx^2y^2
type Curve struct {
MaxPrime *big.Int
D *big.Int
}
// https://www.youtube.com/watch?v=l6jTFxQaUJA
func (c *Curve) Add(a, b *Point) *Point {
x1, y1 := a.X, a.Y
x2, y2 := b.X, b.Y
x3 := c.x3(x1, x2, y1, y2)
y3 := c.y3(x1, x2, y1, y2)
return &Point{X: x3, Y: y3}
}
func (c *Curve) x3(x1, x2, y1, y2 *big.Int) *big.Int {
numerator := c.xNumerator(x1, x2, y1, y2)
denominator := c.xDenominator(x1, x2, y1, y2)
x3 := numerator.Div(numerator, denominator)
return x3.Mod(x3, c.MaxPrime)
}
func (c *Curve) y3(x1, x2, y1, y2 *big.Int) *big.Int {
numerator := c.yNumerator(x1, x2, y1, y2)
denominator := c.yDenominator(x1, x2, y1, y2)
y3 := numerator.Div(numerator, denominator)
return y3.Mod(y3, c.MaxPrime)
}
//calculates (x1 * y2 + y1 * x2) % MaxPrime
func (c *Curve) xNumerator(x1, x2, y1, y2 *big.Int) *big.Int {
calc := big.NewInt(0)
r := calc.Mul(x1, y2)
calc.Add(r, calc.Mul(y1, x2))
return r.Mod(r, c.MaxPrime)
}
// 1 * d * x1 * x2 * y1 * y2
func (c *Curve) xDenominator(x1, x2, y1, y2 *big.Int) *big.Int {
r := big.NewInt(1)
r.Add(r, c.denominatorComponent(x1, x2, y1, y2))
return r.Mod(r, c.MaxPrime)
}
// y1 * y2 - x1 * x2
func (c *Curve) yNumerator(x1, x2, y1, y2 *big.Int) *big.Int {
calc := big.NewInt(0)
r := calc.Mul(y1, y2)
calc.Sub(r, calc.Mul(x1, x2))
return r.Mod(r, c.MaxPrime)
}
// 1- d*x1*x2*y1*y2
func (c *Curve) yDenominator(x1, x2, y1, y2 *big.Int) *big.Int {
r := big.NewInt(1)
r.Add(r, c.denominatorComponent(x1, x2, y1, y2))
return r.Mod(r, c.MaxPrime)
}
//calculates d*x1*x2*y1*y2
func (c *Curve) denominatorComponent(x1, x2, y1, y2 *big.Int) *big.Int {
r := big.NewInt(0)
r.Mul(c.D, x1).Mul(r, x2).Mul(r, y1).Mul(r, y2)
return r.Mod(r, c.MaxPrime)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment