/*
 * 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.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.certificates.cryptoapi.CryptoAPIX509Certificate;
import com.scytl.cryptolib.certificates.factory.CryptoX509Certificate;

/**
 * Reads a X.509 certificate from a file in a pem format.
 */
public class X509CertificateLoader {

    public CryptoAPIX509Certificate load(final String fileName)
            throws GeneralSecurityException, GeneralCryptoLibException, IOException {
        try(InputStream is = Files.newInputStream(Paths.get(fileName))) {
            return load(is);
        }
    }

    public CryptoAPIX509Certificate load(final Path fileName)
        throws GeneralSecurityException, GeneralCryptoLibException, IOException {
        try(InputStream is = Files.newInputStream(fileName)) {
            return load(is);
        }
    }

    public CryptoAPIX509Certificate load(final InputStream inputStream)
        throws GeneralSecurityException, GeneralCryptoLibException, IOException {

        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate crt = (X509Certificate) cf.generateCertificate(inputStream);
        return new CryptoX509Certificate(crt);
    }
}
