package com.jscape.util.keystore;

import com.jscape.util.crypto.CryptoServicesProvider;
import com.jscape.util.io.DataCodec;
import com.jscape.util.io.primitive.IntByteArrayCodec;
import com.jscape.util.io.primitive.IntStringCodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.Provider;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;

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

/**
 * @author Alex Usun
 */
public class SshRsaPublicKeyCodec
        implements DataCodec<PublicKey> {

    private final Provider provider;

    public static void writeValue(PublicKey value, OutputStream out)
            throws IOException {
        try {
            RSAPublicKey key = (RSAPublicKey) value;

            IntStringCodec.writeBigEndianValue("ssh-rsa", StandardCharsets.US_ASCII, out);
            IntByteArrayCodec.writeBigEndianValue(key.getPublicExponent().toByteArray(), out);
            IntByteArrayCodec.writeBigEndianValue(key.getModulus().toByteArray(), out);
        } catch (Throwable e) {
            throw ioException(e);
        }
    }

    public static PublicKey readValue(InputStream in, Provider provider)
            throws IOException {
        try {
            String algorithm = IntStringCodec.readBigEndianValue(StandardCharsets.US_ASCII, in);
            assertSupported(algorithm);

            BigInteger exponent = new BigInteger(IntByteArrayCodec.readBigEndianValue(in));
            BigInteger modulus = new BigInteger(IntByteArrayCodec.readBigEndianValue(in));
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);

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

            return factory.generatePublic(keySpec);
        } catch (Throwable e) {
            throw ioException(e);
        }
    }

    private static void assertSupported(String algorithm)
            throws IOException {
        if (!algorithm.equals("ssh-rsa")) {
            throw new IOException("Unsupported algorithm: " + algorithm);
        }
    }

    public static SshRsaPublicKeyCodec defaultCodec() {
        return new SshRsaPublicKeyCodec(null);
    }

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

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

    public void write(PublicKey value, OutputStream out)
            throws IOException {
        writeValue(value, out);
    }

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

}