KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SnowMailClient > gnupg > Main > GnuPGCommands


1 package SnowMailClient.gnupg.Main;
2
3 import java.util.*;
4 import java.io.*;
5 import javax.swing.*;
6 import javax.swing.event.*;
7 import javax.swing.border.*;
8 import java.awt.*;
9 import java.awt.event.*;
10
11 import SnowMailClient.utils.*;
12
13 import snow.utils.gui.*;
14 import snow.crypto.*;
15 import snow.concurrent.*;
16
17 import SnowMailClient.utils.storage.*;
18 import SnowMailClient.gnupg.LineProcessors.*;
19 import SnowMailClient.gnupg.model.*;
20 import SnowMailClient.crypto.*;
21 import SnowMailClient.Language.Language;
22
23
24 /** Here are all the commands that call gpg.exe and gobbles the in & out streams
25 */

26 public final class GnuPGCommands
27 {
28
29   private GnuPGCommands()
30   {
31
32   } // Constructor
33

34   /** read all the public keys present in the gpg installation
35   */

36   public static Vector<GnuPGKeyID> readPublicKeyIDs(String JavaDoc pathToGPG) throws Exception JavaDoc
37   {
38     if(!new File(pathToGPG).exists()) throw new Exception JavaDoc(Language.translate("GnuPG path invalid"));
39     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{pathToGPG, "--no-greeting", "--with-fingerprint", "--fixed-list-mode", "--with-colons", "--list-public-keys"});
40
41     // forget errors
42
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
43     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
44     errGobbler.start();
45
46     KeyIDReader keyIDLineProcessor = new KeyIDReader();
47     StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), keyIDLineProcessor);
48     inGobbler.start();
49
50     int rep = p.waitFor();
51     try
52     {
53       inGobbler.join(5000);
54     } catch(Exception JavaDoc e) {}
55
56     try
57     {
58       errGobbler.join(5000);
59     } catch(Exception JavaDoc e) {}
60
61     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
62
63     return keyIDLineProcessor.getKeyIDs();
64   }
65
66
67   public static Vector<GnuPGKeyID> readSecretKeyIDs(String JavaDoc pathToGPG) throws Exception JavaDoc
68   {
69     if(!new File(pathToGPG).exists()) throw new Exception JavaDoc(Language.translate("GnuPG path invalid"));
70     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{pathToGPG, "--no-greeting", "--with-fingerprint", "--fixed-list-mode", "--with-colons", "--list-secret-keys"});
71
72     // forget errors
73
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
74     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
75     errGobbler.start();
76
77     KeyIDReader keyIDLineProcessor = new KeyIDReader();
78     StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), keyIDLineProcessor);
79     inGobbler.start();
80
81     int rep = p.waitFor();
82
83     try
84     {
85       inGobbler.join(5000);
86     } catch(Exception JavaDoc e) {}
87
88     try
89     {
90       errGobbler.join(5000);
91     } catch(Exception JavaDoc e) {}
92
93     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
94
95     return keyIDLineProcessor.getKeyIDs();
96   }
97
98   /** read version of gpg (1.2.2, 1.4.0, ...)
99   */

100   public static String JavaDoc readGPGVersion(String JavaDoc pathToGPG) throws Exception JavaDoc
101   {
102     if(!new File(pathToGPG).exists()) throw new Exception JavaDoc(Language.translate("GnuPG path invalid"));
103     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{pathToGPG, "--version"});
104
105     // forget errors
106
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
107     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
108     errGobbler.start();
109
110     VersionLineProcessor vlp = new VersionLineProcessor();
111     StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), vlp);
112     inGobbler.start();
113
114     int rep = p.waitFor();
115
116     try
117     {
118       inGobbler.join(5000);
119     } catch(Exception JavaDoc e) {}
120
121     try
122     {
123       errGobbler.join(5000);
124     } catch(Exception JavaDoc e) {}
125
126     //CAUTION, in 1.4, some DLL are not read...
127
if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
128
129     // vlp.getCompleteVersionDescription();
130

131     return vlp.getVersion(); // only the first line
132
}
133
134
135
136   /** encrypt for a given recipient
137   */

138   public static String JavaDoc encryptBufferForRecipient(
139                            String JavaDoc pathToGPG,
140                            String JavaDoc message,
141                            GnuPGKeyID keyID,
142                            boolean ascii,
143                            Interrupter interrupter) throws Exception JavaDoc
144   {
145     //System.out.println("Encrypting for "+keyID.getKeyID());
146

147     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
148        pathToGPG, "-e"+(ascii?"a":""),
149        "--quiet", "--yes", "--batch", "--no-greeting",
150        "--trust-model", "always", // :-(
151
"-r", keyID.getFingerprint()
152     });
153
154     if(interrupter!=null)
155     {
156       interrupter.setProcessToOptionalKill(p);
157     }
158
159
160     // forget errors
161
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
162     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
163     errGobbler.start();
164
165     ByteArrayOutputStream bos = new ByteArrayOutputStream();
166     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
167     inGobbler.start();
168
169     // write message
170
ByteArrayInputStream bin = new ByteArrayInputStream(message.getBytes());
171     byte[] buf = new byte[256];
172     int read =-1;
173     while(( read=bin.read(buf))!=-1)
174     {
175        p.getOutputStream().write(buf,0,read);
176     }
177
178     // EOF
179
try
180     {
181       p.getOutputStream().flush();
182       p.getOutputStream().close();
183     }
184     catch(Exception JavaDoc ignored) {}
185
186     int rep = p.waitFor();
187
188     try
189     {
190       inGobbler.join(5000);
191     } catch(Exception JavaDoc e) {}
192
193     try
194     {
195       errGobbler.join(5000);
196     } catch(Exception JavaDoc e) {}
197
198     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
199     /* occurs often when trust not set !
200      GPG Error stream: gpg: DAB17279: There is no assurance this key belongs to the named user
201      GPG Error stream: gpg: [stdin]: encryption failed: unusable public key
202     */

