package com.nintendo.ecqv;

import java.math.BigInteger;
import org.bouncycastle.jce.spec.ECParameterSpec;

public class ECMath {
    // Computes y^2 = x^3 + ax + b
    // Then y = Sqrt(y^2)
    // Sqrt(n) = y^((p + 1) / 4) only if: p mod 4 = 3
    public static BigInteger ComputeY(BigInteger x, ECParameterSpec c)
    {
        BigInteger p = c.getCurve().getField().getCharacteristic();
        BigInteger a = c.getCurve().getA().toBigInteger();
        BigInteger b = c.getCurve().getB().toBigInteger();

        // t2 <- x^3
        BigInteger t2 = x.modPow(new BigInteger("3"), p);

        // t <- a * x
        BigInteger t = a.multiply(x).mod(p);

        // t2 <- x^3 + a * x + b
        t2 = t2.add(t).add(b).mod(p);

        // Square root when p mod 4 = 3
        // y <- y2^((p + 1) / 4)
        BigInteger exponent = p.add(BigInteger.ONE).divide(new BigInteger("4")).mod(p);
        BigInteger y = t2.modPow(exponent, p);

        // y = min(y',p-y')
        BigInteger pMinusY = p.subtract(y).mod(p);
        y = y.min(pMinusY);

        return y;
    }
}
