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

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

*- Agregado soporte para descrifrar un documento cifrado al seleccionarlo desde el sistema de archivo del móvil.

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