Index: TibisayMovil/src/ve/gob/cenditel/tibisaymovil/PKCS12ToDecryptActivity.java
===================================================================
--- TibisayMovil/src/ve/gob/cenditel/tibisaymovil/PKCS12ToDecryptActivity.java	(revision 647bb1fc72eeb1363c7064dc02a911d1c36b7e13)
+++ TibisayMovil/src/ve/gob/cenditel/tibisaymovil/PKCS12ToDecryptActivity.java	(revision f32914c53199f85368d3c7cee87b4de9b6c0dd59)
@@ -13,4 +13,7 @@
 import java.util.Collections;
 import java.util.Date;
+import java.util.Vector;
+
+import com.lowagie.text.pdf.PdfReader;
 
 import ee.sk.digidoc.DataFile;
@@ -22,9 +25,9 @@
 import ee.sk.xmlenc.EncryptedData;
 import ee.sk.xmlenc.factory.EncryptedDataParser;
-
 import ve.gob.cenditel.tibisaymovil.R;
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.Dialog;
+import android.app.ProgressDialog;
 import android.content.Context;
 import android.content.DialogInterface;
@@ -32,6 +35,8 @@
 import android.graphics.drawable.Drawable;
 import android.net.Uri;
+import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Environment;
+import android.os.Looper;
 import android.util.Log;
 import android.view.LayoutInflater;
@@ -655,5 +660,5 @@
 		AlertDialog dialogDetails = null;
 		
-		AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
+		final AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
 		dialogbuilder.setTitle(R.string.title_pkcs12_password);
 		dialogbuilder.setView(dialogview);
