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