203     if(errorProcessor.hasText("failed")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
204
205     return new String JavaDoc(bos.toByteArray());
206   }
207
208
209   public static boolean verifySecretKeyPassword(String JavaDoc pathToGPG, GnuPGKeyID keyID, byte[] pass) throws Exception JavaDoc
210   {
211      try
212      {
213        ByteArrayInputStream bin = new ByteArrayInputStream("Hello this is a test".getBytes());
214        byte[] result = signBuffer(pathToGPG, bin, keyID, pass, null);
215        if(result==null) return false;
216
217        return true;
218      }
219      catch(BadPasswordException be)
220      {
221        return false;
222      }
223      catch(Exception JavaDoc e)
224      {
225        throw e;
226      }
227   }
228
229
230
231   /** sign a message with the key.
232      This appends a clear text signature that wraps the original clear text.
233      CAUTION: The text is NOT enciphered
234   */

235   public static byte[] signBuffer(String JavaDoc pathToGPG, ByteArrayInputStream bin, GnuPGKeyID keyID, byte[] pass, Interrupter interrupter
236      ) throws Exception JavaDoc
237   {
238     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
239        pathToGPG, "--clearsign", "--sign", "-a",
240        "--quiet", "--yes", "--no-greeting",
241        "-u", "\""+keyID.getKeyID()+"\"",
242        "--passphrase-fd", "0" // give password in stdin
243
});
244
245     if(interrupter!=null) interrupter.setProcessToOptionalKill(p);
246
247     ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
248     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
249     errGobbler.start();
250
251     ByteArrayOutputStream bos = new ByteArrayOutputStream();
252     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
253     inGobbler.start();
254
255     // give password in stdin
256
p.getOutputStream().write(pass);
257     p.getOutputStream().write((byte)'\n');
258     p.getOutputStream().flush();
259
260     // write message
261
byte[] buf = new byte[256];
262     int read =-1;
263     while(( read=bin.read(buf))!=-1)
264     {
265        p.getOutputStream().write(buf,0,read);
266     }
267
268     // EOF
269
p.getOutputStream().flush();
270     p.getOutputStream().close();
271
272     int rep = p.waitFor();
273
274     try
275     {
276       inGobbler.join(5000);
277     } catch(Exception JavaDoc e) {}
278
279     try
280     {
281       errGobbler.join(5000);
282     } catch(Exception JavaDoc e) {}
283
284     if(errorProcessor.hasText("bad passphrase"))
285     {
286       throw new BadPasswordException(Language.translate("Bad passphrase for %",keyID.getKeyID()));
287     }
288
289     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
290
291     return bos.toByteArray();
292   }
293
294   /** @throws Exception
295   *
296   public static Vector<SignatureVerificationResult> decryptMessage(String pathToGPG, InputStream signedMessage) throws Exception
297   {
298     Process p = Runtime.getRuntime().exec(new String[]{
299        pathToGPG, "--quiet", "--decrypt"});
300
301     return null;
302   }*/

303
304
305   /** @throws Exception
306   */

307   public static Vector<SignatureVerificationResult> verifySignature(
308                                 String JavaDoc pathToGPG, InputStream signedMessage,
309                                 ProgressModalDialog progress) throws Exception JavaDoc
310   {
311     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
312        pathToGPG, "--no-greeting", "--quiet", "--batch", "--fixed-list-mode", "--with-colons", "--verify",});
313
314     if(progress!=null) progress.setProcessToOptionalKill(p);
315
316     // the signature verify occurs on the error stream !!
317

318     ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
319     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
320     errGobbler.start();
321
322     ByteArrayOutputStream bos = new ByteArrayOutputStream();
323     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
324     inGobbler.start();
325
326     // write message
327
byte[] buf = new byte[256];
328     int read =-1;
329     while(( read=signedMessage.read(buf))!=-1)
330     {
331        p.getOutputStream().write( buf, 0, read);
332     }
333
334     // EOF
335
p.getOutputStream().flush();
336     p.getOutputStream().close();
337
338     int rep = p.waitFor();
339
340     try
341     {
342       inGobbler.join(5000);
343     } catch(Exception JavaDoc e) {}
344
345     try
346     {
347       errGobbler.join(5000);
348     } catch(Exception JavaDoc e) {}
349
350     // ok, whole process & read terminated.
351
// let us analyse the output now
352
Vector<SignatureVerificationResult> signatures = parseSignaturesFromOutput(errorProcessor.getAllErrorMessage());
353
354     if(errorProcessor.hasText("invalid")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
355     if(errorProcessor.hasText("CRC error")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
356
357     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
358
359     return signatures;
360   }
361
362
363   private static Vector<SignatureVerificationResult> parseSignaturesFromOutput(String JavaDoc text) throws Exception JavaDoc
364   {
365      System.out.println("\n========= Parse signature verif from ========\n"+text+"\n\n");
366      BufferedReader br = new BufferedReader(new StringReader(text));
367      Vector<SignatureVerificationResult> signatures = new Vector<SignatureVerificationResult>();
368
369      SignatureVerificationResult actual = null;
370      String JavaDoc line = null;
371      while((line = br.readLine())!=null)
372      {
373        if(line.indexOf("Signature made")>=0)
374        {
375          // this is the start of a new signature result
376
if(actual!=null) signatures.addElement(actual);
377          actual = new SignatureVerificationResult();
378          actual.parseLine(line);
379        }
380        else
381        {
382          if(actual!=null) actual.parseLine(line);
383        }
384      }
385
386      if(actual!=null) signatures.addElement(actual);
387
388      return signatures;
389   }
390
391
392   /** decrypt for a given recipient
393   */

394   public static String JavaDoc decryptBufferForRecipient(String JavaDoc pathToGPG,
395                   String JavaDoc encryptedMessage, GnuPGKeyID keyID, byte[] pass,
396                   ProgressModalDialog progress) throws Exception JavaDoc
397   {
398     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
399        pathToGPG,
400        //"--quiet", "--yes",
401
"--no-greeting",
402        "--passphrase-fd", "0", //, // give password in stdin
403
//"-r", "\""+keyID.getKeyID()+"\""
404
"--decrypt"
405     });
406
407     if(progress!=null)
408     {
409       progress.setProcessToOptionalKill(p);
410     }
411
412     ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
413     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
414     errGobbler.start();
415
416     ByteArrayOutputStream bos = new ByteArrayOutputStream();
417     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
418     inGobbler.start();
419
420     // give password in stdin
421
p.getOutputStream().write(pass);
422     p.getOutputStream().write((byte)'\n');
423     p.getOutputStream().flush();
424
425     // write message
426
ByteArrayInputStream bin = new ByteArrayInputStream(encryptedMessage.getBytes());
427     byte[] buf = new byte[256];
428     int read =-1;
429     while(( read=bin.read(buf))!=-1)
430     {
431        p.getOutputStream().write(buf,0,read);
432     }
433
434     // EOF
435
p.getOutputStream().flush();
436     p.getOutputStream().close();
437
438     int rep = p.waitFor();
439
440     try
441     {
442       inGobbler.join(5000);
443     } catch(Exception JavaDoc e) {}
444
445     try
446     {
447       errGobbler.join(5000);
448     } catch(Exception JavaDoc e) {}
449
450     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
451     if(errorProcessor.hasText("failed")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
452
453     return new String JavaDoc(bos.toByteArray());
454   }
455
456
457   /** set the trust
458   1 = I don't know or won't say
459   2 = I do NOT trust
460   3 = I trust marginally
461   4 = I trust fully
462   5 = I trust ultimately
463   */

