package com.nintendo.ecqv;

import org.bouncycastle.math.ec.ECPoint;
import java.math.BigInteger;

public class Certificate {
    // Certificate is the same size of a curve point (x, y) = 2 * sizeof(FieldElement) = 256 bits
    // Using point compression, only x is needed (y will be computed) = 128 bits
    // A 256 bits public key suitable for decipher can be extracted from this certificate
    public ECPoint    m_certificate;

    // r is the private key contribution data and it is not mandatory
    // It can be used to check that a public key extracted from a certificate is valid
    // We should discard it and not store it on the Amiibo
    public BigInteger m_r;

    // When point compression is used. Y coordinate is ignored from the m_certificate point
    public boolean    m_isPointCompression;

    public Certificate(ECPoint certificate, BigInteger r, boolean isPointCompression)
    {
        m_certificate        = certificate;
        m_r                  = r;
        m_isPointCompression = isPointCompression;
    }

    public byte[] GetCertificateAsBytes()
    {
        byte[] out = null;
        if (m_isPointCompression)
            out = m_certificate.getXCoord().getEncoded();
        else
            out = Hash.PointToOctetString(m_certificate);

        assert(out.length == GetCertificateSize() );

        return out;
    }

    public int GetCertificateSize()
    {
        int fieldElementSizeInBits  = m_certificate.getXCoord().getFieldSize();
        assert((fieldElementSizeInBits & 1) == 0);

        int fieldElementSizeInBytes = fieldElementSizeInBits / 8;
        int certificateSizeInBytes  = m_isPointCompression ? fieldElementSizeInBytes : 2 * fieldElementSizeInBytes;

        return certificateSizeInBytes;
    }

    public ECPoint GetCertificatePoint()
    {
        return m_certificate;
    }

    public BigInteger GetR()
    {
        return m_r;
    }
}
