package com.jscape.util.keystore;

import com.jscape.util.IOTools;
import com.jscape.util.crypto.CryptoServicesProvider;
import com.jscape.util.io.DataCodec;
import org.bouncycastle.jce.interfaces.ECPrivateKey;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;

import static com.jscape.util.ExceptionTools.ioException;

/**
 * @author Alex Usun
 */
public class Pkcs8EcKeyPairCodec
        implements DataCodec<KeyPair> {

    public static KeyPair readValue(InputStream in)
            throws IOException {
        byte[] data = IOTools.readFully(in);

        try {
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(data);

            KeyFactory factory = KeyFactory.getInstance("EC", CryptoServicesProvider.instance());
            ECPrivateKey privateKey = (ECPrivateKey) factory.generatePrivate(spec);

            ECPrivateKeySpec privateKeySpec = factory.getKeySpec(privateKey, ECPrivateKeySpec.class);
            ECParameterSpec params = privateKeySpec.getParams();
            ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(params.getG().multiply((privateKey.getD())), params);
            PublicKey publicKey = factory.generatePublic(publicKeySpec);

            return new KeyPair(publicKey, privateKey);
        } catch (Exception e) {
            throw ioException(e);
        }
    }

    public static void writeValue(KeyPair value, OutputStream out)
            throws IOException {
        try {
            byte[] bytes = value.getPrivate().getEncoded();
            out.write(bytes);
        } catch (Exception e) {
            throw ioException(e);
        }
    }

    public static Pkcs8EcKeyPairCodec defaultCodec() {
        return new Pkcs8EcKeyPairCodec();
    }

    @Override
    public KeyPair read(InputStream in)
            throws IOException {
        return readValue(in);
    }

    @Override
    public void write(KeyPair value, OutputStream out)
            throws IOException {
        writeValue(value, out);
    }
}