464   public static void setTrust(String JavaDoc pathToGPG,
465                   GnuPGKeyID keyID, int newTrust,
466                   ProgressModalDialog progress) throws Exception JavaDoc
467   {
468     System.out.println("Set trust to "+newTrust+" for "+keyID.getMails());
469
470     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
471        pathToGPG, "--yes", "--yes",
472        "--no-comments", "--no-greeting",
473        "--command-fd", "0",
474        "--edit-key", keyID.getFingerprint()
475     });
476
477     if(progress!=null)
478     {
479       progress.setProcessToOptionalKill(p);
480     }
481
482     ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
483     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
484     errGobbler.start();
485
486     ByteArrayOutputStream bos = new ByteArrayOutputStream();
487     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
488     inGobbler.start();
489
490
491     // write trust
492
p.getOutputStream().write("trust".getBytes());
493     p.getOutputStream().write((byte)'\n');
494     p.getOutputStream().flush();
495
496     p.getOutputStream().write((""+newTrust).getBytes());
497     p.getOutputStream().write((byte)'\n');
498     p.getOutputStream().flush();
499
500     if(newTrust==5)
501     {
502       p.getOutputStream().write("y".getBytes());
503       p.getOutputStream().write((byte)'\n');
504       p.getOutputStream().flush();
505     }
506
507     p.getOutputStream().write("save".getBytes());
508     p.getOutputStream().write((byte)'\n');
509     p.getOutputStream().flush();
510
511     p.getOutputStream().close();
512
513     int rep = p.waitFor();
514
515     try
516     {
517       inGobbler.join(5000);
518     } catch(Exception JavaDoc e) {}
519
520     try
521     {
522       errGobbler.join(5000);
523     } catch(Exception JavaDoc e) {}
524
525
526     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
527     if(errorProcessor.hasText("failed")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
528
529     System.out.println("SetTrust err message="+errorProcessor.getAllErrorMessage());
530     System.out.println("SetTrust response="+new String JavaDoc(bos.toByteArray()));
531
532   }
533
534   /** finds out which key is needed to decrypt the message
535       try to decrypt with a false password and analyse the result.
536       @return {name, ID}
537   */

538   public static String JavaDoc[] determineUsedKey(String JavaDoc pathToGPG,
539                   String JavaDoc encryptedMessage,
540                   ProgressModalDialog progress) throws Exception JavaDoc
541   {
542     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
543        pathToGPG,
544        //"--quiet", "--yes",
545
"--no-greeting",
546        "--passphrase-fd", "0", // give password in stdin
547
"--decrypt"
548     });
549
550     if(progress!=null)
551     {
552       progress.setProcessToOptionalKill(p);
553     }
554
555     ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
556     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
557     errGobbler.start();
558
559     ByteArrayOutputStream bos = new ByteArrayOutputStream();
560     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
561     inGobbler.start();
562
563     // give password in stdin
564
p.getOutputStream().write("---------------------------ç*@\n".getBytes()); // surely false
565
p.getOutputStream().flush();
566
567     // write message
568
ByteArrayInputStream bin = new ByteArrayInputStream(encryptedMessage.getBytes());
569     byte[] buf = new byte[256];
570     int read =-1;
571     while(( read=bin.read(buf))!=-1)
572     {
573        p.getOutputStream().write(buf,0,read);
574     }
575
576     // EOF
577
p.getOutputStream().flush();
578     p.getOutputStream().close();
579
580     int rep = p.waitFor();
581
582     try
583     {
584       inGobbler.join(5000);
585     } catch(Exception JavaDoc e) {}
586
587     try
588     {
589       errGobbler.join(5000);
590     } catch(Exception JavaDoc e) {}
591
592     // if(errorProcessor.hasError()) throw new Exception(errorProcessor.getAllErrorMessage());
593
// if(errorProcessor.hasText("failed")) throw new Exception(errorProcessor.getAllErrorMessage());
594
String JavaDoc erm = errorProcessor.getAllErrorMessage();// + new String(bos.toByteArray());
595
int pos = erm.indexOf("ID ");
596     if(pos==-1) throw new Exception JavaDoc(Language.translate("Cannot find key ID in")+erm);
597     int posEnd=erm.indexOf(",", pos+3);
598     String JavaDoc ID = erm.substring(pos+3,posEnd);
599 // System.out.println("ERM="+erm);
600

