Search code examples
gocryptographyecdsamodular-arithmetic

How to calculate `x^3 + ax + b mod p` with Golang big.Int


I'm trying to find the Y coordinate for an elliptic point. I understand the formula is y^2≡x^3+ax+b mod p.

However I'm unsure of how I would actually program this in Go.

xCubed.Exp(X, 3, nil)
AX.Mul(A,X)

N.Add(XPow3, AX) // x^3 + ax
N.Mod(N, P) // mod p
N.Add(N, B) // (x^3 + ax) + b
N.Mod(N, P) // mod p

return N

Where xCubed,X,N,P,B are *big.Int and N represents y^2

I'm a noob to modular arithmetic, so my assumption mod P is applied to each operation; Is this the correct way to to calculate x^3 + ax + b mod p?

edit: should I have added AX.Mod(p) ?


Solution

  • I figured it out, by scouting some code in the elliptic lib

    func GetY(x *big.Int, curve *elliptic.CurveParams) *big.Int {
    
    
        x3 := new(big.Int).Mul(x, x)
        x3.Mul(x3, x)
    
        threeX := new(big.Int).Lsh(x, 1)
        threeX.Add(threeX, x)
    
        x3.Sub(x3, threeX)
        x3.Add(x3, curve.B)
        x3.Mod(x3, curve.P)
    
        return x3.ModSqrt(x3, curve.P)
    }