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

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

Agregado encabezado de licencia a archivos fuentes.

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