/*
 * Created on Nov 2, 2013
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.tin.aadhaar.AadhaarAuth.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Iterator;

import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

public class SubAuaVerifier {
	private X509Certificate getCertificateFromFile(String certificateFile) throws GeneralSecurityException, IOException {
		FileInputStream fis = null;
		try {
			Security.addProvider(new BouncyCastleProvider());
			CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
			fis = new FileInputStream(certificateFile);
			return (X509Certificate) certFactory.generateCertificate(fis);
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}
	public boolean verifySignatureParam(String sig,String strSaCd)
	{
		Log.aadhaarAuth_Log.debug("in verifySignatureParam method");
		boolean verified=false;
		try
		{
			//String data = "111111111111^abc^1234^F";
		    byte[] pkcs7SignedData =  Base64.decode(sig.getBytes());// a PKCS7 signed data block  
		    //CMSSignedData csd = new CMSSignedData(new CMSProcessableByteArray(data.getBytes()),pkcs7SignedData);
		    CMSSignedData csd = new CMSSignedData(pkcs7SignedData);
		    /*CMSProcessableByteArray cpb = (CMSProcessableByteArray) csd.getSignedContent();
		    byte[] signedContent = (byte[]) cpb.getContent();
		    
		    
		    String getData = new String(signedContent); */
		    //System.out.println("Data from sig :"+getData);
		    String publicKeyPath = UIDProperties.getSubAuaPublicKeyPath();
		    String publicKeyFile = publicKeyPath + "/" + strSaCd + ".cer";
		    Log.aadhaarAuth_Log.info("Sub Aua public key file :"+publicKeyFile);
		    
		    X509Certificate senderCert=getCertificateFromFile(publicKeyFile); // the sender's certificate 
		    Collection signers = csd.getSignerInfos().getSigners();
		    for (Iterator sit = signers.iterator(); sit.hasNext();) 
		    {    
		    	SignerInformation si = (SignerInformation) sit.next();  
		    	verified = si.verify(senderCert, "BC");  
		    	//System.out.println("verified: " + verified); 
		    }
		}catch(Exception e)
		{
			e.printStackTrace();
			verified=false;
			Log.aadhaarAuth_Log.error("Exeption in verifySignatureParam method of SubAuaVerifier class :"+e,e);			
		}		
		return verified;
	}

}