601     pos = erm.indexOf(" \"");
602     if(pos==-1) throw new Exception JavaDoc(Language.translate("Cannot find key name in")+erm);
603     posEnd=erm.indexOf("\"", pos+3);
604     String JavaDoc name = erm.substring(pos+3,posEnd);
605
606     return new String JavaDoc[]{ID, name};
607   }
608
609
610   public static String JavaDoc getPublicKey(String JavaDoc pathToGPG, GnuPGKeyID id) throws Exception JavaDoc
611   {
612     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
613        pathToGPG, "--armor", "--export", id.getKeyID()
614     });
615
616
617     // forget errors
618
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
619     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
620     errGobbler.start();
621
622     ByteArrayOutputStream bos = new ByteArrayOutputStream();
623     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
624     inGobbler.start();
625
626     int rep = p.waitFor();
627     try
628     {
629       inGobbler.join(5000);
630     } catch(Exception JavaDoc e) {}
631
632     try
633     {
634       errGobbler.join(5000);
635     } catch(Exception JavaDoc e) {}
636
637     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
638     if(errorProcessor.hasText("warning")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
639
640     return new String JavaDoc(bos.toByteArray());
641   }
642
643
644   public static String JavaDoc getSecretKey(String JavaDoc pathToGPG, GnuPGKeyID id) throws Exception JavaDoc
645   {
646     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
647        pathToGPG, "--armor", "--export-secret-keys", id.getKeyID()
648     });
649
650
651     // forget errors
652
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
653     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
654     errGobbler.start();
655
656     ByteArrayOutputStream bos = new ByteArrayOutputStream();
657     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
658     inGobbler.start();
659
660     int rep = p.waitFor();
661     try
662     {
663       inGobbler.join(5000);
664     } catch(Exception JavaDoc e) {}
665
666     try
667     {
668       errGobbler.join(5000);
669     } catch(Exception JavaDoc e) {}
670
671     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
672
673     return new String JavaDoc(bos.toByteArray());
674   }
675
676
677   public static void addKey(String JavaDoc pathToGPG, String JavaDoc asciikey) throws Exception JavaDoc
678   {
679     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
680        pathToGPG, "--batch", "--quiet", "--yes", "--import"
681     });
682
683
684     // forget errors
685
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
686     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
687     errGobbler.start();
688
689     ByteArrayOutputStream bos = new ByteArrayOutputStream();
690     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
691     inGobbler.start();
692
693     // write key
694
p.getOutputStream().write(asciikey.getBytes());
695     p.getOutputStream().write("\r\n".getBytes());
696     // EOF
697
p.getOutputStream().flush();
698     p.getOutputStream().close();
699
700
701     int rep = p.waitFor();
702     try
703     {
704       inGobbler.join(5000);
705     } catch(Exception JavaDoc e) {}
706
707     try
708     {
709       errGobbler.join(5000);
710     } catch(Exception JavaDoc e) {}
711
712     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
713
714     System.out.println("in: "+new String JavaDoc(bos.toByteArray()));
715   }
716
717   public static void removePublicKey(String JavaDoc pathToGPG, GnuPGKeyID id) throws Exception JavaDoc
718   {
719     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
720         pathToGPG, "--yes", "--batch", "--delete-key", id.getFingerprint().replaceAll(" ", "")});
721
722     // errors
723
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
724     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
725     errGobbler.start();
726
727     // output
728
SimpleLineProcessor simpleLineProcessor = new SimpleLineProcessor("Out: ");
729     StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), simpleLineProcessor);
730     inGobbler.start();
731
732     int rep = p.waitFor();
733
734     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
735     if(errorProcessor.hasText("failed")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
736
737   }
738
739
740   public static void removePublicAndPrivateKey(String JavaDoc pathToGPG, GnuPGKeyID id) throws Exception JavaDoc
741   {
742     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
743         pathToGPG, "--no-greeting", "--yes", "--batch", "--delete-secret-and-public-key", id.getFingerprint().replaceAll(" ", "")});
744
745     // errors
746
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
747     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
748     errGobbler.start();
749
750     // output
751
SimpleLineProcessor simpleLineProcessor = new SimpleLineProcessor("Out: ");
752     StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), simpleLineProcessor);
753     inGobbler.start();
754
755     int rep = p.waitFor();
756     try
757     {
758       inGobbler.join(5000);
759     } catch(Exception JavaDoc e) {}
760
761     try
762     {
763       errGobbler.join(5000);
764     } catch(Exception JavaDoc e) {}
765
766     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
767     if(errorProcessor.hasText("failed")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
768
769   }
770
771   /* WARNING: use an experimental feature of 1.4.0
772 Unattended key generation
773 =========================
774 This feature allows unattended generation of keys controlled by a
775 parameter file. To use this feature, you use --gen-key together with
776 --batch and feed the parameters either from stdin or from a file given
777 on the commandline.
778
779 The format of this file is as follows:
780   o Text only, line length is limited to about 1000 chars.
781   o You must use UTF-8 encoding to specify non-ascii characters.
782   o Empty lines are ignored.
783   o Leading and trailing spaces are ignored.
784   o A hash sign as the first non white space character indicates a comment line.
785   o Control statements are indicated by a leading percent sign, the
786     arguments are separated by white space from the keyword.
787   o Parameters are specified by a keyword, followed by a colon. Arguments
788     are separated by white space.
789   o The first parameter must be "Key-Type", control statements
790     may be placed anywhere.
791   o Key generation takes place when either the end of the parameter file
792     is reached, the next "Key-Type" parameter is encountered or at the
793     control statement "%commit"
794   o Control statements:
795     %echo <text>
796     Print <text>.
797     %dry-run
798     Suppress actual key generation (useful for syntax checking).
799     %commit
800     Perform the key generation. An implicit commit is done
801     at the next "Key-Type" parameter.
802     %pubring <filename>
803     %secring <filename>
804     Do not write the key to the default or commandline given
805     keyring but to <filename>. This must be given before the first
806     commit to take place, duplicate specification of the same filename
807     is ignored, the last filename before a commit is used.
808     The filename is used until a new filename is used (at commit points)
809     and all keys are written to that file. If a new filename is given,
810     this file is created (and overwrites an existing one).
811     Both control statements must be given.
812    o The order of the parameters does not matter except for "Key-Type"
813      which must be the first parameter. The parameters are only for the
814      generated keyblock and parameters from previous key generations are not
815      used. Some syntactically checks may be performed.
816      The currently defined parameters are:
817      Key-Type: <algo-number>|<algo-string>
818     Starts a new parameter block by giving the type of the
819     primary key. The algorithm must be capable of signing.
820     This is a required parameter.
821      Key-Length: <length-in-bits>
822     Length of the key in bits. Default is 1024.
823      Key-Usage: <usage-list>
824         Space or comma delimited list of key usage, allowed values are
825         "encrypt" and "sign". This is used to generate the key flags.
826         Please make sure that the algorithm is capable of this usage.
827      Subkey-Type: <algo-number>|<algo-string>
828     This generates a secondary key. Currently only one subkey
829     can be handled.
830      Subkey-Length: <length-in-bits>
831     Length of the subkey in bits. Default is 1024.
832      Subkey-Usage: <usage-list>
833         Similar to Key-Usage.
834      Passphrase: <string>
835     If you want to specify a passphrase for the secret key,
836     enter it here. Default is not to use any passphrase.
837      Name-Real: <string>
838      Name-Comment: <string>
839      Name-Email: <string>
840     The 3 parts of a key. Remember to use UTF-8 here.
841     If you don't give any of them, no user ID is created.
842      Expire-Date: <iso-date>|(<number>[d|w|m|y])
843     Set the expiration date for the key (and the subkey). It
844     may either be entered in ISO date format (2000-08-15) or as
845     number of days, weeks, month or years. Without a letter days
846     are assumed.
847      Preferences: <string>
848         Set the cipher, hash, and compression preference values for
849     this key. This expects the same type of string as "setpref"
850     in the --edit menu.
851      Revoker: <algo>:<fpr> [sensitive]
852         Add a designated revoker to the generated key. Algo is the
853     public key algorithm of the designated revoker (i.e. RSA=1,
854     DSA=17, etc.) Fpr is the fingerprint of the designated
855     revoker. The optional "sensitive" flag marks the designated
856     revoker as sensitive information. Only v4 keys may be
857     designated revokers.
858      Handle: <string>
859         This is an optional parameter only used with the status lines
860         KEY_CREATED and KEY_NOT_CREATED. STRING may be up to 100
861         characters and should not contauin spaces. It is useful for
862         batch key generation to associate a key parameter block with a
863         status line.
864
865
866 Here is an example:
867 $ cat >foo <<EOF
868      %echo Generating a standard key
869      Key-Type: DSA
870      Key-Length: 1024
871      Subkey-Type: ELG-E
872      Subkey-Length: 1024
873      Name-Real: Joe Tester
874      Name-Comment: with stupid passphrase
875      Name-Email: joe@foo.bar
876      Expire-Date: 0
877      Passphrase: abc
878      %pubring foo.pub
879      %secring foo.sec
880      # Do a commit here, so that we can later print "done" :-)
881      %commit
882      %echo done
883 EOF
884 $ gpg --batch --gen-key foo
885  [...]
886 $ gpg --no-default-keyring --secret-keyring ./foo.sec \
887                   --keyring ./foo.pub --list-secret-keys
888 /home/wk/work/gnupg-stable/scratch/foo.sec
889 ------------------------------------------
890 sec 1024D/915A878D 2000-03-09 Joe Tester (with stupid passphrase) <joe@foo.bar>
891 ssb 1024g/8F70E2C0 2000-03-09
892
893   */

