package com.nintendo.ecqv;

import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.math.ec.ECPoint;

import java.math.BigInteger;

public class Hash {
    static final int POINT_STRING_LEN = 32; // 32 bytes (16 per coordinate)
    static final int HASH_LENGTH      = 32; // Sha256

    public static byte[] GetHash(byte[] data, int dataLength)
    {
        SHA256Digest digest = new SHA256Digest();
        digest.update(data, 0, dataLength);

        byte[] out = new byte[HASH_LENGTH];
        digest.doFinal(out, 0);
        return out;
    }

    public static BigInteger HashToInteger(byte[] data, BigInteger divider)
    {
        return new BigInteger(data).mod(divider);
    }

    public static byte[] PointToOctetString(ECPoint point)
    {
        byte[] x = point.getXCoord().getEncoded();
        byte[] y = point.getYCoord().getEncoded();

        byte[] out = new byte[POINT_STRING_LEN];
        for (int i = 0; i < POINT_STRING_LEN / 2; i++)
            out[i] = x[i];

        for (int i = 0; i < POINT_STRING_LEN / 2; i++)
            out[i + POINT_STRING_LEN / 2] = y[i];

        return out;
    }

    public static BigInteger PointToIntegerHash(ECPoint point, BigInteger divider)
    {
        byte[] puString = PointToOctetString(point);
        byte[] hash     = GetHash(puString, POINT_STRING_LEN);

        return HashToInteger(hash, divider);
    }
}
