  
  var CAPICOM_CURRENT_USER_STORE= 2;
	var CAPICOM_ENCODE_BASE64 = 0;
  var CAPICOM_INFO_SUBJECT_SIMPLE_NAME = 0;
   //var CAPICOM_INFO_ISSUER_SIMPLE_NAME = 1;
   //var CAPICOM_INFO_SUBJECT_EMAIL_NAME = 2;
   //var CAPICOM_INFO_ISSUER_EMAIL_NAME  = 3;
   
    var CAPICOM_STORE_OPEN_READ_ONLY  = 0
    
    //var CAPICOM_KEY_SPEC_KEYEXCHANGE= 1
    //var CAPICOM_KEY_SPEC_SIGNATURE = 2 	
	
	var CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
	var CAPICOM_E_CANCELLED = -2138568446;
	//var CAPICOM_VERIFY_SIGNATURE_AND_CERTIFICATE = 1;
	var CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9;
	var CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
    var CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6;
    var CERT_KEY_SPEC_PROP_ID = 6;
	var CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
    var CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 0x00000080;
    
    //CertStore for 'my'	
	var MyStore = new ActiveXObject("CAPICOM.Store");
	//Selected Certificate for signature
	var	SelectedCertificate = new ActiveXObject("CAPICOM.Certificate");
	//Certificate selected check number,yes for 1,no for 0
	var CertificateSelectedCheck = 0;

	//when init Test if CAPICOM is Installed
	if (IsCAPICOMInstalled() != true)
	{
		// Alert the that CAPICOM was not able to be installed
		alert("请先按照要求设置IE,确保CA安全控件能正确安装！");	
	}
	
	//Test CAPICOM Installed or not
	function IsCAPICOMInstalled()
	{
		if(typeof(oCAPICOM) == "object")
		{
			if( (oCAPICOM.object != null) )
			{
				// Found CAPICOM
				return true;
			}
		}
	}
	//select option
 function populateCertificateList()
   {
    var szStore="my";
    window.status="Populating Certificate Store....";
    // Instantiate the objects we will be using...
    if( typeof(MyStore) != "object" )
    {
     var MyStore = new ActiveXObject("CAPICOM.Store");
    }
     try
	   {
          MyStore.Open(CAPICOM_CURRENT_USER_STORE, szStore, CAPICOM_STORE_OPEN_READ_ONLY);
	   }
	   catch (e)
	   {
		if (e.number != CAPICOM_E_CANCELLED)
		{
	   		alert("选择的证书有问题，请确认USBkey是否正确插入!");
			return false;
		}
	   }
    // Create the enumeration object so we can see what certificates are available.
    var Certificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_KEY_USAGE,CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE).Find(CAPICOM_CERTIFICATE_FIND_TIME_VALID)
	   .Find(CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY,CERT_KEY_SPEC_PROP_ID);
    //begin constructing table
    szHTML = "   <table cellpadding=\"0\" cellspacing=\"0\">";
    szHTML = szHTML +"    <tr><td><select name=\"txtCertificate\" id=\"txtCertificate\" class=\"selectcss\">";
    
    // Enumerate through each of the certificates in the store..
   if(Certificates.Count!=0){
    for (i = 1; i <= (Certificates.Count); i++)
    {
     szHTML = szHTML +"  <option value="
      + Certificates.Item(i).Thumbprint + " title="+Certificates.Item(i).GetInfo(CAPICOM_INFO_SUBJECT_SIMPLE_NAME)+">"+ Certificates.Item(i).GetInfo(CAPICOM_INFO_SUBJECT_SIMPLE_NAME)  
     +"</option>";
      CertificateSelectedCheck =1
    }
    }else{
    szHTML = szHTML +" <option>请正确插入USBkey</option>";
    }
     // end table
    szHTML = szHTML +"  </select></td>";
    szHTML = szHTML +" </tr>";
    szHTML = szHTML +"</table>";

    // update the div
    certdiv.innerHTML=szHTML;
    
    // Clean up
    MyStore = null;
    Certificates = null;
    
    window.status="";
   }
	
	//Find a certificate By hash code
	function FindCertificateByHash(szThumbprint){
	
	   // instantiate the CAPICOM objects
	   var MyStore = new ActiveXObject("CAPICOM.Store");

	   // open the current users personal certificate store
	   try
	   {
	   	MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);
	   }
	   catch (e)
	   {
		if (e.number != CAPICOM_E_CANCELLED)
		{
	   		alert("选择证书有问题，请确认USBkey正确插入!");
			return false;
		}
	   }

	   // find all of the certificates that have the specified hash
	   var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, szThumbprint);
	   return FilteredCertificates.Item(1);

	   // Clean Up
	   MyStore = null;
	   FilteredCertificates = null;
  	}
  
  	//Before submit the <form>, Sign the text
	function SignText(){
	if(CertificateSelectedCheck ==0) {
		alert("请正确插入USBkey，并选择一张证书登录！");
			return false;
		}else{	
				try
				{
				// Set the data that we want to sign
		            var SignedData = new ActiveXObject("CAPICOM.SignedData");
		 	        var Signer = new ActiveXObject("CAPICOM.Signer");
		   	        var TimeAttribute = new ActiveXObject("CAPICOM.Attribute");
				    SignedData.Content = GenRand();
				  
					// Set the Certificate we would like to sign with
			 	  	Signer.Certificate =  FindCertificateByHash(frmStore.txtCertificate.value);

					// Set the time in which we are applying the signature
					var Today = new Date();
					TimeAttribute.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
					TimeAttribute.Value = Today.getVarDate();
					Today = null;
					//Signer.AuthenticatedAttributes.Add(TimeAttribute);
					
					// Do the Sign operation

					var szSignature = SignedData.Sign(Signer, false, CAPICOM_ENCODE_BASE64);
				}
				catch (e)
				{
					
					if (e.number != -2146893792)
					{
						//mean 					
						  alert("请确认USBkey是否正确插入或者IE安全设置是否正确。" + e.description);
					}
					return false;
				}//end catch
				frmStore.username.value = Signer.Certificate.GetInfo(CAPICOM_INFO_SUBJECT_SIMPLE_NAME);
				frmStore.signedText.value = szSignature;
			
			SignedData = null;
			Signer = null;
			TimeAttribute = null;
			frmStore.txtCertificate.value=null;
			return true;
		}//Certificate != null
	}
	
	//return a now time like YYYY-MM-DD-HH-MM-SS 
	function NowTime(){
	
	   	/*var digital, s = "";         
	   	digital = new Date();            
	   	s += digital.getYear()+ "-";
	   	s += (digital.getMonth() + 1) + "-";
	   	s += digital.getDate() + "-";
	   	s += digital.getHours()+ "-";
		s += digital.getMinutes()+ "-";
		s += digital.getSeconds();
	  	return(s);*/
	  	return frmStore.servertime.value;
	}
	
	//Generate a 128 length random byte string
	function GenRand(){
	
		var util = new ActiveXObject("CAPICOM.Utilities");
		var rand = util.BinaryToHex(util.GetRandom(128));
		var i = 0;
		var ansString = "";
		var num;
		var numString = "";
		for(i=0;i<256;){
			num = parseInt(rand.substr(i,2), 16);
			numString += num + " " ;
			ansString += String.fromCharCode(num);
			i+=2;
		}
		//alert("TIME" + NowTime()+ "TIME");
		//set the string to contentText
		return "TIME" + NowTime()+ "TIME" + ansString;
		
	}