894
895   /** WARNING: use an experimental feature of 1.4.0
896   */

897   public static void generateNew_DSA_ElG_KeyPair(String JavaDoc pathToGPG,
898      String JavaDoc nameReal, String JavaDoc nameComment, String JavaDoc nameEmail, String JavaDoc passphrase, String JavaDoc elgKeyLength, String JavaDoc expires,
899      ProgressModalDialog progress) throws Exception JavaDoc
900   {
901     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
902         pathToGPG, "--batch", "--gen-key"});
903
904     if(progress!=null)
905       progress.setProcessToOptionalKill(p);
906
907     // forget errors
908
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
909     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
910     errGobbler.start();
911
912     ByteArrayOutputStream bos = new ByteArrayOutputStream();
913     StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
914     inGobbler.start();
915
916     // write batch arguments
917
//p.getOutputStream().write("%echo Start".getBytes());
918
p.getOutputStream().write(("Key-Type: DSA").getBytes());
919     p.getOutputStream().write(("\r\nKey-Length: 1024").getBytes()); // DSA have fixed 1024
920
p.getOutputStream().write( "\r\nSubkey-Type: ELG-E".getBytes());
921     p.getOutputStream().write(("\r\nSubkey-Length: "+elgKeyLength).getBytes()); // Elg-e: 1024-4096
922

923     p.getOutputStream().write(("\r\nName-Real: " +nameReal).getBytes());
924     p.getOutputStream().write(("\r\nName-Comment: "+nameComment).getBytes());
925     p.getOutputStream().write(("\r\nName-Email: " +nameEmail).getBytes());
926
927     p.getOutputStream().write(("\r\nExpire-Date: "+expires).getBytes());
928     p.getOutputStream().write(("\r\nPassphrase: "+passphrase).getBytes());
929 // p.getOutputStream().write("\r\n%commit".getBytes());
930
// p.getOutputStream().write("\r\n%echo done #*ç!?@;,!".getBytes());
931

