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