source: dispositivos_moviles/TibisayMovil/src/ve/gob/cenditel/tibisaymovil/PKCS12ToDecryptActivity.java @ ba6bc7c

Last change on this file since ba6bc7c was ba6bc7c, checked in by Antonio Araujo Brett <aaraujo@…>, 11 years ago

Deshabilitados mensajes de depuración en clases.

  • Property mode set to 100644
File size: 43.4 KB
Line 
1package ve.gob.cenditel.tibisaymovil;
2
3import java.io.BufferedInputStream;
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.FileNotFoundException;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.io.InputStream;
10import java.security.cert.X509Certificate;
11import java.text.SimpleDateFormat;
12import java.util.ArrayList;
13import java.util.Collections;
14import java.util.Date;
15import java.util.Vector;
16
17import com.lowagie.text.pdf.PdfReader;
18
19import ee.sk.digidoc.DataFile;
20import ee.sk.digidoc.DigiDocException;
21import ee.sk.digidoc.SignedDoc;
22import ee.sk.digidoc.factory.DigiDocFactory;
23import ee.sk.digidoc.factory.Pkcs12SignatureFactory;
24import ee.sk.utils.ConfigManager;
25import ee.sk.xmlenc.EncryptedData;
26import ee.sk.xmlenc.factory.EncryptedDataParser;
27import ve.gob.cenditel.tibisaymovil.R;
28import android.app.Activity;
29import android.app.AlertDialog;
30import android.app.Dialog;
31import android.app.ProgressDialog;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.graphics.drawable.Drawable;
36import android.net.Uri;
37import android.os.AsyncTask;
38import android.os.Bundle;
39import android.os.Environment;
40import android.os.Looper;
41import android.util.Log;
42import android.view.LayoutInflater;
43import android.view.View;
44import android.view.ViewGroup;
45import android.view.View.OnClickListener;
46import android.view.Window;
47import android.webkit.MimeTypeMap;
48import android.widget.AdapterView;
49import android.widget.ArrayAdapter;
50import android.widget.BaseAdapter;
51import android.widget.Button;
52import android.widget.EditText;
53import android.widget.ImageView;
54import android.widget.LinearLayout;
55import android.widget.ListView;
56import android.widget.RadioButton;
57import android.widget.TextView;
58import android.widget.AdapterView.OnItemClickListener;
59import android.widget.Toast;
60
61public class PKCS12ToDecryptActivity extends Activity implements OnItemClickListener, OnClickListener {
62
63        private File cwd;
64    private File selected;
65    private FileBrowserView viewHolder;
66    private FileListAdapter listAdapter;
67    private String filterMImeType = "application/*";
68   
69    // cadena que mantiene la ruta del archivo descifrar
70    private String fileToDecrypt = null;
71   
72 // cadena que mantiene la ruta del archivo descifrado
73    private String decryptedFile = null;
74
75    // cadena que mantiene la ruta del archivo PKCS12
76    private String pkcs12File = null;
77
78    // contrasena del archivo p12
79    private String pkcs12Password = null;
80
81   
82        @Override
83        protected void onCreate(Bundle savedInstanceState) {
84                //Estilando la barra de titulo
85                final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
86
87                super.onCreate(savedInstanceState);
88               
89                this.viewHolder = new FileBrowserView();       
90
91        if (savedInstanceState != null) {
92                if(savedInstanceState.getString("selected") != null)
93                        this.selected = new File(savedInstanceState.getString("selected"));
94
95            if (this.selected != null) {
96               
97                PKCS12ToDecryptActivity.this.updateButton
98                (PKCS12ToDecryptActivity.this.viewHolder.accept,true);
99
100            }
101           
102            this.cwd = new File(savedInstanceState.getString("cwd"));
103            this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter(this.cwd.getAbsolutePath(), filterMImeType));
104           
105        } else {
106            this.selected = null;
107            this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter());
108        }
109       
110       
111        boolean enabled = false;
112        if (this.selected != null)
113                enabled = this.viewHolder.accept.isEnabled();
114       
115        PKCS12ToDecryptActivity.this.updateButton
116        (PKCS12ToDecryptActivity.this.viewHolder.accept,enabled);
117       
118        //Estilando Barra de titulo
119                if(customTitleSupported)
120                        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
121               
122               
123                // chequear si intent tiene data
124        final android.content.Intent intent = getIntent();
125        final android.net.Uri data = intent.getData();
126     
127       
128        if (data != null) {
129                // verificar el tipo de scheme
130            String scheme = data.getScheme();
131           
132            // descifrar un archivo que esta en el dispositivo
133            if (scheme.equals("file")) {
134                Log.d("PKCS12ToDecryptActivity: ", "scheme == file");
135                //Toast.makeText(getApplicationContext(), "Descifrar archivo: "+data.getPath(), Toast.LENGTH_SHORT).show();
136         
137                // obtener archivo a descifrar
138                          if (data.getPath().endsWith("cdoc")){
139                                  fileToDecrypt = data.getPath();
140                                 
141                                 
142                                        }else{
143                                                Toast.makeText(getApplicationContext(), "¡Intentando descifrar un archivo distinto de .cdoc!", Toast.LENGTH_SHORT).show();
144                                                Log.d("PKCS12ToDecryptActivity: ", "¡Intentando descifrar un archivo distinto de .cdoc!");
145                                                finish();
146                                        }               
147            }
148        }else{
149       
150                final Bundle bundle = getIntent().getExtras();
151                // verificacion de archivo desde la Activity principal
152                if (bundle != null) {
153                        Log.d("PKCS12ToDecryptActivity: ", "bundle != null");
154                        // Capturando archivo original que se debe descifrar
155                        fileToDecrypt = getIntent().getExtras().getString("fileToDecrypt");
156                }
157       
158        }
159            //Capturando archivo original que se debe descifrar
160        //fileToDecrypt = getIntent().getExtras().getString("fileToDecrypt");
161           
162        }
163
164       
165    /**
166     * Provides the data to be shown in the file browser ListView.
167     *
168     * @author José M. Prieto (jmprieto@emergya.com)
169     */
170    private class FileListAdapter extends BaseAdapter {
171
172        private final ArrayList<File> directories;
173        private final ArrayList<File> files;
174
175        private FileListAdapter() {
176            this("/",filterMImeType);
177        }
178
179        private FileListAdapter(String location) {
180            this(location, "");
181        }
182       
183        private FileListAdapter(String location, String filterMimeType) {
184               
185            directories = new ArrayList<File>();
186            files = new ArrayList<File>();
187           
188            //Obtiene etiqueta que se colocará antes del path que visualizará el usuario
189                String toPathText = PKCS12ToDecryptActivity.this.getString(R.string.pathstring)+":   ";
190                //Coloca el texto de la etiqueta en la vista
191                PKCS12ToDecryptActivity.this.viewHolder.pathString.setText(toPathText);
192                //Coloca el texto con el path actual
193                PKCS12ToDecryptActivity.this.viewHolder.path.setText(location);
194                //Crea un objeto file cwd con la ubicacion dada en location
195            PKCS12ToDecryptActivity.this.cwd = new File(location);
196            //Obtiene el directorio padre del objeto file cwd
197            File parent = PKCS12ToDecryptActivity.this.cwd.getParentFile();
198            //Si tiene un padre, lo agrega en la posición cero de la lista de directorios 
199           
200            if (parent != null) {
201                directories.add(0, parent);
202            }
203           
204            //Crea un arreglo con las lista de archivos contenidos en el directorio cwd
205            File[] ls = PKCS12ToDecryptActivity.this.cwd.listFiles();
206            if (ls != null) {
207                for (File f : ls) { //recorre todos los archivos contenidos en el directorio
208                       
209                    if (FsUtils.isHiddenOrNotReadable(f)) { // Si son ocultos no hace nada
210                        continue;
211                    }
212                  // Si son directorios los agrega a la lista de directorios a partir de la posición 1
213                  // En la posición 0 se encuentra el directorio padre 
214                    if (f.isDirectory()) {
215                        directories.add(f);
216                    } else // De lo contrario lo agrega a la lista de archivos
217                        {
218                        //Valida tipo de archivo a mostrar
219                        Uri selectedUri = Uri.fromFile(f);
220                        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
221                        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
222                         
223//                          Toast.makeText(PKCS12ToDecryptActivity.this,
224//                          "FileExtension: " + fileExtension + "\n" +
225//                          "MimeType: " + mimeType,
226//                          Toast.LENGTH_LONG).show();
227                       
228                                                 
229                        // en principio no filtrar ningun archivo
230                        if(filterMimeType.isEmpty() || filterMimeType == mimeType || fileExtension.equals("p12") || fileExtension.equals("pfx"))
231                                files.add(f);
232                               
233                    }
234                }
235            }
236
237            Collections.sort(directories); // Ordena los directorios alfabeticamente
238            Collections.sort(files); // Ordena los archivos alfabeticamente
239        }
240       
241        /**
242         * Retorna cantidad total de elementos que se listarán en el directorio.
243         */
244        @Override 
245        public int getCount() {
246               
247            return directories.size() + files.size();
248           
249        }
250
251        /**
252         * Dada una posición en el listado del directorio, retorna un archivo o directorio
253         * según corresponda.
254         */
255        @Override
256        public File getItem(int position) {
257
258            if (position < directories.size()) {
259                return directories.get(position);
260            } else {
261                return files.get(position - directories.size());
262            }
263        }
264
265        /**
266         * Retorna un código hash para el archivo, permite comparar si dos archivos son los mismos
267         */
268        @Override
269        public long getItemId(int position) {
270
271            return getItem(position).hashCode();
272        }
273       
274        /**
275         * Crea la visualización de cada item del fileBrowser
276         */
277        @Override
278        public View getView(int position, View convertView, ViewGroup parent) {
279
280                //Crea la vista de cada fila del filebrowser a partir del layout
281            if (convertView == null) {
282                LayoutInflater inflater = LayoutInflater.from(PKCS12ToDecryptActivity.this);
283                convertView = inflater.inflate(R.layout.file_to_verify_bdoc_signature_item, parent, false); 
284            }
285           
286            // Se enlaza a cada componente del layout
287            ImageView image = (ImageView) convertView.findViewById(R.id.type_image);
288            TextView fileName = (TextView) convertView.findViewById(R.id.filename_text);
289            TextView modified = (TextView) convertView.findViewById(R.id.filename_modified);
290           
291            // Se obtiene el archivo ubicado en position
292                File file = getItem(position);
293               
294                //RadioButton
295            RadioButton radio = (RadioButton) convertView.findViewById(R.id.file_radio);
296            radio.setFocusable(false);
297           
298            // Se asignan los iconos según el tipo de archivo y se oculta el radio en los directorios
299            if (file.isDirectory()) {
300                image.setImageResource(R.drawable.ic_carpeta);
301                radio.setVisibility(View.INVISIBLE);
302                radio.setChecked(false);
303            } else {
304                image.setImageResource(R.drawable.ic_archivo);
305                radio.setVisibility(View.VISIBLE);
306               
307                if (PKCS12ToDecryptActivity.this.selected == null ||
308                        PKCS12ToDecryptActivity.this.selected.hashCode() != file.hashCode()){
309                                radio.setChecked(false);
310                } else{
311                        radio.setChecked(true);
312                }         
313            }
314
315            // Si es el directorio que hace referencia al padre le coloca como nombre ".."
316            if (file.isDirectory() && position == 0 && ! "/".equals(PKCS12ToDecryptActivity.this.cwd.getAbsolutePath())) {
317                fileName.setText("..");
318            } else {
319                fileName.setText(file.getName());
320            }
321 
322           
323            //Datos de modificación del archivo
324            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
325            Date date = new Date(file.lastModified());
326           
327            String dateString = PKCS12ToDecryptActivity.this.getString(R.string.modified)+": ";
328            if (file.lastModified()>0)
329                modified.setText(dateString+sdf.format(date));
330            else
331                modified.setText(dateString+"-");
332           
333            return convertView;
334        }
335       
336        /**
337         * Controla la selección de cada item del fileBrowser
338         */
339        public void select(ListView parent, int position) {
340
341            File item = getItem(position);
342            //Si es un directorio el seleccionado se hace un llamado del fileBrowser del directorio
343            if (item.isDirectory()) {
344                parent.setAdapter(PKCS12ToDecryptActivity.this.listAdapter = new FileListAdapter(item.getAbsolutePath(), filterMImeType));
345            } else { // Si es un archivo
346               
347                        //Se agrega el archivo a la lista de seleccionados si no se encuentra en la misma               
348                if (PKCS12ToDecryptActivity.this.selected == null || 
349                        PKCS12ToDecryptActivity.this.selected.hashCode() != item.hashCode()){
350                       
351                        PKCS12ToDecryptActivity.this.selected = item;
352                       
353                        PKCS12ToDecryptActivity.this.updateButton(PKCS12ToDecryptActivity.this.viewHolder.accept,true);                 
354                                               
355                }
356                else{ // De lo contrario se elimina de la lista de seleccionados
357                       
358                        PKCS12ToDecryptActivity.this.selected = null;                           
359                        PKCS12ToDecryptActivity.this.updateButton(PKCS12ToDecryptActivity.this.viewHolder.accept,false);
360                                       
361                }
362                notifyDataSetChanged();
363           }
364        }       
365    }   
366
367
368   
369   
370    @Override
371    protected void onSaveInstanceState(Bundle outState) {
372        super.onSaveInstanceState(outState);
373
374        outState.putParcelable("intent", this.getIntent());
375        outState.putString("cwd", this.cwd.getAbsolutePath());
376        if(this.selected != null)
377                outState.putString("selected", this.selected.getAbsolutePath());
378       
379        }
380   
381    private void updateButton(View v, boolean bool) {
382        try{
383
384                v.setEnabled(bool);
385                if (v instanceof TextView){
386                        Drawable icon = ((TextView)v).getCompoundDrawables()[1];
387                        if (icon!=null)
388                        if (bool)
389                                icon.setAlpha(255);
390                        else
391                                icon.setAlpha(127);     
392                }
393                if (v instanceof ImageView){
394                        ImageView result = (ImageView) v;
395                        if (bool)
396                                result.setAlpha(255);
397                        else
398                                result.setAlpha(127);   
399                }
400       
401        }catch(NullPointerException e){}
402                       
403        }
404   
405    private void updateButton(LinearLayout layout, boolean bool) {
406        try{
407        layout.setEnabled(bool);
408        for (int i=0; i<layout.getChildCount();i++){
409                this.updateButton(layout.getChildAt(i), bool);
410        }
411        }catch(NullPointerException e){}
412                       
413        }
414
415       
416       
417        /**
418     * Holds references to view objects.
419     *
420     * @author José M. Prieto (jmprieto@emergya.com)
421     */
422    private class FileBrowserView {
423
424        public ListView fileList;
425        public TextView path;
426        public LinearLayout accept;
427                public LinearLayout clear;
428        public TextView pathString;
429
430        public FileBrowserView() {
431
432            setContentView(R.layout.activity_pkcs12_to_decrypt);
433            this.path = (TextView) findViewById(R.id.path);
434            this.pathString = (TextView) findViewById(R.id.pathstring);
435
436            this.fileList = (ListView) findViewById(R.id.file_list);
437            this.fileList.setOnItemClickListener(PKCS12ToDecryptActivity.this);
438            this.fileList.setItemsCanFocus(true);
439         
440           
441            this.clear = (LinearLayout) findViewById(R.id.button_clear_zone);
442            this.clear.setOnClickListener(PKCS12ToDecryptActivity.this);
443           
444            this.accept = (LinearLayout) findViewById(R.id.button_accept_zone);
445            this.accept.setOnClickListener(PKCS12ToDecryptActivity.this);
446
447        }
448    }
449   
450        @Override
451    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
452       
453       
454        if (parent.getId() == R.id.file_list) { // user selects a file
455            this.listAdapter.select((ListView) parent, position);
456           
457        } else { // user de-selects a file
458            //this.listAdapter.addIfSameDirectory(selectedAdapter.doUnselect((ListView) parent, position));
459               
460        }
461        //this.viewHolder.numSelected.setText(Integer.toString(this.selected.size()));
462    }
463
464    @Override
465    public void onClick(View v) {
466
467        switch (v.getId()) {
468
469       
470        case R.id.button_clear_zone:
471               
472                this.selected = null;
473                this.listAdapter.notifyDataSetChanged();
474
475                //this.viewHolder.numSelected.setText(""+this.selected.size());
476            this.updateButton(this.viewHolder.accept, false);
477                break;         
478       
479
480       
481            case R.id.button_accept_zone:
482               
483                // lanzar intent para compartir el archivo seleccionado
484                pkcs12File = PKCS12ToDecryptActivity.this.selected.getAbsolutePath();
485               
486                // crear dialogo para solicitar la contrasena del PKCS12
487                Dialog d = onCreateDialog();
488                d.show();
489               
490                //Toast.makeText(getApplicationContext(), "PKCS12ToDecryptActivity - PKCS12: "+pkcs12File, Toast.LENGTH_SHORT).show();
491               
492                break;         
493       
494        }
495    }
496   
497       
498        // funcion para compartir el archivo
499        private void shareIt() {
500               
501                Intent shareIntent = new Intent();
502                shareIntent.setAction(Intent.ACTION_SEND);
503                File file = new File(fileToDecrypt);
504               
505               
506                Uri uri = Uri.fromFile(file);
507                Log.i("DEBUG", file.getPath());
508                //Log.d("******", getMimeType(file.getPath()));
509                //shareIntent.setDataAndType(uri, getMimeType(file.getPath()));
510                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
511                shareIntent.setType("application/*");
512                startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_it_using)));
513        }
514       
515       
516        /**
517     * Selecciona el certificado del destinatario del directorio de certificados
518     * para cifrado
519     * @return void
520     */
521        // funcion para desplegar el gestor de certificados de destinatarios para cifrar
522        private void selectCertificateToEncrypt(String fileToEncrypt) {
523               
524                // desplegar la actividad de gestor de certificados de destinatarios
525
526                // chequear disponibilidad de directorio de certificados
527            if (!checkCertificatesDirectoryAvailability()){
528                //Toast.makeText(getApplicationContext(), "PKCS12ToDecryptActivity: directorio no disponible", Toast.LENGTH_SHORT).show();
529               
530                finish();
531                return;
532            }else{
533                // lanzar el activity SelectCeritificateToEncryptActivity
534                Intent intent = new Intent(this, SelectCertificateToEncryptActivity.class);             
535                        intent.putExtra("fileToEncrypt", fileToEncrypt);
536                        startActivity(intent);
537
538            }
539               
540               
541               
542               
543               
544        } // fin de selectRecipientCertificate()
545       
546        /**
547     * Chequea la disponibilidad del directorio de /TibisayMovil/CertificatesToEncrypt
548     * @return boolean
549     */
550    private boolean checkCertificatesDirectoryAvailability() {
551        // verificar acceso al directorio /mnt/sdcard/TibisayMovil/CertificatesToEncrypt
552            boolean mExternalStorageAvailable = false;
553            boolean mExternalStorageWriteable = false;
554            String state = Environment.getExternalStorageState();
555           
556            String certificatesDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
557                        getResources().getString(R.string.app_name) + "/" +
558                        getResources().getString(R.string.certificate_dir_files) + "/";
559           
560                AlertDialog.Builder builder = new AlertDialog.Builder(PKCS12ToDecryptActivity.this);
561               
562           
563            if (Environment.MEDIA_MOUNTED.equals(state)) {
564                // We can read and write the media
565                mExternalStorageAvailable = mExternalStorageWriteable = true;
566                //Toast.makeText(getApplicationContext(), "We can read and write the media", Toast.LENGTH_SHORT).show();
567               
568                // Crear directorio CertificatesToEncrypt donde se almacenan los certificados de
569                // destinatarios para cifrado
570                /*
571                        String certificatesDir = Environment.getExternalStorageDirectory() + "/" +
572                        getResources().getString(R.string.app_name) + "/" +
573                        getResources().getString(R.string.certificates_dir) + "/";
574                        */                     
575                        if (prepareDirectory(certificatesDir)){                         
576                                return true;
577                        }else{
578                                builder.setMessage("No existe el directorio "+certificatesDir+" para almacenar certificados.").setTitle("Error:");
579               
580                        }
581                       
582            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
583                // We can only read the media
584                mExternalStorageAvailable = true;
585                mExternalStorageWriteable = false;
586                //Toast.makeText(getApplicationContext(), "We can only read the media", Toast.LENGTH_SHORT).show();
587               
588                builder.setMessage("Directorio "+certificatesDir+ " montado de solo lectura. No se pueden almancenar certificados.").setTitle("Error:");
589       
590               
591            } else {
592                // Something else is wrong. It may be one of many other states, but all we need
593                //  to know is we can neither read nor write
594                mExternalStorageAvailable = mExternalStorageWriteable = false;
595                //Toast.makeText(getApplicationContext(), "we can neither read nor write", Toast.LENGTH_SHORT).show();
596               
597                builder.setMessage("Directorio "+certificatesDir+ " no está disponible. No se pueden almancenar certificados.").setTitle("Error:");                     
598       
599            }
600           
601           
602        builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
603                public void onClick(DialogInterface dialog, int id) {
604               // User cancelled the dialog
605                        PKCS12ToDecryptActivity.this.finish();
606            }
607        });
608            AlertDialog dialog = builder.create();
609            dialog.show();
610            return false;
611    } // fin de checkCertificatesDirectoryAvailability
612       
613   
614    /**
615     * Prepara directorio
616     * @return boolean
617     */
618    boolean prepareDirectory(String dir) 
619    {
620        try
621        {
622            if (makedirs(dir)) 
623            {
624                return true;
625            } else {
626                return false;
627            }
628        } catch (Exception e) 
629        {
630            e.printStackTrace();
631            //Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_LONG).show();
632            Toast.makeText(this, "No se pudo iniciar el sistema de archivos. ¿Está la SDCARD montada?", Toast.LENGTH_LONG).show();
633            return false;
634        }
635    }
636   
637    /**
638     * Crea directorio utilizando la variable tmpDir
639     * @return boolean
640     */
641    private boolean makedirs(String dir) 
642    {
643        //File tempdir = new File(extractedDirFiles);
644        File tempdir = new File(dir);
645        if (!tempdir.exists())
646            tempdir.mkdirs();
647        return (tempdir.isDirectory());
648    }
649   
650   
651    /**
652     * Crea dialogo para obtener la contrasena del archivo P12
653     *
654     * @return Dialog
655     */
656        public Dialog onCreateDialog() {
657         
658                LayoutInflater inflater = LayoutInflater.from(this);
659                final View dialogview = inflater.inflate(R.layout.pkcs12_password, null);
660
661                AlertDialog dialogDetails = null;
662               
663                final AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
664                dialogbuilder.setTitle(R.string.title_pkcs12_password);
665                dialogbuilder.setView(dialogview);
666               
667               
668                final EditText password = (EditText) dialogview.findViewById(R.id.password);
669                final Button okButton = (Button) dialogview.findViewById(R.id.button_accept);
670                okButton.setEnabled(true);
671                               
672                okButton.setOnClickListener(new View.OnClickListener() {
673                         
674                    @Override
675                    public void onClick(View v) {
676                     
677                     
678                     
679                     // asignar la contrasena
680                     pkcs12Password = password.getText().toString();
681                     if (!pkcs12Password.isEmpty()){
682                         //Toast.makeText(PKCS12ToDecryptActivity.this,"PKCS12 Password : "+ password.getText().toString(), Toast.LENGTH_LONG).show();
683                         
684                         password.setText("");
685                         
686                             // ejecutar el proceso de descifrado.
687                             decryptFile(fileToDecrypt, pkcs12File, pkcs12Password);
688
689                         
690                     }
691                     
692                     // ejecutar el proceso de descifrado.
693                     //decryptFile(fileToDecrypt, pkcs12File, pkcs12Password);
694                     
695                     // borrar el contenido de pkcs12Password
696                     pkcs12Password = "";
697                     
698                    }
699                });
700                               
701                dialogDetails = dialogbuilder.create();
702               
703                return dialogDetails;
704
705        }
706       
707       
708        /**
709     * Descifra el archivo pasado como argumento con el archivo P12
710     *
711     * @return void
712     */
713        private void decryptFile(final String fileToDecrypt, final String pkcs12File, final String pkcs12Password) {
714               
715                //Toast.makeText(getApplicationContext(), "Decrypting file: " + fileToDecrypt, Toast.LENGTH_SHORT).show();
716               
717                // -----------------------------
718                AsyncTask<Void, Void, ArrayList<String>> task = new AsyncTask<Void, Void, ArrayList<String>>() {
719
720            private ProgressDialog pd;
721
722            @Override
723            protected void onPreExecute() {
724
725                     pd = new ProgressDialog(PKCS12ToDecryptActivity.this);     
726                     pd.setTitle("Descifrando archivo");       
727                     pd.setMessage(getString(R.string.por_favor_epsere));       
728                     pd.setCancelable(false);   
729                     pd.setIndeterminate(true); 
730                     pd.show();
731
732            }
733
734            @Override
735            protected ArrayList<String> doInBackground(Void... arg0) {
736
737                /*
738                try {
739                    Thread.sleep(3000);
740                } catch(InterruptedException ex) {
741                    Thread.currentThread().interrupt();
742                }
743                */
744               
745                // para solventar error:
746                // Can't create handler inside thread that has not called Looper.prepare()
747                Looper.prepare();
748               
749                // arreglo para almacenar resultado de la operacion
750                ArrayList<String> resultArray = new ArrayList<String>();
751                resultArray.clear();
752               
753                ConfigManager.init("jar://jdigidoc.cfg");
754                        // signed doc object if used
755                SignedDoc m_sdoc;
756                m_sdoc = null;
757
758                // encrypted data object if used
759                EncryptedData m_cdoc;
760                m_cdoc = null;
761                       
762                        String outFile = null, keystoreFile = null, keystorePasswd = null, keystoreType="PKCS12";
763
764                        keystoreFile = pkcs12File;
765
766                        keystorePasswd = pkcs12Password;
767
768                        Log.d("Reading encrypted file: ",  fileToDecrypt);
769                       
770                        try {
771                                EncryptedDataParser dencFac =  ConfigManager.instance().getEncryptedDataParser();
772                                m_cdoc = dencFac.readEncryptedData(fileToDecrypt);                             
773                        } catch(Exception ex) {                 
774                                System.err.println("ERROR: reading encrypted file: " + fileToDecrypt + " - " + ex);
775                                Log.d("ERROR: reading encrypted file: ",  ex.getMessage());
776                                ex.printStackTrace(System.err);
777                                Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
778                               
779                                //showDialog("Error:", ex.getMessage(), false);
780                                //return null;
781                               
782                                resultArray.add("false");
783                                resultArray.add("Error");
784                                resultArray.add(ex.getMessage());
785                                return resultArray;
786                        }
787                       
788                        int nKey = -1;
789                       
790                        try{
791                               
792                                Pkcs12SignatureFactory p12fac = new Pkcs12SignatureFactory();
793                                p12fac.init();
794                                System.out.println("p12fac.init " );
795                               
796                                p12fac.load(keystoreFile, keystoreType, keystorePasswd);
797                                System.out.println("p12fac.load()");
798                               
799                                X509Certificate cert = p12fac.getAuthCertificate(0, keystorePasswd);
800                                System.out.println("p12fac.getAuthCertificate: " + nKey);
801                               
802                                nKey = m_cdoc.getRecvIndex(cert);
803                                System.out.println("Using recipient: " + nKey);
804                                if (nKey == -1) {
805                                        throw(new ArrayIndexOutOfBoundsException(""));
806                                }
807                               
808                               
809                        } // fin del try interno
810                        catch(DigiDocException ex){
811                                System.err.println("ERROR: finding cdoc recipient: " + ex);
812                               
813                                Log.d("Error finding cdoc recipient: ",  ex.getMessage());
814                        ex.printStackTrace(System.err);
815                        Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();   
816                                       
817                       
818                       
819                        if (ex.getCode() == DigiDocException.ERR_TOKEN_LOGIN) {
820                               
821                                // el pasword del PKCS12 no es correcto
822                                //showDialog(getResources().getString(R.string.msg_encryption_error), "password incorrecto", false);
823                                //return null;
824                               
825                                resultArray.add("false");
826                                resultArray.add(getResources().getString(R.string.msg_encryption_error));
827                                resultArray.add("contraseña incorrecta.");
828                                return resultArray;
829                               
830                               
831                        }else{
832                        //showDialog(getResources().getString(R.string.msg_encryption_error), ex.getMessage(), false);
833                                //return null;
834                               
835                                resultArray.add("false");
836                                resultArray.add(getResources().getString(R.string.msg_encryption_error));
837                                resultArray.add(ex.getMessage());
838                                return resultArray;
839                        }
840                       
841                        } catch(ArrayIndexOutOfBoundsException ex) {
842                                //showDialog(getResources().getString(R.string.msg_encryption_error),
843                                //              getResources().getString(R.string.error_decrypting_file_index_out_of_bounds), false);
844                                //return null;
845                               
846                                resultArray.add("false");
847                                resultArray.add(getResources().getString(R.string.msg_encryption_error));
848                                resultArray.add(getResources().getString(R.string.error_decrypting_file_index_out_of_bounds));
849                                return resultArray;
850                               
851                        }
852                       
853                        System.err.println("**** antes de ejecutar operacion m_cdoc.decryptPkcs12(nKey, keystoreFile, keystorePasswd, keystoreType)");
854                        // ejecutar la operacion de descifrado:
855                        try {
856                               
857                                m_cdoc.decryptPkcs12(nKey, keystoreFile, keystorePasswd, keystoreType);
858                               
859                                String [] absolutePathOriginalFile = fileToDecrypt.split(".cdoc");
860                                //String fileName = split[0];
861                                outFile = absolutePathOriginalFile[0];
862                               
863                                String [] path = absolutePathOriginalFile[0].split("/");
864                               
865                                String originalFileName = path[path.length-1];
866                               
867                                FileOutputStream fos = new FileOutputStream( outFile );
868                               
869                                Log.d("Decrypting file", "antes de escribir archivo " + outFile);
870                       
871                        fos.write(m_cdoc.getData());
872                       
873                        Log.d("Decrypting file", "despues de escribir archivo " + outFile);
874                       
875                        fos.close();
876                       
877                        Log.d("Decrypting file", "despues de cerrar archivo " + outFile);
878                       
879                        DigiDocFactory digFac = ConfigManager.instance().getDigiDocFactory();
880                        Log.d("Decrypting file", "despues ConfigManager.instance().getDigiDocFactory()");               
881                       
882                        File file = new File(outFile);
883                        InputStream selectedFile = null;
884                        selectedFile = new BufferedInputStream(new FileInputStream(file));
885                       
886                        m_sdoc = digFac.readSignedDocFromStreamOfType(selectedFile, false);
887                        Log.d("----", "leyo el ddoc");
888                        //Toast.makeText(getApplicationContext(), "leyó el ddoc", Toast.LENGTH_SHORT).show();
889                       
890                        selectedFile.close();
891
892                        // *******
893                        Log.d("Decrypting file", "antes de m_sdoc.getDataFile(0)");
894                        DataFile df = m_sdoc.getDataFile(0);
895                        Log.d("Decrypting file", "despues de m_sdoc.getDataFile(0)");
896                       
897                        String decryptedDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
898                                getResources().getString(R.string.app_name) + "/" +
899                                getResources().getString(R.string.decrypted_dir_files) + "/";
900                       
901                        decryptedFile = decryptedDir+originalFileName; 
902                       
903                        fos = new FileOutputStream(decryptedFile);
904                        InputStream is = df.getBodyAsStream();
905                       
906                        if(is == null) {
907                        System.err.println("DataFile has no data!");
908                        //showDialog(getResources().getString(R.string.msg_encryption_error),
909                        //              "DataFile has no data!", false);
910                        //return null;
911                       
912                       
913                        resultArray.add("false");
914                                resultArray.add(getResources().getString(R.string.msg_encryption_error));
915                                resultArray.add("DataFile has no data!");
916                                return resultArray;
917                       
918                    }
919                        byte[] data = new byte[4096];
920                    int n = 0, m = 0;
921                    while((n = is.read(data)) > 0) {
922                        fos.write(data, 0, n);
923                        m += n;
924                    }
925                    fos.close();
926                    is.close();
927
928                    // borrar el archivo ddoc
929                    File ddocFile = new File(outFile);
930                    ddocFile.delete();
931                   
932                   
933                    //Toast.makeText(getApplicationContext(), "Descifrado correctamente: " + decryptedFile, Toast.LENGTH_SHORT).show();
934                        //showDialog("Información:", "Archivo descifrado exitosamente.", true);
935                   
936                    resultArray.add("true");
937                                resultArray.add("Información:");
938                                resultArray.add("Archivo descifrado exitosamente.");
939                       
940                               
941                               
942                        } catch (DigiDocException e) {
943                               
944                                //showDialog(getResources().getString(R.string.msg_encryption_error),
945                                //              e.getMessage(), false);
946                                //return null;
947                               
948                                resultArray.add("false");
949                                resultArray.add(getResources().getString(R.string.msg_encryption_error));
950                                resultArray.add(e.getMessage());
951                                return resultArray;
952                               
953                        }
954                       
955                        catch (FileNotFoundException e) {
956                                //showDialog(getResources().getString(R.string.msg_encryption_error),
957                                //              e.getMessage(), false);
958                                //return null;
959                               
960                                resultArray.add("false");
961                                resultArray.add(getResources().getString(R.string.msg_encryption_error));
962                                resultArray.add(e.getMessage());
963                                return resultArray;
964                               
965                        } catch (IOException e) {
966                                //showDialog(getResources().getString(R.string.msg_encryption_error),
967                                //              e.getMessage(), false);
968                                //return null;
969                               
970                                resultArray.add("false");
971                                resultArray.add(getResources().getString(R.string.msg_encryption_error));
972                                resultArray.add(e.getMessage());
973                                return resultArray;
974                               
975                        }
976                               
977                return resultArray;
978         }           
979         @Override
980         protected void onPostExecute(ArrayList<String> result) {
981                 
982                 if (result.get(0).equals("false")){
983                         showDialog(result.get(1), result.get(2), false);
984                 }else{
985                         showDialog(result.get(1), result.get(2), true);
986                 }
987                         
988
989             pd.dismiss();
990
991         }
992
993        };
994
995        task.execute((Void[])null);
996               
997               
998                // -----------------------------
999/*             
1000                ConfigManager.init("jar://jdigidoc.cfg");
1001                // signed doc object if used
1002        SignedDoc m_sdoc;
1003        m_sdoc = null;
1004
1005        // encrypted data object if used
1006        EncryptedData m_cdoc;
1007        m_cdoc = null;
1008               
1009                String outFile = null, keystoreFile = null, keystorePasswd = null, keystoreType="PKCS12";
1010
1011                keystoreFile = pkcs12File;
1012
1013                keystorePasswd = pkcs12Password;
1014
1015                Log.d("Reading encrypted file: ",  fileToDecrypt);
1016               
1017                try {
1018                        EncryptedDataParser dencFac =  ConfigManager.instance().getEncryptedDataParser();
1019                        m_cdoc = dencFac.readEncryptedData(fileToDecrypt);                             
1020                } catch(Exception ex) {                 
1021                        System.err.println("ERROR: reading encrypted file: " + fileToDecrypt + " - " + ex);
1022                        Log.d("ERROR: reading encrypted file: ",  ex.getMessage());
1023                        ex.printStackTrace(System.err);
1024                        Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
1025                       
1026                        showDialog("Error:", ex.getMessage(), false);
1027                        return;
1028                }
1029               
1030                int nKey = -1;
1031               
1032                try{
1033                       
1034                        Pkcs12SignatureFactory p12fac = new Pkcs12SignatureFactory();
1035                        p12fac.init();
1036                        System.out.println("p12fac.init " );
1037                       
1038                        p12fac.load(keystoreFile, keystoreType, keystorePasswd);
1039                        System.out.println("p12fac.load()");
1040                       
1041                        X509Certificate cert = p12fac.getAuthCertificate(0, keystorePasswd);
1042                        System.out.println("p12fac.getAuthCertificate: " + nKey);
1043                       
1044                        nKey = m_cdoc.getRecvIndex(cert);
1045                        System.out.println("Using recipient: " + nKey);
1046                        if (nKey == -1) {
1047                                throw(new ArrayIndexOutOfBoundsException(""));
1048                        }
1049                       
1050                       
1051                } // fin del try interno
1052                catch(DigiDocException ex){
1053                        System.err.println("ERROR: finding cdoc recipient: " + ex);
1054                       
1055                        Log.d("Error finding cdoc recipient: ",  ex.getMessage());
1056                ex.printStackTrace(System.err);
1057                Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();   
1058                               
1059               
1060               
1061                if (ex.getCode() == DigiDocException.ERR_TOKEN_LOGIN) {
1062                       
1063                        // el pasword del PKCS12 no es correcto
1064                        showDialog(getResources().getString(R.string.msg_encryption_error),
1065                                        "password incorrecto", false);
1066                        return;
1067                }
1068                showDialog(getResources().getString(R.string.msg_encryption_error), ex.getMessage(), false);
1069                        return;
1070               
1071                } catch(ArrayIndexOutOfBoundsException ex) {
1072                        showDialog(getResources().getString(R.string.msg_encryption_error),
1073                                        getResources().getString(R.string.error_decrypting_file_index_out_of_bounds), false);
1074                        return;
1075                }
1076               
1077                System.err.println("**** antes de ejecutar operacion m_cdoc.decryptPkcs12(nKey, keystoreFile, keystorePasswd, keystoreType)");
1078                // ejecutar la operacion de descifrado:
1079                try {
1080                       
1081                        m_cdoc.decryptPkcs12(nKey, keystoreFile, keystorePasswd, keystoreType);
1082                       
1083                        String [] absolutePathOriginalFile = fileToDecrypt.split(".cdoc");
1084                        //String fileName = split[0];
1085                        outFile = absolutePathOriginalFile[0];
1086                       
1087                        String [] path = absolutePathOriginalFile[0].split("/");
1088                       
1089                        String originalFileName = path[path.length-1];
1090                       
1091                        FileOutputStream fos = new FileOutputStream( outFile );
1092                       
1093                        Log.d("Decrypting file", "antes de escribir archivo " + outFile);
1094               
1095                fos.write(m_cdoc.getData());
1096               
1097                Log.d("Decrypting file", "despues de escribir archivo " + outFile);
1098               
1099                fos.close();
1100               
1101                Log.d("Decrypting file", "despues de cerrar archivo " + outFile);
1102               
1103                DigiDocFactory digFac = ConfigManager.instance().getDigiDocFactory();
1104                Log.d("Decrypting file", "despues ConfigManager.instance().getDigiDocFactory()");               
1105               
1106                File file = new File(outFile);
1107                InputStream selectedFile = null;
1108                selectedFile = new BufferedInputStream(new FileInputStream(file));
1109               
1110                m_sdoc = digFac.readSignedDocFromStreamOfType(selectedFile, false);
1111                Log.d("----", "leyo el ddoc");
1112                Toast.makeText(getApplicationContext(), "leyó el ddoc", Toast.LENGTH_SHORT).show();
1113               
1114                selectedFile.close();
1115
1116                // *******
1117                Log.d("Decrypting file", "antes de m_sdoc.getDataFile(0)");
1118                DataFile df = m_sdoc.getDataFile(0);
1119                Log.d("Decrypting file", "despues de m_sdoc.getDataFile(0)");
1120               
1121                String decryptedDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
1122                        getResources().getString(R.string.app_name) + "/" +
1123                        getResources().getString(R.string.decrypted_dir_files) + "/";
1124               
1125                decryptedFile = decryptedDir+originalFileName;
1126               
1127                fos = new FileOutputStream(decryptedFile);
1128                InputStream is = df.getBodyAsStream();
1129               
1130                if(is == null) {
1131                System.err.println("DataFile has no data!");
1132                showDialog(getResources().getString(R.string.msg_encryption_error),
1133                                "DataFile has no data!", false);
1134                return;
1135            }
1136                byte[] data = new byte[4096];
1137            int n = 0, m = 0;
1138            while((n = is.read(data)) > 0) {
1139                fos.write(data, 0, n);
1140                m += n;
1141            }
1142            fos.close();
1143            is.close();
1144
1145            // borrar el archivo ddoc
1146            File ddocFile = new File(outFile);
1147            ddocFile.delete();
1148           
1149           
1150            Toast.makeText(getApplicationContext(), "Descifrado correctamente: " + decryptedFile, Toast.LENGTH_SHORT).show();
1151               
1152            showDialog("Información:", "Archivo descifrado exitosamente.", true);
1153           
1154            // TODO lanzar la actividad para mostrar el resultado del cifrado
1155            //showDecryptionResults(fileToDecrypt, decryptedFile);
1156               
1157                       
1158                       
1159                } catch (DigiDocException e) {
1160                       
1161                        showDialog(getResources().getString(R.string.msg_encryption_error),
1162                                        e.getMessage(), false);
1163                        return;
1164                }
1165               
1166                catch (FileNotFoundException e) {
1167                        showDialog(getResources().getString(R.string.msg_encryption_error),
1168                                        e.getMessage(), false);
1169                        return;
1170                } catch (IOException e) {
1171                        showDialog(getResources().getString(R.string.msg_encryption_error),
1172                                        e.getMessage(), false);
1173                        return;
1174                }
1175*/             
1176               
1177               
1178               
1179        } // fin de void decryptFile(String fileToDecrypt, String pkcs12File)
1180       
1181       
1182        /**
1183     * Crea un dialogo con el titulo y mensaje como argumentos y lo despliega 
1184     *
1185     * @return void
1186     */
1187    public void showDialog(String title, String msg, final boolean success) {
1188       
1189        // 1. Instantiate an AlertDialog.Builder with its constructor
1190                AlertDialog.Builder builder = new AlertDialog.Builder(PKCS12ToDecryptActivity.this);
1191
1192                // 2. Chain together various setter methods to set the dialog characteristics
1193                builder.setMessage(msg)
1194                .setTitle(title);
1195
1196                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
1197            public void onClick(DialogInterface dialog, int id) {
1198                // User clicked OK button                                               
1199                //Toast.makeText(getApplicationContext(), "User clicked OK button", Toast.LENGTH_LONG).show();
1200                finish();
1201               
1202                // TODO lanzar la actividad para mostrar el resultado del cifrado
1203                if (success){
1204                        showDecryptionResults(fileToDecrypt, decryptedFile);
1205                }
1206            }
1207                });
1208               
1209                // 3. Get the AlertDialog from create()                         
1210                AlertDialog dialog = builder.create();
1211                dialog.show();         
1212    }
1213               
1214               
1215    /**
1216     * Muestra la actividad de información del proceso de descifrado 
1217     *
1218     * @return void
1219     */
1220    public void showDecryptionResults(String fileToDecrypt, String decryptedFile) {
1221               
1222        // TODO lanzar el activity EncryptionResultActivity
1223       
1224        Intent intent = new Intent(this, DecryptionResultActivity.class);               
1225                intent.putExtra("fileToDecrypt", fileToDecrypt);
1226                intent.putExtra("decryptedFile", decryptedFile);               
1227                startActivity(intent);
1228         
1229       
1230    }
1231   
1232}
1233
Note: See TracBrowser for help on using the repository browser.