package com.nintendo.ecqv;

import com.nintendo.hsminterfaces.RandomInterface;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.math.ec.ECPoint;
import java.math.BigInteger;

public class CertificateAuthority {
    private ECParameterSpec m_EcParams;
    private RandomInterface m_Random;

    // CA key pair
    // This is the Nintendo COMMON (PUBLIC, PRIVATE) KEY PAIR
    private BigInteger      m_PrivateKey;
    private ECPoint         m_PublicKey;

    // Delta key pair
    private BigInteger      m_d;
    private ECPoint         m_D;

    private boolean         m_isUsePointCompression;

    public CertificateAuthority(RandomInterface   randomGenerator,
                                ECParameterSpec   ecParams,
                                KeyPair           caKeyPair,
                                boolean           isUsePointCompression)
    {
        m_Random    = randomGenerator;
        m_EcParams  = ecParams;
        m_isUsePointCompression = isUsePointCompression;

        // Retrieve a public/private key pair for the CA
        m_PrivateKey = caKeyPair.GetPrivateKey();
        m_PublicKey  = caKeyPair.GetPublicKey();

        // Generate a delta key pair for
        // https://tools.ietf.org/html/draft-jivsov-ecc-compact-05
        // 4.2.3.  The key generation algorithm for the sum of points
        KeyPair keyPair = KeyPair.GenerateKeyPair(m_Random, m_EcParams);
        m_d             = keyPair.GetPrivateKey();
        m_D             = keyPair.GetPublicKey();
    }

    public Certificate GenerateCertificate(ECPoint Ru)
    {
        // Generate a new EC key pair
        KeyPair    keyPair = KeyPair.GenerateKeyPair(m_Random, m_EcParams);
        BigInteger k       = keyPair.GetPrivateKey();
        ECPoint    kG      = keyPair.GetPublicKey();

        // Pu = Ru + kG (or gamma = alpha*G + kG)
        ECPoint Pu = Ru.add(kG);
        assert(Pu.isValid() );

        // Fix Pu so it is compliant with y = min(y, p-y)
        // https://tools.ietf.org/html/draft-jivsov-ecc-compact-05
        // 4.2.3.  The key generation algorithm for the sum of points
        if (m_isUsePointCompression)
        {
            BigInteger PuY, pMinusY, minimum;

            Pu      = Pu.normalize(); // Normalize the point before getting its affine coordinates
            PuY     = Pu.getYCoord().toBigInteger();
            pMinusY = m_EcParams.getCurve().getField().getCharacteristic().subtract(PuY);
            minimum = PuY.min(pMinusY);

            while (minimum.compareTo(PuY) != 0)
            {
                Pu = Pu.add(m_D);
                assert(Pu.isValid() );
                k = k.add(m_d).mod(m_EcParams.getN() );

                Pu      = Pu.normalize(); // Normalize the point before getting its affine coordinates
                PuY     = Pu.getYCoord().toBigInteger();
                pMinusY = m_EcParams.getCurve().getField().getCharacteristic().subtract(PuY);
                minimum = PuY.min(pMinusY);
            }
        }

        // Compute CertU and its integer hash e (we skip the encoding part which uses IDa)
        BigInteger e = Hash.PointToIntegerHash(Pu, m_EcParams.getN() );

        // Check t is not the identity element
        // t = ePu + Qca
        ECPoint ePu = Pu.multiply(e);
        ECPoint t   = ePu.add(m_PublicKey);

        // TODO: go back to GenKeyPair(k, &kG) if t is the identity element
        assert(!t.isInfinity() );

        // Compute private key reconstruction data "r"
        // r = ek + dca (mod n), (a = e*alpha + s)
        // This step is not mandatory
        BigInteger ek = e.multiply(k).mod(m_EcParams.getN() );
        BigInteger r  = ek.add(m_PrivateKey).mod(m_EcParams.getN() );

        return new Certificate(Pu, r, m_isUsePointCompression);
    }

    public ECPoint GetPublicKey()
    {
        return m_PublicKey;
    }
}