932     // EOF
933
p.getOutputStream().flush();
934     p.getOutputStream().close();
935
936
937     int rep = p.waitFor();
938     try
939     {
940       inGobbler.join(5000);
941     } catch(Exception JavaDoc e) {}
942
943     try
944     {
945       errGobbler.join(5000);
946     } catch(Exception JavaDoc e) {}
947
948     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
949     if(errorProcessor.hasText("invalid")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
950     if(errorProcessor.hasText("missing")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
951   }
952
953
954   public static void sendPublicKey(String JavaDoc pathToGPG, GnuPGKeyID id, ProgressModalDialog progress) throws Exception JavaDoc
955   {
956     Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
957
958         pathToGPG,
959          "--no-greeting",
960         //"--yes", "--batch",
961
"--send-keys",
962          "--keyserver", "subkeys.pgp.net",
963          id.getFingerprint().replaceAll(" ", "")});
964
965     if(progress!=null)
966       progress.setProcessToOptionalKill(p);
967
968     // errors
969
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
970     StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
971     errGobbler.start();
972
973     // output
974
SimpleLineProcessor simpleLineProcessor = new SimpleLineProcessor("Out: ");
975     StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), simpleLineProcessor);
976     inGobbler.start();
977
978     // write key
979
//p.getOutputStream().write(asciikey.getBytes());
980
//p.getOutputStream().write("\r\n".getBytes());
981
// EOF
982
p.getOutputStream().flush();
983     p.getOutputStream().close();
984
985     int rep = p.waitFor();
986     try
987     {
988       inGobbler.join(5000);
989     } catch(Exception JavaDoc e) {}
990
991     try
992     {
993       errGobbler.join(5000);
994     } catch(Exception JavaDoc e) {}
995
996
997     if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
998     if(errorProcessor.hasText("failed")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
999
1000  }
1001
1002  public static Vector<KeyIDFromSearchResult> searchKeysOnServer(String JavaDoc pathToGPG, String JavaDoc text, ProgressModalDialog progress) throws Exception JavaDoc
1003  {
1004    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
1005
1006        pathToGPG, "--yes",
1007        //"--batch",
1008
"--no-greeting",
1009         "--keyserver", "hkp://subkeys.pgp.net",
1010         "--search-keys", text
1011    });
1012
1013    if(progress!=null)
1014    {
1015      progress.setProcessToOptionalKill(p);
1016    }
1017
1018    // errors
1019
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1020    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1021    errGobbler.start();
1022
1023    // output
1024
KeySearchResultProcessor keyProcessor = new KeySearchResultProcessor();
1025    StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), keyProcessor);
1026    inGobbler.start();
1027
1028    // EOF
1029
//p.getOutputStream().flush();
1030
//p.getOutputStream().close();
1031

1032
1033    int rep = p.waitFor();
1034    try
1035    {
1036      inGobbler.join(5000);
1037    } catch(Exception JavaDoc e) {}
1038
1039
1040    try
1041    {
1042      errGobbler.join(5000);
1043    } catch(Exception JavaDoc e) {}
1044
1045    if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1046    //if(errorProcessor.hasText("failed")) throw new Exception(errorProcessor.getAllErrorMessage());
1047
// failed: illegal byte sequence occurs often !...
1048
// so we must let it pass
1049

1050    return keyProcessor.getKeyIDs();
1051  }
1052
1053  public static void importKeyFromServer(String JavaDoc pathToGPG, KeyIDFromSearchResult key, ProgressModalDialog progress) throws Exception JavaDoc
1054  {
1055    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
1056
1057        pathToGPG, "--yes", "--batch",
1058         "--keyserver", "hkp://subkeys.pgp.net",
1059         "--recv-keys", key.getKeyShortID()
1060    });
1061
1062    if(progress!=null)
1063    {
1064      progress.setProcessToOptionalKill(p);
1065    }
1066
1067    // errors
1068
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1069    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1070    errGobbler.start();
1071
1072    // output nothing todo, is internal processed
1073
//KeySearchResultProcessor keyProcessor = new KeySearchResultProcessor();
1074
StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), errorProcessor);
1075    inGobbler.start();
1076
1077    // EOF
1078
//p.getOutputStream().flush();
1079
//p.getOutputStream().close();
1080

1081
1082    int rep = p.waitFor();
1083    try
1084    {
1085      inGobbler.join(5000);
1086    } catch(Exception JavaDoc e) {}
1087
1088
1089    try
1090    {
1091      errGobbler.join(5000);
1092    } catch(Exception JavaDoc e) {}
1093
1094    if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1095    //if(errorProcessor.hasText("failed")) throw new Exception(errorProcessor.getAllErrorMessage());
1096

1097  }
1098
1099
1100  public static void refreshPublicKeysFromServer(String JavaDoc pathToGPG, ProgressModalDialog progress) throws Exception JavaDoc
1101  {
1102      Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
1103        pathToGPG, "--yes", "--batch", "--no-greeting",
1104        "--keyserver", "hkp://subkeys.pgp.net",
1105        "--refresh-keys"
1106      });
1107
1108      if(progress!=null) progress.setProcessToOptionalKill(p);
1109
1110    // errors
1111
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1112    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1113    errGobbler.start();
1114
1115    // output nothing todo, is internal processed
1116
StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), errorProcessor);
1117    inGobbler.start();
1118
1119    // EOF
1120
//p.getOutputStream().flush();
1121
//p.getOutputStream().close();
1122

1123    int rep = p.waitFor();
1124    try
1125    {
1126      inGobbler.join(5000);
1127    } catch(Exception JavaDoc e) {}
1128
1129
1130    try
1131    {
1132      errGobbler.join(5000);
1133    } catch(Exception JavaDoc e) {}
1134
1135    if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1136    if(errorProcessor.hasText("failed")) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1137  }
1138
1139
1140
1141  //
1142
// not used yet ...
1143
//
1144

