/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.csr;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;

import org.bouncycastle.operator.ContentVerifierProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;
import org.bouncycastle.pkcs.PKCSException;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;

import com.scytl.products.ov.config.exceptions.ConfigurationEngineException;
import com.scytl.products.ov.config.exceptions.specific.CSRLoaderException;
import com.scytl.products.ov.utils.PemUtils;

public class CSRLoader {

    public JcaPKCS10CertificationRequest getCSRFromPEM(final Path tenantCSRPath) throws ConfigurationEngineException {

        JcaPKCS10CertificationRequest csr = null;
        try {
            csr = PemUtils.csrFromPem(new String(Files.readAllBytes(tenantCSRPath), StandardCharsets.UTF_8));
        } catch (ConfigurationEngineException | IOException e) {
            throw new ConfigurationEngineException("CSR could not be loaded", e);
        }

        PublicKey tenantPublicKey = null;
        try {
            tenantPublicKey = csr.getPublicKey();
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            throw new CSRLoaderException("CSR could not get the public key from the CSR", e);
        }

        try {
            final ContentVerifierProvider verifierProvider =
                new JcaContentVerifierProviderBuilder().build(tenantPublicKey);

            if (!csr.isSignatureValid(verifierProvider)) {
                throw new CSRLoaderException("CSR was tampered and the signature could not be verified");
            }

        } catch (OperatorCreationException | PKCSException e) {
            throw new CSRLoaderException("An error occurred while verifying the signature of the CSR", e);
        }
        return csr;
    }
}
