KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SnowMailClient > gnupg > GnuPGLink


1 package SnowMailClient.gnupg;
2
3
4 import javax.swing.*;
5 import javax.swing.border.*;
6 import java.awt.*;
7 import java.awt.event.*;
8 import java.util.*;
9 import java.io.*;
10
11 import snow.utils.gui.*;
12 import snow.concurrent.*;
13 import SnowMailClient.Language.Language;
14 import snow.utils.storage.*;
15 import SnowMailClient.utils.*;
16 import SnowMailClient.gnupg.Main.GnuPGCommands;
17 import SnowMailClient.gnupg.model.*;
18 import SnowMailClient.gnupg.Views.GPGPasswordDialog;
19 import SnowMailClient.SnowMailClientApp;
20
21
22 /** Establish a link with an external GnuPG application and allow encrypt / decrypt buffers
23     caches the key id's and the passwords
24     get the link from the main app
25
26   Usage:
27      0) Set the gpg path (auto in constructor, read from props)
28      1) Get a secret or public key ID
29      2) Encrypt, decrypt, get keys, ...
30
31 */

32 public final class GnuPGLink
33 {
34   // Parameters
35

36   private String JavaDoc pathToGPG = "c:/app/gnupg/gpg.exe";
37   private String JavaDoc gpgVersion = "";
38
39   // Read from gpg at each startup or gpg path change
40
TreeSet<GnuPGKeyID> publicKeyIDsModel = new TreeSet<GnuPGKeyID>(); // sorted keys
41
TreeSet<GnuPGKeyID> secretKeyIDsModel = new TreeSet<GnuPGKeyID>(); // sorted keys
42

43   // cache
44
final private Map<String JavaDoc, byte[]> keyPasswords = new Hashtable<String JavaDoc, byte[]>();
45
46   private boolean isGPG_available = false;
47
48
49   public GnuPGLink()
50   {
51   } // Constructor
52

53
54   public Vector<Object JavaDoc> getVectorRepresentation()
55   {
56     Vector<Object JavaDoc> rep = new Vector<Object JavaDoc>();
57     rep.addElement(1); //0: version
58
rep.addElement(pathToGPG); // 1
59
rep.addElement(gpgVersion); //2
60

61     Vector<Object JavaDoc> keyPasswordsKeys = new Vector<Object JavaDoc>();
62     Vector<Object JavaDoc> keyPasswordsValues = new Vector<Object JavaDoc>();
63
64     for(String JavaDoc id: keyPasswords.keySet())
65     {
66        keyPasswordsKeys.add(id);
67        keyPasswordsValues.addElement(keyPasswords.get(id));
68     }
69
70     rep.add(keyPasswordsKeys); // 3
71
rep.add(keyPasswordsValues); // 4
72

73     return rep;
74   }
75
76 @SuppressWarnings JavaDoc("unchecked")
77   public void createFromVectorRepresentation(Vector<Object JavaDoc> v)
78   {
79     int version = (Integer JavaDoc) v.elementAt(0);
80     if(version==1)
81     {
82        pathToGPG = (String JavaDoc) v.elementAt(1);
83        gpgVersion = (String JavaDoc) v.elementAt(2);
84        Vector<String JavaDoc> ke = (Vector<String JavaDoc>) v.elementAt(3);
85        Vector<byte[]> va = (Vector<byte[]>) v.elementAt(4);
86        keyPasswords.clear();
87        for(int i=0; i<ke.size(); i++)
88        {
89          keyPasswords.put(ke.elementAt(i), va.elementAt(i));
90        }
91
92        // read actual public and private keys from GPG !
93
try
94        {
95           setGPGPath(pathToGPG);
96        } catch(Exception JavaDoc ignored) { System.out.println("No GPG Link");}
97     }
98     else
99     {
100       throw new RuntimeException JavaDoc("Bad version "+version);
101     }
102   }
103
104
105   public String JavaDoc getGPGVersionString() { return this.gpgVersion; }
106
107
108   /** true if the path is valid, and keys successfully read.
109   */

110   public boolean isGPG_available() { return isGPG_available; }
111
112   public String JavaDoc getPathToGPG() { return this.pathToGPG; }
113
114   /** set the path and read all the private/public key IDs
115   */

116   public void setGPGPath(String JavaDoc path) throws Exception JavaDoc
117   {
118     pathToGPG = path;
119
120     //properties.setProperty("gpgpath", path);
121

122     gpgVersion = GnuPGCommands.readGPGVersion(path);
123     //System.out.println("GPG Version is "+gpgVersion);
124
//if(gpgVersion.compareTo("1.4")<0) throw new Exception("Bad GPG version "+gpgVersion);
125

126     publicKeyIDsModel.clear();
127     publicKeyIDsModel.addAll( GnuPGCommands.readPublicKeyIDs(path) );
128
129     secretKeyIDsModel.clear();
130     secretKeyIDsModel.addAll( GnuPGCommands.readSecretKeyIDs(path) );
131
132     isGPG_available = true;
133
134   }
135
136   public TreeSet<GnuPGKeyID> getAllPublicKeyIDs() { return publicKeyIDsModel; }
137   public TreeSet<GnuPGKeyID> getAllSecretKeyIDs() { return secretKeyIDsModel; }
138
139   public GnuPGKeyID[] getPublicKeyIDForAddress(String JavaDoc mail)
140   {
141     Vector<GnuPGKeyID> rep = new Vector<GnuPGKeyID>();
142     for(GnuPGKeyID k: publicKeyIDsModel)
143     {
144       for(UIDRecord uid: k.getUIDs())
145       {
146         if(uid.getMail().compareToIgnoreCase(mail)==0) rep.addElement(k);
147       }
148     }
149     return rep.toArray(new GnuPGKeyID[rep.size()]);
150   }
151
152
153
154   public GnuPGKeyID[] getSecretKeyIDForAddress(String JavaDoc mail)
155   {
156     Vector<GnuPGKeyID> rep = new Vector<GnuPGKeyID>();
157     for(GnuPGKeyID k: secretKeyIDsModel)
158     {
159       for(UIDRecord uid: k.getUIDs())
160       {
161          if(uid.getMail().compareToIgnoreCase(mail)==0) rep.addElement(k);
162       }
163     }
164     return rep.toArray(new GnuPGKeyID[rep.size()]);
165   }
166
167   public boolean hasSecretKeyAssociated(GnuPGKeyID kid)
168   {
169     for(GnuPGKeyID k: secretKeyIDsModel)
170     {
171       if(k.getFingerprint().compareToIgnoreCase(kid.getFingerprint())==0) return true;
172     }
173     return false;
174   }
175
176   /** null if not found
177   */

178   public byte[] getPasswordForKey(GnuPGKeyID kid)
179   {
180     return this.keyPasswords.get(kid.getKeyID());
181   }
182
183   public void setPasswordForKey(GnuPGKeyID kid, byte[] pass)
184   {
185     this.keyPasswords.put(kid.getKeyID(), pass);
186   }
187
188   /** @return null if cancelled
189   */

190   public byte[] getPasswordForKeyAskIfNotFoundOrNotValid(GnuPGKeyID kid, boolean store, JFrame parent)
191   {
192     byte[] pass = this.keyPasswords.get(kid.getKeyID());
193
194     if(pass!=null)
195     {
196       // verify
197
try
198       {
199         if(GnuPGCommands.verifySecretKeyPassword(pathToGPG, kid, pass))
200         {
201           // password ok !
202
return pass;
203         }
204       } catch(Exception JavaDoc ignored){}
205     }
206
207     // no password or bad password
208

209     GPGPasswordDialog pd = new GPGPasswordDialog(parent, this, kid, Language.translate("Enter the password for the GPG key\n%", kid.getKeyID()));
210     if(pd.isPasswordValid())
211     {
212       if(store)
213       {
214         this.setPasswordForKey(kid, pd.getPassword());
215       }
216       return pd.getPassword();
217     }
218
219     return null;
220   }
221
222   /** shows a dialog that asks for the gpg path
223   */

224   public void askGPGPath(JFrame dialogParent)
225   {
226      final JDialog dialog = new JDialog(dialogParent, Language.translate("GnuPG Location Selection"), true);
227      //final String[] rep = new String[]{null};
228
final FileField gpgPathTF = new FileField(pathToGPG, false, Language.translate("Path to gpg.exe")+": ", JFileChooser.FILES_ONLY);
229
230      dialog.getContentPane().setLayout(new BorderLayout());
231
232      JPanel inputPanel = new JPanel();
233      inputPanel.setBorder( BorderFactory.createBevelBorder(BevelBorder.LOWERED));
234      inputPanel.add(gpgPathTF);
235
236      dialog.getContentPane().add(inputPanel, BorderLayout.CENTER);
237
238
239      JPanel labelP = new JPanel(new BorderLayout());
240      JTextArea explainTA = new JTextArea( Language.translate(
241         "\nPlease give the location of the application gpg.exe (Gnu Privacy Guard)."
242       + "\nYou must use at least version 1.4 or later."
243       + "\nIf you don't find this program, you have to install first GnuPG"
244       + "\non your computer. Visit the homepage at www.gnupg.org.") );
245
246      explainTA.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
247      explainTA.setBackground(dialog.getContentPane().getBackground());
248      explainTA.setForeground(dialog.getContentPane().getForeground());
249
250      labelP.add(explainTA, BorderLayout.CENTER);
251      explainTA.setEditable(false);
252      dialog.getContentPane().add(labelP, BorderLayout.NORTH);
253
254      CloseControlPanel ccp = new CloseControlPanel(dialog, true, true, Language.translate("Ok"));
255      dialog.getContentPane().add(ccp, BorderLayout.SOUTH);
256
257
258      gpgPathTF.addActionListener(new ActionListener()
259      {
260        public void actionPerformed(ActionEvent e2)
261        {
262          dialog.setVisible(false);
263        }
264      });
265
266
267      dialog.pack();
268      SnowMailClientApp.centerComponentOnMainFrame(dialog);
269      dialog.setVisible(true);
270
271      if(ccp.getWasCancelled()) return;
272
273      try
274      {
275         setGPGPath(gpgPathTF.getPath().getAbsolutePath());
276      } catch(Exception JavaDoc e){ e.printStackTrace(); }
277   }
278
279
280   // Functions interface
281
//
282

283   /** sign the content with the given key.
284   */

285   public String JavaDoc sign(String JavaDoc content, GnuPGKeyID kid, byte[] pass, Interrupter interrupter) throws Exception JavaDoc
286   {
287      ByteArrayInputStream bin = new ByteArrayInputStream(content.getBytes());
288      byte[] rep = GnuPGCommands.signBuffer(this.pathToGPG, bin, kid, pass, interrupter );
289      return new String JavaDoc(rep);
290   }
291
292   public byte[] sign(ByteArrayInputStream bin, GnuPGKeyID kid, byte[] pass, Interrupter interrupter) throws Exception JavaDoc
293   {
294      byte[] rep = GnuPGCommands.signBuffer(this.pathToGPG, bin, kid, pass, interrupter );
295      return rep;
296   }
297
298   public String JavaDoc getPublicKeyContent(GnuPGKeyID kid) throws Exception JavaDoc
299   {
300      return GnuPGCommands.getPublicKey(this.pathToGPG, kid);
301   }
302
303   public String JavaDoc getSecretKeyContent(GnuPGKeyID kid) throws Exception JavaDoc
304   {
305      return GnuPGCommands.getSecretKey(this.pathToGPG, kid);
306   }
307
308   public void addKey(String JavaDoc asciiKey) throws Exception JavaDoc
309   {
310      GnuPGCommands.addKey(this.pathToGPG, asciiKey);
311   }
312
313   public void removeKey(GnuPGKeyID kid) throws Exception JavaDoc
314   {
315      if(kid.isSecret())
316      {
317         // remove both...
318
GnuPGCommands.removePublicAndPrivateKey(pathToGPG, kid);
319      }
320      else
321      {
322         GnuPGCommands.removePublicKey(pathToGPG, kid);
323      }
324   }
325
326   public void removePublicAndPrivateKey(GnuPGKeyID kid) throws Exception JavaDoc
327   {
328     GnuPGCommands.removePublicAndPrivateKey(pathToGPG, kid);
329   }
330
331 } // GnuPGLink
Popular Tags