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