package com.jscape.util.keystore;

import com.jscape.util.IOTools;
import com.jscape.util.crypto.CryptoServicesProvider;
import com.jscape.util.io.DataCodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.Provider;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;

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

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

    private final Provider provider;

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

        try {
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(data);

            KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider) : KeyFactory.getInstance("RSA");
            RSAPrivateKey privateKey = (RSAPrivateKey) factory.generatePrivate(spec);

            RSAPrivateCrtKeySpec privateKeySpec = factory.getKeySpec(privateKey, RSAPrivateCrtKeySpec.class);
            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privateKey.getModulus(), privateKeySpec.getPublicExponent());
            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 Pkcs8RsaKeyPairCodec defaultCodec() {
        return new Pkcs8RsaKeyPairCodec(null);
    }

    public static Pkcs8RsaKeyPairCodec bcCodec() {
        return new Pkcs8RsaKeyPairCodec(CryptoServicesProvider.instance());
    }

    public Pkcs8RsaKeyPairCodec(Provider provider) {
        this.provider = provider;
    }

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

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