source: dispositivos_moviles/TibisayMovil/src/ve/gob/cenditel/tibisaymovil/SelectCertificateToEncryptActivity.java @ 42e7061

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

*- Modificaciones en actividad para ejecutar cifrado de un archivo a través de una tarea asíncrona (AsyncTask?). Se muestra un diálogo de progreso durante el proceso de cifrado.

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