1145  public static void symmetricEncryptFile(String JavaDoc pathToGPG, File src, File dest, char[] pass, boolean ascii) throws Exception JavaDoc
1146  {
1147
1148    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
1149        pathToGPG, "-c"+(ascii?"a":""),
1150        "--no-greeting",
1151        //"--enable-progress-filter",
1152
"-o", dest.getAbsolutePath(),
1153        "--passphrase-fd", "0", // give password in stdin
1154
src.getAbsolutePath()} );
1155
1156    // errors
1157
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1158    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1159    errGobbler.start();
1160
1161    // output
1162
SimpleLineProcessor simpleLineProcessor = new SimpleLineProcessor("Out: ");
1163    StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), simpleLineProcessor);
1164    inGobbler.start();
1165
1166    // give password in stdin
1167
for(int i=0; i<pass.length; i++)
1168    {
1169      p.getOutputStream().write((byte) pass[i]);
1170      // erase password
1171
//pass[i] = (char)0;
1172
}
1173    p.getOutputStream().write((byte)'\n');
1174    p.getOutputStream().flush();
1175
1176    int rep = p.waitFor();
1177
1178    if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1179  }
1180
1181
1182  public static void encryptFile(String JavaDoc pathToGPG, File src, File dest, GnuPGKeyID keyID, boolean ascii) throws Exception JavaDoc
1183  {
1184    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
1185       pathToGPG, "-e"+(ascii?"a":""),
1186       "--enable-progress-filter",
1187       "-r", "\""+keyID.getKeyID()+"\"",
1188       "-o", dest.getAbsolutePath(),
1189       src.getAbsolutePath()});
1190
1191
1192    // forget errors
1193
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1194    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1195    errGobbler.start();
1196
1197    SimpleLineProcessor simpleLineProcessor = new SimpleLineProcessor("Out: ");
1198    StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), simpleLineProcessor);
1199    inGobbler.start();
1200
1201    int rep = p.waitFor();
1202
1203    if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1204  }
1205
1206
1207  public static byte[] encryptBuffer(String JavaDoc pathToGPG, ByteArrayInputStream bin, char[] pass, boolean ascii) throws Exception JavaDoc
1208  {
1209    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
1210       pathToGPG, "-c"+(ascii?"a":""),
1211       "--quiet", "--no-greeting",
1212       //"--enable-progress-filter",
1213
"--passphrase-fd", "0" // give password in stdin
1214

1215    });
1216
1217
1218    // forget errors
1219
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1220    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1221    errGobbler.start();
1222
1223    ByteArrayOutputStream bos = new ByteArrayOutputStream();
1224    StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
1225    inGobbler.start();
1226
1227    // give password on stdin
1228
for(int i=0; i<pass.length; i++)
1229    {
1230      p.getOutputStream().write((byte) pass[i]);
1231      // erase password
1232
//pass[i] = (char)0;
1233
}
1234    p.getOutputStream().write((byte)'\n');
1235    p.getOutputStream().flush();
1236
1237    // write message
1238
byte[] buf = new byte[256];
1239    int read =-1;
1240    while(( read=bin.read(buf))!=-1)
1241    {
1242       p.getOutputStream().write(buf,0,read);
1243    }
1244
1245    // EOF
1246
p.getOutputStream().flush();
1247    p.getOutputStream().close();
1248
1249    int rep = p.waitFor();
1250    try
1251    {
1252      inGobbler.join(5000);
1253    } catch(Exception JavaDoc e) {}
1254
1255    try
1256    {
1257      errGobbler.join(5000);
1258    } catch(Exception JavaDoc e) {}
1259
1260    if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1261
1262    return bos.toByteArray();
1263  }
1264
1265
1266
1267  public static void encryptBuffer(String JavaDoc pathToGPG, InputStream bin, char[] pass, OutputStream bos, boolean ascii, ProgressModalDialog pd) throws Exception JavaDoc
1268  {
1269    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
1270       pathToGPG, "-c"+(ascii?"a":""),
1271       "--quiet", "--no-greeting",
1272       "--passphrase-fd", "0" // give password in stdin
1273
});
1274
1275
1276    // forget errors
1277
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1278    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1279    errGobbler.start();
1280
1281    StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
1282    inGobbler.start();
1283
1284    // give password on stdin
1285
for(int i=0; i<pass.length; i++)
1286    {
1287      p.getOutputStream().write((byte) pass[i]);
1288      // erase password
1289
//pass[i] = (char)0;
1290
}
1291    p.getOutputStream().write((byte)'\n');
1292    p.getOutputStream().flush();
1293    //System.out.println("wrote pass");
1294

1295    // write message
1296
byte[] buf = new byte[256];
1297    int read =-1;
1298    while(( read=bin.read(buf))!=-1)
1299    {
1300       p.getOutputStream().write(buf,0,read);
1301       pd.incrementProgress(read);
1302
1303       if(pd.wasCancelled())
1304       {
1305           p.destroy();
1306           //break;
1307
throw new Exception JavaDoc("Encryption Aborted");
1308       }
1309    }
1310    System.out.println("wrote mess");
1311
1312    // EOF
1313
p.getOutputStream().flush();
1314    p.getOutputStream().close();
1315
1316    //System.out.println("wait");
1317
//int rep = p.waitFor();
1318
//System.out.println("ok");
1319
try
1320    {
1321      inGobbler.join(5000);
1322    } catch(Exception JavaDoc e) {}
1323
1324    try
1325    {
1326      errGobbler.join(5000);
1327    } catch(Exception JavaDoc e) {}
1328
1329    if(errorProcessor.hasError()) throw new Exception JavaDoc(errorProcessor.getAllErrorMessage());
1330
1331  }
1332
1333
1334  public static byte[] decryptBuffer(String JavaDoc pathToGPG, ByteArrayInputStream bin, char[] pass) throws Exception JavaDoc
1335  {
1336    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]{
1337       pathToGPG,
1338       "--enable-progress-filter", "--no-greeting",
1339       "--quiet",
1340       "-d",
1341       "--passphrase-fd", "0", // give password in stdin
1342
});
1343
1344
1345    // forget errors
1346
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1347    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1348    errGobbler.start();
1349
1350    ByteArrayOutputStream bos = new ByteArrayOutputStream();
1351    StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
1352    inGobbler.start();
1353
1354    // give password on stdin
1355
for(int i=0; i<pass.length; i++)
1356    {
1357      p.getOutputStream().write((byte) pass[i]);
1358      // erase password
1359
//pass[i] = (char)0;
1360
}
1361    p.getOutputStream().write((byte)'\n');
1362    p.getOutputStream().flush();
1363    //System.out.println("wrote pass");
1364

