/*
 * 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.commons.domain.model.platform;

import java.security.KeyPair;
import java.util.Date;

import com.scytl.cryptolib.api.certificates.CertificatesServiceAPI;
import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.certificates.bean.CertificateData;
import com.scytl.cryptolib.certificates.bean.RootCertificateData;
import com.scytl.cryptolib.certificates.bean.ValidityDates;
import com.scytl.cryptolib.certificates.bean.X509DistinguishedName;
import com.scytl.cryptolib.certificates.cryptoapi.CryptoAPIX509Certificate;
import com.scytl.cryptolib.certificates.service.CertificatesService;

public class CertificateUtil {
	
	public static CryptoAPIX509Certificate createRootSelfSignedCertificate(String commonName, String orgName, String orgUnit,
			String country, Date validFrom, Date validTo, KeyPair certKeyPair) throws GeneralCryptoLibException{
		CertificatesServiceAPI certificateGenerator = new CertificatesService();
		RootCertificateData rootCertificateData = new RootCertificateData();
		X509DistinguishedName self = new X509DistinguishedName.Builder(commonName, country).addOrganization(orgName)
				.addOrganizationalUnit(orgUnit).build();
		rootCertificateData.setSubjectDn(self);
		rootCertificateData.setSubjectPublicKey(certKeyPair.getPublic());
		rootCertificateData.setValidityDates(new ValidityDates(validFrom, validTo));
		return certificateGenerator.createRootAuthorityX509Certificate(rootCertificateData, certKeyPair.getPrivate());
	}	
	
	public static CryptoAPIX509Certificate createIntermediateCertificate(String commonName, String orgName, String orgUnit,
			String country, Date validFrom, Date validTo, KeyPair certKeyPair, KeyPair issuerKeyPair, X509DistinguishedName x509DistinguishedName) throws GeneralCryptoLibException{
		CertificatesServiceAPI certificateGenerator = new CertificatesService();
		CertificateData certificateData = new CertificateData();
		X509DistinguishedName self = new X509DistinguishedName.Builder(commonName, country).addOrganization(orgName)
				.addOrganizationalUnit(orgUnit).build();
		certificateData.setSubjectDn(self);
		certificateData.setIssuerDn(x509DistinguishedName);
		certificateData.setSubjectPublicKey(certKeyPair.getPublic());
		certificateData.setValidityDates(new ValidityDates(validFrom, validTo));
		return certificateGenerator.createIntermediateAuthorityX509Certificate(certificateData, issuerKeyPair.getPrivate());
	}

}
