package net.catcert.trustedX.Creation.CAdES.T;

import org.apache.axis.client.Stub;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.commons.configuration.Configuration;

import utils.TrustedXConfiguration;
import utils.Util;
import utils.UtilTrustedX;

import com.safelayer.trustedx.client.smartwrapper.Constants;
import com.safelayer.trustedx.client.smartwrapper.SmartHeader;
import com.safelayer.trustedx.client.smartwrapper.SmartSignRequest;
import com.safelayer.trustedx.client.smartwrapper.SmartSignResponse;

/**
 * CMS/PKCS#7 Signature Generation
 * 
 * @author aalcaide
 */
public class CreateSignature_CAdES_T_Detached_Hash {

	private static final String path_in = "in/hashes_to_sign/";
	private static final String path_out = "out/Signatures/CAdES/";

	private static final String filename = "hash.bin";
	
	
	public static void main(String[] args) {
		try {

			Configuration conf = TrustedXConfiguration.getConfiguration();
			String host = conf.getString("host");
			String distinguishedName = conf.getString("distinguishedname");
			String dipositari = conf.getString("dipositari");
			String rol  = conf.getString("rol");
			
			// Definition of Signature Request endpoint
			SmartSignRequest ssr = new SmartSignRequest(host);
			
			// Add customized header elements for SOAP
			Stub stub = (Stub) ssr.getStub();
			stub.setHeader(null, "Rol", rol);
			stub.setHeader(null, "Dipositari", dipositari);

			// Text Signature (CMS)
			ssr.setProfile(Constants.Profile.CMSPKCS7);
			
			// Read of the text data
			ssr.setInputHashDigest(Util.readBinaryFileB64(path_in+filename));
			ssr.setInputHashAlgorithm(Constants.DigestAlgorithm.SHA1);
			
			// CMS signature type
			ssr.setSignatureType(Constants.SignatureType.CADES);
			// CAdES signature form
			ssr.setSignatureFormat(Constants.SignatureFormat.ES_T);

			// Key selection using Distinguished Name			
			ssr.setKeySubjectName(distinguishedName);
			
			// Sending the request
			SmartSignResponse ssrs = ssr.send();

			if (UtilTrustedX.checkSW(ssrs.getResultMajor(), ssrs.getResultMinor(), ssrs.getResultMessage())) {
				// Retrieve and write signature data to disk
				String destFilename = path_out + filename.substring(0, filename.lastIndexOf("."))
						+ "_Signature_CAdES_T_Detached.p7b";
				Util.writeBinaryFileB64(destFilename, ssrs.getSignatureBase64());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}