1365    // write message
1366
byte[] buf = new byte[256];
1367    int read =-1;
1368    while(( read=bin.read(buf))!=-1)
1369    {
1370       p.getOutputStream().write(buf,0,read);
1371    }
1372    //System.out.println("wrote mess");
1373

1374    // EOF
1375
p.getOutputStream().flush();
1376    p.getOutputStream().close();
1377
1378    //int rep = p.waitFor();
1379
//System.out.println("ok");
1380
try
1381    {
1382      inGobbler.join(5000);
1383    } catch(Exception JavaDoc e) {}
1384
1385    try
1386    {
1387      errGobbler.join(5000);
1388    } catch(Exception JavaDoc e) {}
1389
1390    String JavaDoc err = errorProcessor.getAllErrorMessage();
1391    String JavaDoc err_ = err.toLowerCase();
1392    if(err.indexOf("bad key")>=0) throw new Exception JavaDoc(Language.translate("Bad key"));
1393    if(err.indexOf("failed")>=0) throw new Exception JavaDoc(err);
1394    if(err.indexOf("no valid")>=0) throw new Exception JavaDoc(err);
1395
1396    return bos.toByteArray();
1397  }
1398
1399
1400  /** give the info about the encrypted buffer
1401  */

1402  public static String JavaDoc infoBuffer(String JavaDoc pathToGPG, ByteArrayInputStream bin) throws Exception JavaDoc
1403  {
1404    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[]
1405    {
1406       pathToGPG,
1407       "--decrypt",
1408       "--verbose",
1409       // "--list-packets",
1410
"--no-greeting",
1411       "--passphrase-fd", "0", // give password in stdin
1412
});
1413
1414
1415    // forget errors
1416
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1417    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1418    errGobbler.start();
1419
1420    ByteArrayOutputStream bos = new ByteArrayOutputStream();
1421    StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), bos);
1422    inGobbler.start();
1423
1424    // give password on stdin
1425
/* for(int i=0; i<pass.length; i++)
1426    {
1427      p.getOutputStream().write((byte) pass[i]);
1428      // erase password
1429      pass[i] = (char)0;
1430    }
1431 */

1432    //System.out.println("write password");
1433
p.getOutputStream().write((byte)'\n');
1434    p.getOutputStream().flush();
1435
1436    //System.out.println("write mess pass");
1437

1438    // write message
1439
byte[] buf = new byte[1024];
1440    int read =-1;
1441    while(( read=bin.read(buf))!=-1)
1442    {
1443       p.getOutputStream().write(buf,0,read);
1444    }
1445    //System.out.println("wrote mess");
1446

1447
1448    // EOF
1449
p.getOutputStream().flush();
1450    p.getOutputStream().close();
1451
1452    //System.out.println("wait");
1453
//int rep = p.waitFor();
1454
//System.out.println("ok");
1455
try
1456    {
1457      inGobbler.join(5000);
1458    } catch(Exception JavaDoc e) {}
1459
1460    try
1461    {
1462      errGobbler.join(5000);
1463    } catch(Exception JavaDoc e) {}
1464
1465    String JavaDoc err = errorProcessor.getAllErrorMessage();
1466    System.out.println("ERROR=\n"+err);
1467
1468    //String err_ = err.toLowerCase();
1469
//if(err.indexOf("bad key") >=0) throw new Exception("Bad key");
1470
//if(err.indexOf("failed") >=0) throw new Exception(err);
1471
//if(err.indexOf("no valid")>=0) throw new Exception(err);
1472

1473    return new String JavaDoc(bos.toByteArray());
1474  }
1475
1476
1477  public static void decryptFile(String JavaDoc pathToGPG, File src, File dest, char[] pass) throws Exception JavaDoc
1478  {
1479    Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] {
1480       pathToGPG,
1481       "--enable-progress-filter",
1482       "--quiet", "--no-greeting",
1483       "-o",dest.getAbsolutePath(),
1484       "--passphrase-fd", "0", // give password in stdin
1485
"-d",
1486       src.getAbsolutePath()});
1487
1488    System.out.println("Decrypt Started");
1489
1490    // forget errors
1491
ErrorLineProcessor errorProcessor = new ErrorLineProcessor();
1492    StreamLineGobbler errGobbler = new StreamLineGobbler(p.getErrorStream(), errorProcessor);
1493    errGobbler.start();
1494
1495    SimpleLineProcessor simpleLineProcessor = new SimpleLineProcessor("Out: ");
1496    StreamLineGobbler inGobbler = new StreamLineGobbler(p.getInputStream(), simpleLineProcessor);
1497    inGobbler.start();
1498
1499    // give password in stdin
1500
p.getOutputStream().write((new String JavaDoc(pass)+"\n").getBytes());
1501    p.getOutputStream().flush();
1502
1503
1504    System.out.println("Wait");
1505    int rep = p.waitFor();
1506    System.out.println("OK");
1507
1508    String JavaDoc err = errorProcessor.getAllErrorMessage();
1509    String JavaDoc err_ = err.toLowerCase();
1510    if(err.indexOf("bad key")>=0) throw new Exception JavaDoc(Language.translate("Bad key"));
1511    if(err.indexOf("failed")>=0) throw new Exception JavaDoc(err);
1512    if(err.indexOf("no valid")>=0) throw new Exception JavaDoc(err);
1513
1514    //if(errorProcessor.hasError()) throw new Exception(errorProcessor.getAllErrorMessage());
1515
}
1516
1517} // GnuPGCommands
Popular Tags