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 | |
---|
21 | package ve.gob.cenditel.tibisaymovil; |
---|
22 | |
---|
23 | import java.io.ByteArrayInputStream; |
---|
24 | import java.io.ByteArrayOutputStream; |
---|
25 | import java.io.File; |
---|
26 | import java.io.FileOutputStream; |
---|
27 | import java.io.IOException; |
---|
28 | import java.io.InputStream; |
---|
29 | import java.io.ObjectOutputStream; |
---|
30 | import java.security.PrivateKey; |
---|
31 | import java.security.cert.X509Certificate; |
---|
32 | import java.util.ArrayList; |
---|
33 | import java.util.List; |
---|
34 | |
---|
35 | import com.sun.jersey.api.client.ClientHandlerException; |
---|
36 | import com.sun.jersey.api.client.UniformInterfaceException; |
---|
37 | |
---|
38 | import android.app.Activity; |
---|
39 | import android.content.Context; |
---|
40 | import android.content.Intent; |
---|
41 | import android.content.res.Resources; |
---|
42 | import android.net.Uri; |
---|
43 | import android.os.Bundle; |
---|
44 | import android.os.Environment; |
---|
45 | import android.text.method.ScrollingMovementMethod; |
---|
46 | import android.util.Log; |
---|
47 | import android.view.View; |
---|
48 | import android.view.Window; |
---|
49 | import android.view.View.OnClickListener; |
---|
50 | import android.widget.Button; |
---|
51 | import android.widget.LinearLayout; |
---|
52 | import android.widget.TextView; |
---|
53 | import android.widget.Toast; |
---|
54 | |
---|
55 | |
---|
56 | import com.lowagie.text.exceptions.InvalidPdfException; |
---|
57 | // prueba de droidtext |
---|
58 | import com.lowagie.text.pdf.*; |
---|
59 | import com.lowagie.text.*; |
---|
60 | |
---|
61 | public class SignActivity extends Activity implements OnClickListener { |
---|
62 | |
---|
63 | private boolean embedInPdf; |
---|
64 | private String alias; |
---|
65 | private List<Uri> uris; |
---|
66 | private SignView viewHolder; |
---|
67 | private List<Uri> signed; |
---|
68 | private List<Uri> unsigned; |
---|
69 | private ArrayList<Uri> send = new ArrayList<Uri>(); |
---|
70 | private SignTask task; |
---|
71 | |
---|
72 | /** Called when the activity is first created. */ |
---|
73 | @Override |
---|
74 | public void onCreate(Bundle savedInstanceState) { |
---|
75 | //Estilando la barra de titulo |
---|
76 | final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); |
---|
77 | |
---|
78 | super.onCreate(savedInstanceState); |
---|
79 | this.embedInPdf = getIntent().getBooleanExtra(IntentExtraField.EMBED_SIGNATURE_IN_PDF, false); |
---|
80 | this.alias = getIntent().getStringExtra(IntentExtraField.ALIAS); |
---|
81 | this.uris = getIntent().getParcelableArrayListExtra(IntentExtraField.FILES); |
---|
82 | this.viewHolder = new SignView(); |
---|
83 | |
---|
84 | this.task = (SignTask) getLastNonConfigurationInstance(); |
---|
85 | if (this.task != null) { |
---|
86 | this.task.activity = this; |
---|
87 | } else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { |
---|
88 | this.task = (SignTask) new SignTask(this, FsUtils.createOutputDirectory(this), this).execute( |
---|
89 | uris.toArray(new Uri[uris.size()])); |
---|
90 | } else { |
---|
91 | this.viewHolder.noStorageError(); |
---|
92 | } |
---|
93 | |
---|
94 | if (savedInstanceState != null) { |
---|
95 | this.send = savedInstanceState.getParcelableArrayList("send"); |
---|
96 | this.viewHolder.done(); |
---|
97 | } |
---|
98 | //Estilando Barra de titulo |
---|
99 | if(customTitleSupported) |
---|
100 | getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar); |
---|
101 | } |
---|
102 | |
---|
103 | @Override |
---|
104 | public Object onRetainNonConfigurationInstance() { |
---|
105 | |
---|
106 | return this.task; |
---|
107 | } |
---|
108 | |
---|
109 | @Override |
---|
110 | protected void onDestroy() { |
---|
111 | this.task.cancel(true); |
---|
112 | |
---|
113 | if (this.task != null) { |
---|
114 | this.task.activity = null; |
---|
115 | } |
---|
116 | super.onDestroy(); |
---|
117 | } |
---|
118 | |
---|
119 | @Override |
---|
120 | protected void onSaveInstanceState(Bundle outState) { |
---|
121 | |
---|
122 | super.onSaveInstanceState(outState); |
---|
123 | outState.putParcelableArrayList("send", this.send); |
---|
124 | } |
---|
125 | |
---|
126 | @Override |
---|
127 | public void onBackPressed() { |
---|
128 | Intent back = new Intent(this, TibisayMovilActivity.class); |
---|
129 | startActivity(back); |
---|
130 | finish(); |
---|
131 | } |
---|
132 | |
---|
133 | |
---|
134 | @Override |
---|
135 | public void onClick(View v) { |
---|
136 | |
---|
137 | switch (v.getId()) { |
---|
138 | |
---|
139 | case R.id.button_finish_zone: |
---|
140 | Intent back = new Intent(this, TibisayMovilActivity.class); |
---|
141 | startActivity(back); |
---|
142 | finish(); |
---|
143 | break; |
---|
144 | |
---|
145 | case R.id.button_share_zone: |
---|
146 | Intent intent = IntentUtils.sendMultipleFiles(this.send); |
---|
147 | //In case user has no email application. |
---|
148 | try{ |
---|
149 | startActivity(intent); |
---|
150 | finish(); |
---|
151 | }catch (android.content.ActivityNotFoundException e){ |
---|
152 | Toast.makeText(this, this.getString(R.string.errornoemail), Toast.LENGTH_SHORT).show(); |
---|
153 | } |
---|
154 | } |
---|
155 | } |
---|
156 | |
---|
157 | private static class SignTask extends AsyncErrorTask<Uri, Void, List<Uri>> { |
---|
158 | |
---|
159 | private SignActivity activity; |
---|
160 | private String directory; |
---|
161 | private Context context; |
---|
162 | |
---|
163 | public SignTask(SignActivity activity, String directory, Context context) { |
---|
164 | |
---|
165 | this.activity = activity; |
---|
166 | this.directory = directory; |
---|
167 | this.context = context; |
---|
168 | } |
---|
169 | |
---|
170 | @Override |
---|
171 | protected List<Uri> doInBackground(Uri... uris) { |
---|
172 | |
---|
173 | X509Certificate[] chain; |
---|
174 | X509Certificate certificate; |
---|
175 | PrivateKey key; |
---|
176 | KeyChainStrategy keyChain = KeyChainStrategy.getInstance(); |
---|
177 | |
---|
178 | try { |
---|
179 | chain = keyChain.getCertificateChain(this.activity.alias); |
---|
180 | certificate = chain[0]; |
---|
181 | key = keyChain.getPrivateKey(this.activity.alias); |
---|
182 | } catch (Exception e) { |
---|
183 | this.cancel(true); |
---|
184 | chain=null; |
---|
185 | key=null; |
---|
186 | certificate=null; |
---|
187 | throw new RuntimeException(e); |
---|
188 | } |
---|
189 | |
---|
190 | ArrayList<Uri> signed = new ArrayList<Uri>(uris.length); |
---|
191 | |
---|
192 | //NEW: History. |
---|
193 | ArrayList<String> sourcesPath = new ArrayList<String>(); |
---|
194 | ArrayList<String> destinationsPath = new ArrayList<String>(); |
---|
195 | |
---|
196 | Log.d("SignActivity:SignTask", "antes del for"); |
---|
197 | |
---|
198 | for (Uri uri : uris) { |
---|
199 | Uri signedUri = null; |
---|
200 | |
---|
201 | try { |
---|
202 | String inputFilename = uri.getPath(); |
---|
203 | if (this.activity.embedInPdf && FsUtils.isPDF(inputFilename)) { |
---|
204 | |
---|
205 | |
---|
206 | // ******************************************************************** |
---|
207 | Log.d("SignActivity", "antes de CryptoUtils.signPDF"); |
---|
208 | |
---|
209 | PdfReader reader = new PdfReader(inputFilename); |
---|
210 | |
---|
211 | Log.d("SignActivity", "new PdfReader"); |
---|
212 | |
---|
213 | int n; |
---|
214 | String targetFilename = new File(this.directory, uri.getLastPathSegment()).getPath(); |
---|
215 | if ((n = targetFilename.lastIndexOf(".")) > targetFilename.lastIndexOf("/")) { |
---|
216 | targetFilename = targetFilename.substring(0, n) + "-firma.pdf"; |
---|
217 | } else { |
---|
218 | targetFilename = targetFilename + "-firma.pdf"; |
---|
219 | } |
---|
220 | Log.d("SignActivity", "targetFilename: "+targetFilename); |
---|
221 | |
---|
222 | FileOutputStream fout = new FileOutputStream(targetFilename); |
---|
223 | |
---|
224 | PdfStamper stp = PdfStamper.createSignature(reader, fout, '?'); |
---|
225 | |
---|
226 | Log.d("SignActivity", "PdfStamper.createSignature"); |
---|
227 | |
---|
228 | PdfSignatureAppearance sap = stp.getSignatureAppearance(); |
---|
229 | |
---|
230 | Log.d("SignActivity", "stp.getSignatureAppearance()"); |
---|
231 | |
---|
232 | sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); |
---|
233 | |
---|
234 | Log.d("SignActivity", "sap.setCrypto"); |
---|
235 | |
---|
236 | sap.setReason("Firma PKCS12 Android"); |
---|
237 | |
---|
238 | Log.d("SignActivity", "sap.setReason"); |
---|
239 | |
---|
240 | sap.setLocation("Imaginanet"); |
---|
241 | |
---|
242 | Log.d("SignActivity", "sap.setLocation"); |
---|
243 | |
---|
244 | stp.close(); |
---|
245 | |
---|
246 | Log.d("SignActivity", "stp.close"); |
---|
247 | |
---|
248 | //signedUri = FsUtils.saveToFile(fout, targetFilename); |
---|
249 | File file = new File(targetFilename); |
---|
250 | signedUri = Uri.fromFile(file); |
---|
251 | |
---|
252 | // ******************************************************************** |
---|
253 | /* |
---|
254 | InputStream signedPDF = CryptoUtils.signPDF(new File(inputFilename), chain, key, this.context); |
---|
255 | int n; |
---|
256 | String targetFilename = new File(this.directory, uri.getLastPathSegment()).getPath(); |
---|
257 | if ((n = targetFilename.lastIndexOf(".")) > targetFilename.lastIndexOf("/")) { |
---|
258 | targetFilename = targetFilename.substring(0, n) + "-firma.pdf"; |
---|
259 | } else { |
---|
260 | targetFilename = targetFilename + "-firma.pdf"; |
---|
261 | } |
---|
262 | signedUri = FsUtils.saveToFile(signedPDF, targetFilename); |
---|
263 | */ |
---|
264 | |
---|
265 | //TODO: signedUri for uri |
---|
266 | signed.add(uri); |
---|
267 | |
---|
268 | this.activity.send.add(signedUri); |
---|
269 | } else { |
---|
270 | FsUtils.copyTo(new File(uri.getPath()), this.directory); |
---|
271 | |
---|
272 | |
---|
273 | Log.d("SignActivity", "antes de CryptoUtils.signPKCS7"); |
---|
274 | |
---|
275 | byte[] signature = CryptoUtils.signPKCS7(new File(inputFilename), certificate, key); |
---|
276 | int n; |
---|
277 | String targetFilename = new File(this.directory, uri.getLastPathSegment()).getPath(); |
---|
278 | if ((n = targetFilename.lastIndexOf(".")) > targetFilename.lastIndexOf("/")) { |
---|
279 | targetFilename = targetFilename.substring(0, n) + ".p7b"; |
---|
280 | } else { |
---|
281 | targetFilename = targetFilename + ".p7b"; |
---|
282 | } |
---|
283 | Log.d("SignActivity", "antes de signedUri"); |
---|
284 | signedUri = FsUtils.saveToFile(signature, targetFilename); |
---|
285 | signed.add(uri); |
---|
286 | this.activity.send.add(uri); |
---|
287 | this.activity.send.add(signedUri); |
---|
288 | Log.d("SignActivity", "despues de signedUri"); |
---|
289 | } |
---|
290 | } catch (FileAlreadyExistsException e) { |
---|
291 | final Activity act = ((Activity) this.context); |
---|
292 | Toast.makeText(act, act.getString(R.string.errorServerNotReachable), Toast.LENGTH_SHORT).show(); |
---|
293 | |
---|
294 | //} catch (DocumentWritingException e) { |
---|
295 | |
---|
296 | } catch (ClientHandlerException e){ |
---|
297 | final Activity act = ((Activity) this.context); |
---|
298 | act.runOnUiThread(new Runnable() { |
---|
299 | public void run() { |
---|
300 | Toast.makeText(act, act.getString(R.string.errorServerNotReachable), Toast.LENGTH_SHORT).show(); |
---|
301 | } |
---|
302 | }); |
---|
303 | } catch (UniformInterfaceException e) { |
---|
304 | final Activity act = ((Activity) this.context); |
---|
305 | act.runOnUiThread(new Runnable() { |
---|
306 | public void run() { |
---|
307 | Toast.makeText(act, act.getString(R.string.errorConnection), Toast.LENGTH_SHORT).show(); |
---|
308 | } |
---|
309 | }); |
---|
310 | } catch (InvalidPdfException e) { |
---|
311 | //empty |
---|
312 | } catch (Exception e) { |
---|
313 | final Activity act = ((Activity) this.context); |
---|
314 | Toast.makeText(act, "exception", Toast.LENGTH_SHORT).show(); |
---|
315 | FsUtils.checkOutOfSpace(e, true); |
---|
316 | this.cancel(true); |
---|
317 | //throw new RuntimeException(e); |
---|
318 | } |
---|
319 | |
---|
320 | |
---|
321 | //HISTORY: |
---|
322 | //Fixed spaces path error with getPath instead of getEncodedPath |
---|
323 | finally{ |
---|
324 | sourcesPath.add(uri.getPath()); |
---|
325 | if (signedUri!=null) |
---|
326 | destinationsPath.add(signedUri.getPath()); |
---|
327 | else |
---|
328 | destinationsPath.add(""); |
---|
329 | |
---|
330 | |
---|
331 | } |
---|
332 | } |
---|
333 | |
---|
334 | |
---|
335 | // DIR Save history.mbs |
---|
336 | String[] pathSplit = this.directory.split("/"); |
---|
337 | String dirName = pathSplit[pathSplit.length-1]; |
---|
338 | File targetHistory = new File(this.directory, dirName); |
---|
339 | |
---|
340 | //File targetHistory = new File(this.directory, "history.mbs"); |
---|
341 | |
---|
342 | String alias = this.activity.alias; |
---|
343 | // this.saveHistoryData(alias, CertificateUtils.getSubject(chain[0]), |
---|
344 | // CertificateUtils.getSerial(chain[0]), |
---|
345 | // CertificateUtils.getIssuer(chain[0]),sourcesPath, destinationsPath, targetHistory); |
---|
346 | //---------- |
---|
347 | |
---|
348 | |
---|
349 | return signed; |
---|
350 | } |
---|
351 | |
---|
352 | |
---|
353 | |
---|
354 | |
---|
355 | |
---|
356 | |
---|
357 | @Override |
---|
358 | protected void onPostExecute(List<Uri> signed) { |
---|
359 | |
---|
360 | if (this.activity != null) { |
---|
361 | if (getError() != null) { |
---|
362 | if (getError().getCause() instanceof OutOfSpaceError) { |
---|
363 | this.activity.viewHolder.outOfSpaceError(); |
---|
364 | } else { |
---|
365 | this.activity.viewHolder.unknownError(); |
---|
366 | } |
---|
367 | return; |
---|
368 | } |
---|
369 | this.activity.signed = signed; |
---|
370 | if (signed.size() < this.activity.uris.size()) { |
---|
371 | this.activity.unsigned = new ArrayList<Uri>(this.activity.uris); |
---|
372 | this.activity.unsigned.removeAll(signed); |
---|
373 | |
---|
374 | } |
---|
375 | this.activity.viewHolder.update(); |
---|
376 | |
---|
377 | } |
---|
378 | } |
---|
379 | |
---|
380 | |
---|
381 | // private void saveHistoryData(String alias, String subject, String serial, String issuer, List<String> files, |
---|
382 | // ArrayList<String> unsigned, File path) { |
---|
383 | // |
---|
384 | // |
---|
385 | // HistoryData data = new HistoryData (alias, subject, serial, issuer, files, unsigned); |
---|
386 | // |
---|
387 | // ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
---|
388 | // try{ |
---|
389 | // ObjectOutputStream oos = new ObjectOutputStream(baos); |
---|
390 | // oos.writeObject(data); |
---|
391 | // oos.flush(); |
---|
392 | // oos.close(); |
---|
393 | // }catch(IOException e){} |
---|
394 | // InputStream is = new ByteArrayInputStream(baos.toByteArray()); |
---|
395 | // |
---|
396 | // try { |
---|
397 | // FsUtils.saveToFile(is, path.getPath()); |
---|
398 | // } catch (Exception e){} |
---|
399 | // |
---|
400 | // |
---|
401 | // } |
---|
402 | |
---|
403 | |
---|
404 | } |
---|
405 | |
---|
406 | private class SignView { |
---|
407 | |
---|
408 | public LinearLayout finish; |
---|
409 | public LinearLayout share; |
---|
410 | public TextView summary; |
---|
411 | public TextView summary2; |
---|
412 | public View signing; |
---|
413 | |
---|
414 | public SignView () { |
---|
415 | setContentView(R.layout.sign); |
---|
416 | |
---|
417 | this.finish = (LinearLayout) findViewById(R.id.button_finish_zone); |
---|
418 | this.finish.setOnClickListener(SignActivity.this); |
---|
419 | |
---|
420 | this.share = (LinearLayout) findViewById(R.id.button_share_zone); |
---|
421 | this.share.setOnClickListener(SignActivity.this); |
---|
422 | |
---|
423 | this.summary = (TextView) findViewById(R.id.summary); |
---|
424 | this.summary.setMovementMethod(new ScrollingMovementMethod()); |
---|
425 | this.summary2 = (TextView) findViewById(R.id.summary2); |
---|
426 | this.summary2.setMovementMethod(new ScrollingMovementMethod()); |
---|
427 | |
---|
428 | this.signing = findViewById(R.id.signing); |
---|
429 | } |
---|
430 | |
---|
431 | public void noStorageError() { |
---|
432 | |
---|
433 | this.summary.setText(R.string.no_storage); |
---|
434 | this.signing.setVisibility(View.GONE); |
---|
435 | } |
---|
436 | |
---|
437 | public void outOfSpaceError() { |
---|
438 | |
---|
439 | this.summary.setText(R.string.error_no_space); |
---|
440 | this.signing.setVisibility(View.GONE); |
---|
441 | } |
---|
442 | |
---|
443 | public void unknownError() { |
---|
444 | |
---|
445 | this.summary.setText(R.string.error_unknown); |
---|
446 | this.signing.setVisibility(View.GONE); |
---|
447 | } |
---|
448 | |
---|
449 | public void update() { |
---|
450 | |
---|
451 | StringBuilder builder = new StringBuilder(); |
---|
452 | StringBuilder builder2 = new StringBuilder(); |
---|
453 | Resources res = SignActivity.this.getResources(); |
---|
454 | |
---|
455 | //Fix Error #75235 |
---|
456 | if (SignActivity.this.signed != null && !SignActivity.this.signed.isEmpty()) { |
---|
457 | // builder.append(res.getString(R.string.signedfiles)); |
---|
458 | for (Uri file : SignActivity.this.signed) { |
---|
459 | builder.append("\n - "); |
---|
460 | builder.append(file.getLastPathSegment()); |
---|
461 | } |
---|
462 | // builder.append("\n\n"); |
---|
463 | } |
---|
464 | if (SignActivity.this.unsigned != null && !SignActivity.this.unsigned.isEmpty()) { |
---|
465 | |
---|
466 | builder2.append(res.getString(R.string.unsigned2)); |
---|
467 | for (Uri file : SignActivity.this.unsigned) { |
---|
468 | builder2.append("\n - "); |
---|
469 | builder2.append(file.getLastPathSegment()); |
---|
470 | } |
---|
471 | |
---|
472 | |
---|
473 | } |
---|
474 | |
---|
475 | this.summary.setText(builder); |
---|
476 | this.summary2.setText(builder2); |
---|
477 | done(); |
---|
478 | } |
---|
479 | |
---|
480 | public void done() { |
---|
481 | |
---|
482 | this.signing.setVisibility(View.GONE); |
---|
483 | this.share.setEnabled(true); |
---|
484 | } |
---|
485 | } |
---|
486 | } |
---|