[8379cd8] | 1 | /* |
---|
| 2 | Tibisay Movil |
---|
| 3 | |
---|
| 4 | Copyright (C) 2013 Antonio Araujo (aaraujo@cenditel.gob.ve), Jose Ruiz |
---|
| 5 | (jruiz@cenditel.gob.ve), Fundacion Centro Nacional de Desarrollo e |
---|
| 6 | Investigacion en Tecnologias Libres - CENDITEL. |
---|
| 7 | |
---|
| 8 | La Fundación CENDITEL concede permiso para usar, copiar, distribuir y/o |
---|
| 9 | modificar este programa, reconociendo el derecho que la humanidad posee al |
---|
| 10 | libre acceso al conocimiento, bajo los términos de la licencia de software |
---|
| 11 | GPL versión 2.0 de la Free Software Foundation. |
---|
| 12 | |
---|
| 13 | Este programa se distribuye con la esperanza de que sea util, pero SIN |
---|
| 14 | NINGUNA GARANTIA; tampoco las implicitas garantias de MERCANTILIDAD o |
---|
| 15 | ADECUACION A UN PROPOSITO PARTICULAR. |
---|
| 16 | |
---|
| 17 | Para mayor información sobre los términos de la licencia ver el archivo |
---|
| 18 | llamado "gpl-2.0.txt" en ingles. |
---|
| 19 | */ |
---|
| 20 | |
---|
[d5ab40f] | 21 | package ve.gob.cenditel.tibisaymovil; |
---|
| 22 | |
---|
| 23 | import java.io.BufferedInputStream; |
---|
| 24 | import java.io.File; |
---|
| 25 | import java.io.FileInputStream; |
---|
| 26 | import java.io.FileNotFoundException; |
---|
| 27 | import java.io.IOException; |
---|
| 28 | import java.io.InputStream; |
---|
| 29 | import java.security.cert.X509Certificate; |
---|
| 30 | import java.text.SimpleDateFormat; |
---|
| 31 | import java.util.ArrayList; |
---|
| 32 | import java.util.Collections; |
---|
| 33 | import java.util.Date; |
---|
| 34 | |
---|
| 35 | import ee.sk.digidoc.DigiDocException; |
---|
| 36 | import ee.sk.digidoc.SignedDoc; |
---|
| 37 | |
---|
| 38 | import ve.gob.cenditel.tibisaymovil.R; |
---|
| 39 | import android.app.Activity; |
---|
| 40 | import android.app.AlertDialog; |
---|
| 41 | import android.content.DialogInterface; |
---|
| 42 | import android.content.Intent; |
---|
| 43 | import android.graphics.drawable.Drawable; |
---|
| 44 | import android.net.Uri; |
---|
| 45 | import android.os.Bundle; |
---|
| 46 | import android.os.Environment; |
---|
| 47 | import android.util.Log; |
---|
| 48 | import android.view.LayoutInflater; |
---|
| 49 | import android.view.View; |
---|
| 50 | import android.view.ViewGroup; |
---|
| 51 | import android.view.View.OnClickListener; |
---|
| 52 | import android.view.Window; |
---|
| 53 | import android.webkit.MimeTypeMap; |
---|
| 54 | import android.widget.AdapterView; |
---|
| 55 | import android.widget.ArrayAdapter; |
---|
| 56 | import android.widget.BaseAdapter; |
---|
| 57 | import android.widget.ImageView; |
---|
| 58 | import android.widget.LinearLayout; |
---|
| 59 | import android.widget.ListView; |
---|
| 60 | import android.widget.RadioButton; |
---|
| 61 | import android.widget.TextView; |
---|
| 62 | import android.widget.AdapterView.OnItemClickListener; |
---|
| 63 | import android.widget.Toast; |
---|
| 64 | |
---|
| 65 | public class CertificateToLoadActivity extends Activity implements OnItemClickListener, OnClickListener { |
---|
| 66 | |
---|
| 67 | private File cwd; |
---|
| 68 | private File selected; |
---|
| 69 | private FileBrowserView viewHolder; |
---|
| 70 | private FileListAdapter listAdapter; |
---|
| 71 | private String filterMImeType = "application/pdf"; |
---|
| 72 | |
---|
| 73 | // cadena que mantiene la ruta del archivo a compartir |
---|
| 74 | private String fileToLoad = null; |
---|
| 75 | |
---|
| 76 | |
---|
| 77 | //ruta del directorio que almancena los certificados de destinatarios |
---|
| 78 | String certificatesDir; |
---|
| 79 | |
---|
| 80 | @Override |
---|
| 81 | protected void onCreate(Bundle savedInstanceState) { |
---|
| 82 | //Estilando la barra de titulo |
---|
| 83 | final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); |
---|
| 84 | |
---|
| 85 | super.onCreate(savedInstanceState); |
---|
| 86 | |
---|
| 87 | this.viewHolder = new FileBrowserView(); |
---|
| 88 | |
---|
| 89 | if (savedInstanceState != null) { |
---|
| 90 | if(savedInstanceState.getString("selected") != null) |
---|
| 91 | this.selected = new File(savedInstanceState.getString("selected")); |
---|
| 92 | |
---|
| 93 | if (this.selected != null) { |
---|
| 94 | |
---|
| 95 | CertificateToLoadActivity.this.updateButton |
---|
| 96 | (CertificateToLoadActivity.this.viewHolder.accept,true); |
---|
| 97 | |
---|
| 98 | } |
---|
| 99 | |
---|
| 100 | this.cwd = new File(savedInstanceState.getString("cwd")); |
---|
| 101 | this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter(this.cwd.getAbsolutePath(), filterMImeType)); |
---|
| 102 | |
---|
| 103 | } else { |
---|
| 104 | this.selected = null; |
---|
| 105 | this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter()); |
---|
| 106 | } |
---|
| 107 | |
---|
| 108 | |
---|
| 109 | boolean enabled = false; |
---|
| 110 | if (this.selected != null) |
---|
| 111 | enabled = this.viewHolder.accept.isEnabled(); |
---|
| 112 | |
---|
| 113 | CertificateToLoadActivity.this.updateButton |
---|
| 114 | (CertificateToLoadActivity.this.viewHolder.accept,enabled); |
---|
| 115 | |
---|
| 116 | //Estilando Barra de titulo |
---|
| 117 | if(customTitleSupported) |
---|
| 118 | getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar); |
---|
| 119 | |
---|
| 120 | // asignar ruta de certificados de destinatarios |
---|
| 121 | certificatesDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + |
---|
| 122 | getResources().getString(R.string.app_name) + "/" + |
---|
| 123 | getResources().getString(R.string.certificates_dir) + "/"; |
---|
| 124 | //Toast.makeText(getApplicationContext(), "certificatesDir: "+ certificatesDir, Toast.LENGTH_SHORT).show(); |
---|
| 125 | |
---|
| 126 | } |
---|
| 127 | |
---|
| 128 | |
---|
| 129 | /** |
---|
| 130 | * Provides the data to be shown in the file browser ListView. |
---|
| 131 | * |
---|
| 132 | * @author José M. Prieto (jmprieto@emergya.com) |
---|
| 133 | */ |
---|
| 134 | private class FileListAdapter extends BaseAdapter { |
---|
| 135 | |
---|
| 136 | private final ArrayList<File> directories; |
---|
| 137 | private final ArrayList<File> files; |
---|
| 138 | |
---|
| 139 | private FileListAdapter() { |
---|
| 140 | this("/",filterMImeType); |
---|
| 141 | } |
---|
| 142 | |
---|
| 143 | private FileListAdapter(String location) { |
---|
| 144 | this(location, ""); |
---|
| 145 | } |
---|
| 146 | |
---|
| 147 | private FileListAdapter(String location, String filterMimeType) { |
---|
| 148 | |
---|
| 149 | directories = new ArrayList<File>(); |
---|
| 150 | files = new ArrayList<File>(); |
---|
| 151 | |
---|
| 152 | //Obtiene etiqueta que se colocará antes del path que visualizará el usuario |
---|
| 153 | String toPathText = CertificateToLoadActivity.this.getString(R.string.pathstring)+": "; |
---|
| 154 | //Coloca el texto de la etiqueta en la vista |
---|
| 155 | CertificateToLoadActivity.this.viewHolder.pathString.setText(toPathText); |
---|
| 156 | //Coloca el texto con el path actual |
---|
| 157 | CertificateToLoadActivity.this.viewHolder.path.setText(location); |
---|
| 158 | //Crea un objeto file cwd con la ubicacion dada en location |
---|
| 159 | CertificateToLoadActivity.this.cwd = new File(location); |
---|
| 160 | //Obtiene el directorio padre del objeto file cwd |
---|
| 161 | File parent = CertificateToLoadActivity.this.cwd.getParentFile(); |
---|
| 162 | //Si tiene un padre, lo agrega en la posición cero de la lista de directorios |
---|
| 163 | |
---|
| 164 | if (parent != null) { |
---|
| 165 | directories.add(0, parent); |
---|
| 166 | } |
---|
| 167 | |
---|
| 168 | //Crea un arreglo con las lista de archivos contenidos en el directorio cwd |
---|
| 169 | File[] ls = CertificateToLoadActivity.this.cwd.listFiles(); |
---|
| 170 | if (ls != null) { |
---|
| 171 | for (File f : ls) { //recorre todos los archivos contenidos en el directorio |
---|
| 172 | |
---|
| 173 | if (FsUtils.isHiddenOrNotReadable(f)) { // Si son ocultos no hace nada |
---|
| 174 | continue; |
---|
| 175 | } |
---|
| 176 | // Si son directorios los agrega a la lista de directorios a partir de la posición 1 |
---|
| 177 | // En la posición 0 se encuentra el directorio padre |
---|
| 178 | if (f.isDirectory()) { |
---|
| 179 | directories.add(f); |
---|
| 180 | } else // De lo contrario lo agrega a la lista de archivos |
---|
| 181 | { |
---|
| 182 | //Valida tipo de archivo a mostrar |
---|
| 183 | Uri selectedUri = Uri.fromFile(f); |
---|
| 184 | String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString()); |
---|
| 185 | String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension); |
---|
| 186 | |
---|
| 187 | // Toast.makeText(CertificateToLoadActivity.this, |
---|
| 188 | // "FileExtension: " + fileExtension + "\n" + |
---|
| 189 | // "MimeType: " + mimeType, |
---|
| 190 | // Toast.LENGTH_LONG).show(); |
---|
| 191 | |
---|
| 192 | |
---|
| 193 | //Filtra por mimeType: se consideran los .pem .crt .cer |
---|
| 194 | if(filterMimeType.isEmpty() || /*filterMimeType == mimeType*/ fileExtension.equals("pem") |
---|
| 195 | || fileExtension.equals("crt") || fileExtension.equals("cer")) |
---|
| 196 | files.add(f); |
---|
| 197 | |
---|
| 198 | } |
---|
| 199 | } |
---|
| 200 | } |
---|
| 201 | |
---|
| 202 | Collections.sort(directories); // Ordena los directorios alfabeticamente |
---|
| 203 | Collections.sort(files); // Ordena los archivos alfabeticamente |
---|
| 204 | } |
---|
| 205 | |
---|
| 206 | /** |
---|
| 207 | * Retorna cantidad total de elementos que se listarán en el directorio. |
---|
| 208 | */ |
---|
| 209 | @Override |
---|
| 210 | public int getCount() { |
---|
| 211 | |
---|
| 212 | return directories.size() + files.size(); |
---|
| 213 | |
---|
| 214 | } |
---|
| 215 | |
---|
| 216 | /** |
---|
| 217 | * Dada una posición en el listado del directorio, retorna un archivo o directorio |
---|
| 218 | * según corresponda. |
---|
| 219 | */ |
---|
| 220 | @Override |
---|
| 221 | public File getItem(int position) { |
---|
| 222 | |
---|
| 223 | if (position < directories.size()) { |
---|
| 224 | return directories.get(position); |
---|
| 225 | } else { |
---|
| 226 | return files.get(position - directories.size()); |
---|
| 227 | } |
---|
| 228 | } |
---|
| 229 | |
---|
| 230 | /** |
---|
| 231 | * Retorna un código hash para el archivo, permite comparar si dos archivos son los mismos |
---|
| 232 | */ |
---|
| 233 | @Override |
---|
| 234 | public long getItemId(int position) { |
---|
| 235 | |
---|
| 236 | return getItem(position).hashCode(); |
---|
| 237 | } |
---|
| 238 | |
---|
| 239 | /** |
---|
| 240 | * Crea la visualización de cada item del fileBrowser |
---|
| 241 | */ |
---|
| 242 | @Override |
---|
| 243 | public View getView(int position, View convertView, ViewGroup parent) { |
---|
| 244 | |
---|
| 245 | //Crea la vista de cada fila del filebrowser a partir del layout |
---|
| 246 | if (convertView == null) { |
---|
| 247 | LayoutInflater inflater = LayoutInflater.from(CertificateToLoadActivity.this); |
---|
| 248 | convertView = inflater.inflate(R.layout.file_to_verify_bdoc_signature_item, parent, false); |
---|
| 249 | } |
---|
| 250 | |
---|
| 251 | // Se enlaza a cada componente del layout |
---|
| 252 | ImageView image = (ImageView) convertView.findViewById(R.id.type_image); |
---|
| 253 | TextView fileName = (TextView) convertView.findViewById(R.id.filename_text); |
---|
| 254 | TextView modified = (TextView) convertView.findViewById(R.id.filename_modified); |
---|
| 255 | |
---|
| 256 | // Se obtiene el archivo ubicado en position |
---|
| 257 | File file = getItem(position); |
---|
| 258 | |
---|
| 259 | //RadioButton |
---|
| 260 | RadioButton radio = (RadioButton) convertView.findViewById(R.id.file_radio); |
---|
| 261 | radio.setFocusable(false); |
---|
| 262 | |
---|
| 263 | // Se asignan los iconos según el tipo de archivo y se oculta el radio en los directorios |
---|
| 264 | if (file.isDirectory()) { |
---|
[58c7f6a] | 265 | image.setImageResource(R.drawable.ic_carpeta_verde); |
---|
[d5ab40f] | 266 | radio.setVisibility(View.INVISIBLE); |
---|
| 267 | radio.setChecked(false); |
---|
| 268 | } else { |
---|
[58c7f6a] | 269 | image.setImageResource(R.drawable.ic_archivo_verde); |
---|
[d5ab40f] | 270 | radio.setVisibility(View.VISIBLE); |
---|
| 271 | |
---|
| 272 | if (CertificateToLoadActivity.this.selected == null || |
---|
| 273 | CertificateToLoadActivity.this.selected.hashCode() != file.hashCode()){ |
---|
| 274 | radio.setChecked(false); |
---|
| 275 | } else{ |
---|
| 276 | radio.setChecked(true); |
---|
| 277 | } |
---|
| 278 | } |
---|
| 279 | |
---|
| 280 | // Si es el directorio que hace referencia al padre le coloca como nombre ".." |
---|
| 281 | if (file.isDirectory() && position == 0 && ! "/".equals(CertificateToLoadActivity.this.cwd.getAbsolutePath())) { |
---|
| 282 | fileName.setText(".."); |
---|
| 283 | } else { |
---|
| 284 | fileName.setText(file.getName()); |
---|
| 285 | } |
---|
| 286 | |
---|
| 287 | |
---|
| 288 | //Datos de modificación del archivo |
---|
| 289 | SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); |
---|
| 290 | Date date = new Date(file.lastModified()); |
---|
| 291 | |
---|
| 292 | String dateString = CertificateToLoadActivity.this.getString(R.string.modified)+": "; |
---|
| 293 | if (file.lastModified()>0) |
---|
| 294 | modified.setText(dateString+sdf.format(date)); |
---|
| 295 | else |
---|
| 296 | modified.setText(dateString+"-"); |
---|
| 297 | |
---|
| 298 | return convertView; |
---|
| 299 | } |
---|
| 300 | |
---|
| 301 | /** |
---|
| 302 | * Controla la selección de cada item del fileBrowser |
---|
| 303 | */ |
---|
| 304 | public void select(ListView parent, int position) { |
---|
| 305 | |
---|
| 306 | File item = getItem(position); |
---|
| 307 | //Si es un directorio el seleccionado se hace un llamado del fileBrowser del directorio |
---|
| 308 | if (item.isDirectory()) { |
---|
| 309 | parent.setAdapter(CertificateToLoadActivity.this.listAdapter = new FileListAdapter(item.getAbsolutePath(), filterMImeType)); |
---|
| 310 | } else { // Si es un archivo |
---|
| 311 | |
---|
| 312 | //Se agrega el archivo a la lista de seleccionados si no se encuentra en la misma |
---|
| 313 | if (CertificateToLoadActivity.this.selected == null || |
---|
| 314 | CertificateToLoadActivity.this.selected.hashCode() != item.hashCode()){ |
---|
| 315 | |
---|
| 316 | CertificateToLoadActivity.this.selected = item; |
---|
| 317 | |
---|
| 318 | CertificateToLoadActivity.this.updateButton(CertificateToLoadActivity.this.viewHolder.accept,true); |
---|
| 319 | |
---|
| 320 | } |
---|
| 321 | else{ // De lo contrario se elimina de la lista de seleccionados |
---|
| 322 | |
---|
| 323 | CertificateToLoadActivity.this.selected = null; |
---|
| 324 | CertificateToLoadActivity.this.updateButton(CertificateToLoadActivity.this.viewHolder.accept,false); |
---|
| 325 | |
---|
| 326 | } |
---|
| 327 | notifyDataSetChanged(); |
---|
| 328 | } |
---|
| 329 | } |
---|
| 330 | } |
---|
| 331 | |
---|
| 332 | |
---|
| 333 | |
---|
| 334 | |
---|
| 335 | @Override |
---|
| 336 | protected void onSaveInstanceState(Bundle outState) { |
---|
| 337 | super.onSaveInstanceState(outState); |
---|
| 338 | |
---|
| 339 | outState.putParcelable("intent", this.getIntent()); |
---|
| 340 | outState.putString("cwd", this.cwd.getAbsolutePath()); |
---|
| 341 | if(this.selected != null) |
---|
| 342 | outState.putString("selected", this.selected.getAbsolutePath()); |
---|
| 343 | |
---|
| 344 | } |
---|
| 345 | |
---|
| 346 | private void updateButton(View v, boolean bool) { |
---|
| 347 | try{ |
---|
| 348 | |
---|
| 349 | v.setEnabled(bool); |
---|
| 350 | if (v instanceof TextView){ |
---|
| 351 | Drawable icon = ((TextView)v).getCompoundDrawables()[1]; |
---|
| 352 | if (icon!=null) |
---|
| 353 | if (bool) |
---|
| 354 | icon.setAlpha(255); |
---|
| 355 | else |
---|
| 356 | icon.setAlpha(127); |
---|
| 357 | } |
---|
| 358 | if (v instanceof ImageView){ |
---|
| 359 | ImageView result = (ImageView) v; |
---|
| 360 | if (bool) |
---|
| 361 | result.setAlpha(255); |
---|
| 362 | else |
---|
| 363 | result.setAlpha(127); |
---|
| 364 | } |
---|
| 365 | |
---|
| 366 | }catch(NullPointerException e){} |
---|
| 367 | |
---|
| 368 | } |
---|
| 369 | |
---|
| 370 | private void updateButton(LinearLayout layout, boolean bool) { |
---|
| 371 | try{ |
---|
| 372 | layout.setEnabled(bool); |
---|
| 373 | for (int i=0; i<layout.getChildCount();i++){ |
---|
| 374 | this.updateButton(layout.getChildAt(i), bool); |
---|
| 375 | } |
---|
| 376 | }catch(NullPointerException e){} |
---|
| 377 | |
---|
| 378 | } |
---|
| 379 | |
---|
| 380 | |
---|
| 381 | |
---|
| 382 | /** |
---|
| 383 | * Holds references to view objects. |
---|
| 384 | * |
---|
| 385 | * @author José M. Prieto (jmprieto@emergya.com) |
---|
| 386 | */ |
---|
| 387 | private class FileBrowserView { |
---|
| 388 | |
---|
| 389 | public ListView fileList; |
---|
| 390 | public TextView path; |
---|
| 391 | public LinearLayout accept; |
---|
| 392 | public LinearLayout clear; |
---|
| 393 | public TextView pathString; |
---|
| 394 | |
---|
| 395 | public FileBrowserView() { |
---|
| 396 | |
---|
| 397 | setContentView(R.layout.activity_certificate_to_load); |
---|
| 398 | this.path = (TextView) findViewById(R.id.path); |
---|
| 399 | this.pathString = (TextView) findViewById(R.id.pathstring); |
---|
| 400 | |
---|
| 401 | this.fileList = (ListView) findViewById(R.id.file_list); |
---|
| 402 | this.fileList.setOnItemClickListener(CertificateToLoadActivity.this); |
---|
| 403 | this.fileList.setItemsCanFocus(true); |
---|
| 404 | |
---|
| 405 | |
---|
| 406 | this.clear = (LinearLayout) findViewById(R.id.button_clear_zone); |
---|
| 407 | this.clear.setOnClickListener(CertificateToLoadActivity.this); |
---|
| 408 | |
---|
| 409 | this.accept = (LinearLayout) findViewById(R.id.button_accept_zone); |
---|
| 410 | this.accept.setOnClickListener(CertificateToLoadActivity.this); |
---|
| 411 | |
---|
| 412 | } |
---|
| 413 | } |
---|
| 414 | |
---|
| 415 | @Override |
---|
| 416 | public void onItemClick(AdapterView<?> parent, View view, int position, long id) { |
---|
| 417 | |
---|
| 418 | |
---|
| 419 | if (parent.getId() == R.id.file_list) { // user selects a file |
---|
| 420 | this.listAdapter.select((ListView) parent, position); |
---|
| 421 | |
---|
| 422 | } else { // user de-selects a file |
---|
| 423 | //this.listAdapter.addIfSameDirectory(selectedAdapter.doUnselect((ListView) parent, position)); |
---|
| 424 | |
---|
| 425 | } |
---|
| 426 | //this.viewHolder.numSelected.setText(Integer.toString(this.selected.size())); |
---|
| 427 | } |
---|
| 428 | |
---|
| 429 | @Override |
---|
| 430 | public void onClick(View v) { |
---|
| 431 | |
---|
| 432 | switch (v.getId()) { |
---|
| 433 | |
---|
| 434 | |
---|
| 435 | case R.id.button_clear_zone: |
---|
| 436 | |
---|
| 437 | this.selected = null; |
---|
| 438 | this.listAdapter.notifyDataSetChanged(); |
---|
| 439 | |
---|
| 440 | //this.viewHolder.numSelected.setText(""+this.selected.size()); |
---|
| 441 | this.updateButton(this.viewHolder.accept, false); |
---|
| 442 | break; |
---|
| 443 | |
---|
| 444 | |
---|
| 445 | |
---|
| 446 | case R.id.button_accept_zone: |
---|
| 447 | |
---|
| 448 | // lanzar intent para compartir el archivo seleccionado |
---|
| 449 | fileToLoad = CertificateToLoadActivity.this.selected.getAbsolutePath(); |
---|
| 450 | |
---|
[ba6bc7c] | 451 | //Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: "+fileToLoad, Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 452 | |
---|
| 453 | loadCertificate(fileToLoad); |
---|
| 454 | |
---|
| 455 | break; |
---|
| 456 | |
---|
| 457 | } |
---|
| 458 | } // fin de onClick |
---|
| 459 | |
---|
| 460 | |
---|
| 461 | |
---|
| 462 | |
---|
| 463 | /** |
---|
| 464 | * Chequea la disponibilidad del directorio de /TibisayMovil/CertificatesToEncrypt |
---|
| 465 | * @return boolean |
---|
| 466 | */ |
---|
| 467 | private boolean checkCertificatesDirectoryAvailability() { |
---|
| 468 | // verificar acceso al directorio /mnt/sdcard/TibisayMovil/CertificatesToEncrypt |
---|
| 469 | boolean mExternalStorageAvailable = false; |
---|
| 470 | boolean mExternalStorageWriteable = false; |
---|
| 471 | String state = Environment.getExternalStorageState(); |
---|
| 472 | |
---|
| 473 | AlertDialog.Builder builder = new AlertDialog.Builder(CertificateToLoadActivity.this); |
---|
| 474 | |
---|
| 475 | |
---|
| 476 | if (Environment.MEDIA_MOUNTED.equals(state)) { |
---|
| 477 | // We can read and write the media |
---|
| 478 | mExternalStorageAvailable = mExternalStorageWriteable = true; |
---|
[ba6bc7c] | 479 | //Toast.makeText(getApplicationContext(), "We can read and write the media", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 480 | |
---|
| 481 | // Crear directorio CertificatesToEncrypt donde se almacenan los certificados de |
---|
| 482 | // destinatarios para cifrado |
---|
| 483 | /* |
---|
| 484 | String certificatesDir = Environment.getExternalStorageDirectory() + "/" + |
---|
| 485 | getResources().getString(R.string.app_name) + "/" + |
---|
| 486 | getResources().getString(R.string.certificates_dir) + "/"; |
---|
| 487 | */ |
---|
| 488 | if (prepareDirectory(certificatesDir)){ |
---|
| 489 | return true; |
---|
| 490 | }else{ |
---|
| 491 | builder.setMessage("No existe el directorio "+certificatesDir+" para almacenar certificados.").setTitle("Error:"); |
---|
| 492 | |
---|
| 493 | } |
---|
| 494 | |
---|
| 495 | } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { |
---|
| 496 | // We can only read the media |
---|
| 497 | mExternalStorageAvailable = true; |
---|
| 498 | mExternalStorageWriteable = false; |
---|
[ba6bc7c] | 499 | //Toast.makeText(getApplicationContext(), "We can only read the media", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 500 | |
---|
| 501 | builder.setMessage("Directorio "+certificatesDir+ " montado de solo lectura. No se pueden almancenar certificados.").setTitle("Error:"); |
---|
| 502 | |
---|
| 503 | |
---|
| 504 | } else { |
---|
| 505 | // Something else is wrong. It may be one of many other states, but all we need |
---|
| 506 | // to know is we can neither read nor write |
---|
| 507 | mExternalStorageAvailable = mExternalStorageWriteable = false; |
---|
[ba6bc7c] | 508 | //Toast.makeText(getApplicationContext(), "we can neither read nor write", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 509 | |
---|
| 510 | builder.setMessage("Directorio "+certificatesDir+ " no está disponible. No se pueden almancenar certificados.").setTitle("Error:"); |
---|
| 511 | |
---|
| 512 | } |
---|
| 513 | |
---|
| 514 | |
---|
| 515 | builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { |
---|
| 516 | public void onClick(DialogInterface dialog, int id) { |
---|
| 517 | // User cancelled the dialog |
---|
| 518 | CertificateToLoadActivity.this.finish(); |
---|
| 519 | } |
---|
| 520 | }); |
---|
| 521 | AlertDialog dialog = builder.create(); |
---|
| 522 | dialog.show(); |
---|
| 523 | return false; |
---|
| 524 | } // fin de checkCertificatesDirectoryAvailability |
---|
| 525 | |
---|
| 526 | /** |
---|
| 527 | * Prepara directorio |
---|
| 528 | * @return boolean |
---|
| 529 | */ |
---|
| 530 | boolean prepareDirectory(String dir) |
---|
| 531 | { |
---|
| 532 | try |
---|
| 533 | { |
---|
| 534 | if (makedirs(dir)) |
---|
| 535 | { |
---|
| 536 | return true; |
---|
| 537 | } else { |
---|
| 538 | return false; |
---|
| 539 | } |
---|
| 540 | } catch (Exception e) |
---|
| 541 | { |
---|
| 542 | e.printStackTrace(); |
---|
[ba6bc7c] | 543 | //Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_LONG).show(); |
---|
| 544 | Toast.makeText(this, "No se pudo iniciar el sistema de archivos. ¿Está la SDCARD montada?", Toast.LENGTH_LONG).show(); |
---|
[d5ab40f] | 545 | return false; |
---|
| 546 | } |
---|
| 547 | } |
---|
| 548 | |
---|
| 549 | /** |
---|
| 550 | * Crea directorio utilizando la variable tmpDir |
---|
| 551 | * @return boolean |
---|
| 552 | */ |
---|
| 553 | private boolean makedirs(String dir) |
---|
| 554 | { |
---|
| 555 | //File tempdir = new File(extractedDirFiles); |
---|
| 556 | File tempdir = new File(dir); |
---|
| 557 | if (!tempdir.exists()) |
---|
| 558 | tempdir.mkdirs(); |
---|
| 559 | return (tempdir.isDirectory()); |
---|
| 560 | } |
---|
| 561 | |
---|
| 562 | |
---|
| 563 | public void launchEncryptionCertificatesActivity() { |
---|
| 564 | Intent intent = new Intent(this, EncryptionCertificatesActivity.class); |
---|
| 565 | startActivity(intent); |
---|
| 566 | } |
---|
| 567 | |
---|
| 568 | |
---|
| 569 | |
---|
| 570 | |
---|
| 571 | |
---|
| 572 | /** |
---|
| 573 | * Carga un certificado desde un archivo en el directorio de certificados |
---|
| 574 | * para cifrado |
---|
| 575 | * @return void |
---|
| 576 | */ |
---|
| 577 | public void loadCertificate(String fileToLoad){ |
---|
| 578 | |
---|
| 579 | |
---|
| 580 | // chequear disponibilidad de directorio de certificados |
---|
| 581 | if (!checkCertificatesDirectoryAvailability()){ |
---|
[ba6bc7c] | 582 | //Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: directorio no disponible", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 583 | |
---|
| 584 | finish(); |
---|
| 585 | // lanzar el activity EncryptionCertificatesActivity |
---|
| 586 | launchEncryptionCertificatesActivity(); |
---|
| 587 | return; |
---|
| 588 | } |
---|
| 589 | |
---|
| 590 | |
---|
| 591 | // cargar el archivo y verificar que es un certificado bien formado |
---|
| 592 | try { |
---|
| 593 | X509Certificate recipientCertificate = SignedDoc.readCertificate(new File(fileToLoad)); |
---|
| 594 | |
---|
| 595 | boolean [] keyUsage = recipientCertificate.getKeyUsage(); |
---|
| 596 | |
---|
[ba6bc7c] | 597 | //Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: cerrificado leido", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 598 | |
---|
| 599 | if (keyUsage == null){ |
---|
[ba6bc7c] | 600 | //Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: keyUsage == null", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 601 | |
---|
| 602 | showDialog("Error:", "El certificado seleccionado no tiene la extensión \"Cifrado de Clave \" (KeyEncipherment) para cifrado. " + |
---|
| 603 | "Seleccione otro certificado."); |
---|
| 604 | return; |
---|
| 605 | } |
---|
| 606 | |
---|
| 607 | if ( keyUsage[2] ){ |
---|
[ba6bc7c] | 608 | //Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: CERTIFICADO SI TIENE KeyEncipherment", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 609 | |
---|
| 610 | |
---|
| 611 | // TODO verificar que el certificado no exista |
---|
| 612 | if (compareCertificate(recipientCertificate)){ |
---|
| 613 | |
---|
[ba6bc7c] | 614 | //Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: El certificado ya existe en el repositorio", Toast.LENGTH_SHORT).show(); |
---|
[d5ab40f] | 615 | |
---|
| 616 | showDialog("Información:", "El certificado ya existe en el repositorio. Se cancela la operación."); |
---|
| 617 | |
---|
| 618 | return; |
---|
| 619 | } |
---|
| 620 | |
---|
| 621 | // copiar el certificado al directorio de certificados |
---|
| 622 | File f = new File(fileToLoad); |
---|
| 623 | FsUtils.copyTo(f, certificatesDir); |
---|
| 624 | |
---|
| 625 | showDialog("Información:", "El certificado se cargó exitosamente."); |
---|
| 626 | |
---|
| 627 | return; |
---|
| 628 | |
---|
| 629 | }else{ |
---|
| 630 | |
---|
| 631 | showDialog("Error:", "El certificado seleccionado no tiene la extensión \"Cifrado de Clave \" (KeyEncipherment) para cifrado. " + |
---|
| 632 | "Seleccione otro certificado."); |
---|
| 633 | |
---|
| 634 | return; |
---|
| 635 | } |
---|
| 636 | |
---|
| 637 | |
---|
| 638 | } catch (DigiDocException e1) { |
---|
| 639 | e1.printStackTrace(); |
---|
| 640 | Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: "+ e1.getMessage(), Toast.LENGTH_SHORT).show(); |
---|
| 641 | |
---|
| 642 | showDialog("Error:", e1.getMessage()); |
---|
| 643 | |
---|
| 644 | return; |
---|
| 645 | |
---|
| 646 | |
---|
| 647 | } catch (IOException e) { |
---|
| 648 | |
---|
| 649 | Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: ERROR no se pudo corpiar el certificado al directorio de certificados", |
---|
| 650 | Toast.LENGTH_SHORT).show(); |
---|
| 651 | |
---|
| 652 | showDialog("Error:", e.getMessage()); |
---|
| 653 | |
---|
| 654 | return; |
---|
| 655 | |
---|
| 656 | } |
---|
| 657 | } |
---|
| 658 | |
---|
| 659 | /** |
---|
| 660 | * Compara el certificado pasado como argumento con los certificados existentes en |
---|
| 661 | * el directorio de certificados. |
---|
| 662 | * |
---|
| 663 | * @return verdadero si ya existe el certificado en el directorio |
---|
| 664 | */ |
---|
| 665 | public boolean compareCertificate(X509Certificate obj){ |
---|
| 666 | |
---|
| 667 | // obtener lista de archivos del directorio de certificados |
---|
| 668 | |
---|
| 669 | File certificateDirectory = new File(certificatesDir); |
---|
| 670 | |
---|
| 671 | File[] ls = certificateDirectory.listFiles(); |
---|
| 672 | if (ls != null) { |
---|
| 673 | for (File f : ls) { //recorre todos los archivos contenidos en el directorio |
---|
| 674 | |
---|
| 675 | if (FsUtils.isHiddenOrNotReadable(f)) { // Si son ocultos no hace nada |
---|
| 676 | continue; |
---|
| 677 | } |
---|
| 678 | |
---|
| 679 | // iterar por cada archivo y verificar si certificado es igual a obj |
---|
| 680 | |
---|
| 681 | X509Certificate certificateRead; |
---|
| 682 | try { |
---|
| 683 | certificateRead = SignedDoc.readCertificate(f); |
---|
| 684 | if (obj.equals(certificateRead)){ |
---|
| 685 | return true; |
---|
| 686 | } |
---|
| 687 | } catch (DigiDocException e) { |
---|
| 688 | e.printStackTrace(); |
---|
| 689 | Toast.makeText(getApplicationContext(), "CertificateToLoadActivity: "+ e.getMessage(), Toast.LENGTH_SHORT).show(); |
---|
| 690 | |
---|
| 691 | showDialog("Error:", e.getMessage()); |
---|
| 692 | } |
---|
| 693 | |
---|
| 694 | |
---|
| 695 | } |
---|
| 696 | return false; |
---|
| 697 | } |
---|
| 698 | |
---|
| 699 | return false; |
---|
| 700 | } |
---|
| 701 | |
---|
| 702 | /** |
---|
| 703 | * Crea un dialogo con el titulo y mensaje como argumentos y lo despliega |
---|
| 704 | * |
---|
| 705 | * @return void |
---|
| 706 | */ |
---|
| 707 | public void showDialog(String title, String msg) { |
---|
| 708 | |
---|
| 709 | // 1. Instantiate an AlertDialog.Builder with its constructor |
---|
| 710 | AlertDialog.Builder builder = new AlertDialog.Builder(CertificateToLoadActivity.this); |
---|
| 711 | |
---|
| 712 | // 2. Chain together various setter methods to set the dialog characteristics |
---|
| 713 | builder.setMessage(msg) |
---|
| 714 | .setTitle(title); |
---|
| 715 | |
---|
| 716 | builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { |
---|
| 717 | public void onClick(DialogInterface dialog, int id) { |
---|
| 718 | // User clicked OK button |
---|
[ba6bc7c] | 719 | //Toast.makeText(getApplicationContext(), "User clicked OK button", Toast.LENGTH_LONG).show(); |
---|
[d5ab40f] | 720 | finish(); |
---|
| 721 | |
---|
| 722 | // lanzar el activity EncryptionCertificatesActivity |
---|
| 723 | launchEncryptionCertificatesActivity(); |
---|
| 724 | } |
---|
| 725 | }); |
---|
| 726 | |
---|
| 727 | // 3. Get the AlertDialog from create() |
---|
| 728 | AlertDialog dialog = builder.create(); |
---|
| 729 | dialog.show(); |
---|
| 730 | |
---|
| 731 | } |
---|
| 732 | |
---|
| 733 | } |
---|
| 734 | |
---|