@@ -669,11 +674,21 @@
 		    public void onClick(View v) {
 		     
-		     Toast.makeText(PKCS12ToDecryptActivity.this,"  Password : "+ password.getText().toString(), Toast.LENGTH_LONG).show();
+		     
 		     
 		     // asignar la contrasena
 		     pkcs12Password = password.getText().toString();
+		     if (!pkcs12Password.isEmpty()){
+		    	 Toast.makeText(PKCS12ToDecryptActivity.this,"PKCS12 Password : "+ password.getText().toString(), Toast.LENGTH_LONG).show();
+		    	 
+		    	 password.setText("");
+		    	 
+			     // ejecutar el proceso de descifrado.
+			     decryptFile(fileToDecrypt, pkcs12File, pkcs12Password);
+
+		    	 
+		     }
 		     
 		     // ejecutar el proceso de descifrado.
-		     decryptFile(fileToDecrypt, pkcs12File, pkcs12Password);
+		     //decryptFile(fileToDecrypt, pkcs12File, pkcs12Password);
 		     
 		     // borrar el contenido de pkcs12Password
@@ -691,19 +706,301 @@
 	
 	/**
-     * Crea dialogo para obtener la contrasena del archivo P12
+     * Descifra el archivo pasado como argumento con el archivo P12
      * 
-     * @return Dialog
+     * @return void
      */
-	private void decryptFile(String fileToDecrypt, String pkcs12File, String pkcs12Password) {
+	private void decryptFile(final String fileToDecrypt, final String pkcs12File, final String pkcs12Password) {
 		
 		Toast.makeText(getApplicationContext(), "Decrypting file: " + fileToDecrypt, Toast.LENGTH_SHORT).show();
 		
-		
+		// -----------------------------
+		AsyncTask<Void, Void, ArrayList<String>> task = new AsyncTask<Void, Void, ArrayList<String>>() {
+
+            private ProgressDialog pd;
+
+            @Override
+            protected void onPreExecute() {
+
+	             pd = new ProgressDialog(PKCS12ToDecryptActivity.this);	
+	             pd.setTitle("Descifrando archivo");	
+	             pd.setMessage(getString(R.string.por_favor_epsere));	
+	             pd.setCancelable(false);	
+	             pd.setIndeterminate(true);	
+	             pd.show();
+
+            }
+
+            @Override
+            protected ArrayList<String> doInBackground(Void... arg0) {
+
+            	/*
+            	try {
+            	    Thread.sleep(3000);
+            	} catch(InterruptedException ex) {
+            	    Thread.currentThread().interrupt();
+            	}
+            	*/
+            	
+            	// para solventar error:
+            	// Can't create handler inside thread that has not called Looper.prepare()
+            	Looper.prepare();
+            	
+            	// arreglo para almacenar resultado de la operacion
+            	ArrayList<String> resultArray = new ArrayList<String>();
+                resultArray.clear();
+            	
+            	ConfigManager.init("jar://jdigidoc.cfg");
+        		// signed doc object if used 
+            	SignedDoc m_sdoc;
+            	m_sdoc = null;
+
+            	// encrypted data object if used 
+            	EncryptedData m_cdoc;
+            	m_cdoc = null;
+        		
+        		String outFile = null, keystoreFile = null, keystorePasswd = null, keystoreType="PKCS12";
+
+        		keystoreFile = pkcs12File;
+
+        		keystorePasswd = pkcs12Password;
+
+        		Log.d("Reading encrypted file: ",  fileToDecrypt);
+        		
+        		try {
+        			EncryptedDataParser dencFac =  ConfigManager.instance().getEncryptedDataParser();
+        			m_cdoc = dencFac.readEncryptedData(fileToDecrypt);				
+        		} catch(Exception ex) {			
+        			System.err.println("ERROR: reading encrypted file: " + fileToDecrypt + " - " + ex);
+        			Log.d("ERROR: reading encrypted file: ",  ex.getMessage());
+        			ex.printStackTrace(System.err);
+        			Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
+        			
+        			//showDialog("Error:", ex.getMessage(), false);
+        			//return null;
+        			
+        			resultArray.add("false");
+        			resultArray.add("Error");
+        			resultArray.add(ex.getMessage());
+        			return resultArray;
+        		}
+        		
+        		int nKey = -1;
+        		
+        		try{
+        			
+        			Pkcs12SignatureFactory p12fac = new Pkcs12SignatureFactory();
+        			p12fac.init();
+        			System.out.println("p12fac.init " );
+        			
+        			p12fac.load(keystoreFile, keystoreType, keystorePasswd);
+        			System.out.println("p12fac.load()");
+        			
+        			X509Certificate cert = p12fac.getAuthCertificate(0, keystorePasswd);
+        			System.out.println("p12fac.getAuthCertificate: " + nKey);
+        			
+        			nKey = m_cdoc.getRecvIndex(cert);
+        			System.out.println("Using recipient: " + nKey);
+        			if (nKey == -1) {
+        				throw(new ArrayIndexOutOfBoundsException(""));
+        			}
+        			
+        			
+        		} // fin del try interno
+        		catch(DigiDocException ex){
+        			System.err.println("ERROR: finding cdoc recipient: " + ex);
+        			
+        			Log.d("Error finding cdoc recipient: ",  ex.getMessage());
+            		ex.printStackTrace(System.err);
+            		Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();	
+            		    		
+            		
+            		
+            		if (ex.getCode() == DigiDocException.ERR_TOKEN_LOGIN) {
+            			
+            			// el pasword del PKCS12 no es correcto
+            			//showDialog(getResources().getString(R.string.msg_encryption_error), "password incorrecto", false);
+            			//return null;
+            			
+            			resultArray.add("false");
+            			resultArray.add(getResources().getString(R.string.msg_encryption_error));
+            			resultArray.add("contraseña incorrecta.");
+            			return resultArray;
+            			
+            			
+            		}else{
+            		//showDialog(getResources().getString(R.string.msg_encryption_error), ex.getMessage(), false);
+        			//return null;
+        			
+            			resultArray.add("false");
+            			resultArray.add(getResources().getString(R.string.msg_encryption_error));
+            			resultArray.add(ex.getMessage());
+            			return resultArray;
+            		}
+            		
+        		} catch(ArrayIndexOutOfBoundsException ex) {
+        			//showDialog(getResources().getString(R.string.msg_encryption_error), 
+        			//		getResources().getString(R.string.error_decrypting_file_index_out_of_bounds), false);
+        			//return null;
+        			
+        			resultArray.add("false");
+        			resultArray.add(getResources().getString(R.string.msg_encryption_error));
+        			resultArray.add(getResources().getString(R.string.error_decrypting_file_index_out_of_bounds));
+        			return resultArray;
+        			
+        		}
+        		
+        		System.err.println("**** antes de ejecutar operacion m_cdoc.decryptPkcs12(nKey, keystoreFile, keystorePasswd, keystoreType)");
+        		// ejecutar la operacion de descifrado:
+        		try {
+        			
+        			m_cdoc.decryptPkcs12(nKey, keystoreFile, keystorePasswd, keystoreType);
+        			
+        			String [] absolutePathOriginalFile = fileToDecrypt.split(".cdoc");
+        			//String fileName = split[0];
+        			outFile = absolutePathOriginalFile[0];
+        			
+        			String [] path = absolutePathOriginalFile[0].split("/");
+        			
+        			String originalFileName = path[path.length-1];
+        			
+        			FileOutputStream fos = new FileOutputStream( outFile );
+        			
+        			Log.d("Decrypting file", "antes de escribir archivo " + outFile);
+            		
+            		fos.write(m_cdoc.getData());
+            		
+            		Log.d("Decrypting file", "despues de escribir archivo " + outFile);
+            		
+            		fos.close();
+            		
+            		Log.d("Decrypting file", "despues de cerrar archivo " + outFile);
+            		
+            		DigiDocFactory digFac = ConfigManager.instance().getDigiDocFactory();
+            		Log.d("Decrypting file", "despues ConfigManager.instance().getDigiDocFactory()");    		
+            		
+            		File file = new File(outFile);
+            		InputStream selectedFile = null;
+                	selectedFile = new BufferedInputStream(new FileInputStream(file));
+                	
+                	m_sdoc = digFac.readSignedDocFromStreamOfType(selectedFile, false);
+                	Log.d("----", "leyo el ddoc");
+                	Toast.makeText(getApplicationContext(), "leyó el ddoc", Toast.LENGTH_SHORT).show();
+                	
+                	selectedFile.close();
+
+            		// *******
+                	Log.d("Decrypting file", "antes de m_sdoc.getDataFile(0)");
+            		DataFile df = m_sdoc.getDataFile(0);
+            		Log.d("Decrypting file", "despues de m_sdoc.getDataFile(0)");
+            		
+            		String decryptedDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
+        			getResources().getString(R.string.app_name) + "/" +
+        			getResources().getString(R.string.decrypted_dir_files) + "/";
+            		
+            		decryptedFile = decryptedDir+originalFileName; 
+            		
+            		fos = new FileOutputStream(decryptedFile);
+            		InputStream is = df.getBodyAsStream();
+            		
+            		if(is == null) {
+                    	System.err.println("DataFile has no data!");
+                    	//showDialog(getResources().getString(R.string.msg_encryption_error), 
+                    	//		"DataFile has no data!", false);
+                    	//return null;
+                    	
+                    	
+                    	resultArray.add("false");
+            			resultArray.add(getResources().getString(R.string.msg_encryption_error));
+            			resultArray.add("DataFile has no data!");
+            			return resultArray;
+                    	
+                    }
+            		byte[] data = new byte[4096];
+                    int n = 0, m = 0;
+                    while((n = is.read(data)) > 0) {
+                    	fos.write(data, 0, n);
+                    	m += n;
+                    }
+                    fos.close();
+                    is.close();
+
+                    // borrar el archivo ddoc
+                    File ddocFile = new File(outFile);
+                    ddocFile.delete();
+                    
+                    
+                    //Toast.makeText(getApplicationContext(), "Descifrado correctamente: " + decryptedFile, Toast.LENGTH_SHORT).show();
+            		//showDialog("Información:", "Archivo descifrado exitosamente.", true);
+                    
+                    resultArray.add("true");
+        			resultArray.add("Información:");
+        			resultArray.add("Archivo descifrado exitosamente.");
+            		
+        			
+        			
+        		} catch (DigiDocException e) {
+        			
+        			//showDialog(getResources().getString(R.string.msg_encryption_error), 
+        			//		e.getMessage(), false);
+        			//return null;
+        			
+        			resultArray.add("false");
+        			resultArray.add(getResources().getString(R.string.msg_encryption_error));
+        			resultArray.add(e.getMessage());
+        			return resultArray;
+        			
+        		}
+        		
+        		catch (FileNotFoundException e) {
+        			//showDialog(getResources().getString(R.string.msg_encryption_error), 
+        			//		e.getMessage(), false);
+        			//return null;
+        			
+        			resultArray.add("false");
+        			resultArray.add(getResources().getString(R.string.msg_encryption_error));
+        			resultArray.add(e.getMessage());
+        			return resultArray;
+        			
+        		} catch (IOException e) {
+        			//showDialog(getResources().getString(R.string.msg_encryption_error), 
+        			//		e.getMessage(), false);
+        			//return null;
+        			
+        			resultArray.add("false");
+        			resultArray.add(getResources().getString(R.string.msg_encryption_error));
+        			resultArray.add(e.getMessage());
+        			return resultArray;
+        			
+        		}
+            	            	
+                return resultArray;
+         }            
+         @Override
+         protected void onPostExecute(ArrayList<String> result) {
+        	 
+        	 if (result.get(0).equals("false")){
+        		 showDialog(result.get(1), result.get(2), false);
+        	 }else{
+        		 showDialog(result.get(1), result.get(2), true);
+        	 }
+			  
+
+             pd.dismiss();
+
+         }
+
+        };
+
+        task.execute((Void[])null);
+		
+		
+		// -----------------------------
+/*		
 		ConfigManager.init("jar://jdigidoc.cfg");
-		/** signed doc object if used */
+		// signed doc object if used 
     	SignedDoc m_sdoc;
     	m_sdoc = null;
 
-    	/** encrypted data object if used */
+    	// encrypted data object if used 
     	EncryptedData m_cdoc;
     	m_cdoc = null;
@@ -875,5 +1172,5 @@
 			return;
 		}
-		
+*/		
 		
 		
