KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jacorb > security > util > KeyStoreManager


1 /*
2  * JacORB - a free Java ORB
3  *
4  * Copyright (C) 1997-2004 Gerald Brose.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */

20
21 package org.jacorb.security.util;
22
23 /**
24  * This class manages a key store
25  *
26  * @author Gerald Brose, FU Berlin; Andre Benvenuti, GST Bern
27  * @version $Id: KeyStoreManager.java,v 1.9 2004/05/06 12:40:01 nicolas Exp $
28  */

29
30 import java.security.*;
31 import java.security.cert.*;
32 import java.io.*;
33 import javax.swing.*;
34 import javax.swing.event.*;
35 import javax.swing.table.*;
36 import javax.swing.tree.*;
37 import javax.swing.event.ListSelectionListener JavaDoc;
38 import javax.swing.event.ListSelectionEvent JavaDoc;
39 import java.awt.*;
40 import java.awt.event.*;
41
42 import java.math.BigInteger JavaDoc;
43 import java.util.*;
44
45 import iaik.asn1.*;
46 import iaik.asn1.structures.*;
47 import iaik.x509.*;
48 import iaik.x509.extensions.*;
49
50 public class KeyStoreManager
51     extends JFrame
52 {
53     /** the password for managing the key store */
54     private char[] ksPassword;
55
56     /** the current key store */
57     private KeyStore ks;
58
59     /** the current key store's file name */
60     private String JavaDoc ksFileName;
61
62     private boolean done = false;
63
64     /** whether the current key store has been modified */
65     private boolean dirty = false;
66
67     /** the tree represinting the key store contents */
68     private KSEntryTree tree;
69
70     /** our handler */
71     private EventHandler actionHandler;
72
73     // file menu items
74
JMenuItem openMenuItem;
75     JMenuItem newMenuItem;
76     JMenuItem saveMenuItem;
77     JMenuItem saveAsMenuItem;
78     JMenuItem closeMenuItem;
79     JMenuItem exitMenuItem;
80
81     /** key menu items */
82     JMenuItem generateKeyMenuItem;
83     JMenuItem deleteKeyMenuItem;
84     JMenuItem verifyChainMenuItem;
85
86     /** trustee menu items */
87     JMenuItem addTrusteeMenuItem;
88     JMenuItem deleteTrusteeMenuItem;
89
90     /** cert menu items */
91     JMenuItem createCertMenuItem;
92     JMenuItem signMenuItem;
93     JMenuItem exportCertMenuItem;
94     JMenuItem importCertMenuItem;
95     JMenuItem deleteCertMenuItem;
96
97     JFileChooser chooser;
98     JPanel topPanel;
99
100     public KeyStoreManager()
101     {
102     super("KeyStoreManager");
103     actionHandler = new EventHandler();
104     chooser = new JFileChooser();
105
106     try
107     {
108         UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
109     }
110     catch (Exception JavaDoc e)
111     {}
112
113     // Build menu bar
114
JMenuBar menuBar = new JMenuBar();
115     setJMenuBar(menuBar);
116
117     // file menu
118

119     JMenu fileMenu = new JMenu("File");
120     menuBar.add(fileMenu);
121
122     openMenuItem = new JMenuItem("Open...");
123     openMenuItem.addActionListener(actionHandler);
124     fileMenu.add(openMenuItem);
125
126     newMenuItem = new JMenuItem("New");
127     newMenuItem.addActionListener(actionHandler);
128     fileMenu.add(newMenuItem);
129
130     saveMenuItem = new JMenuItem("Save");
131     saveMenuItem.addActionListener(actionHandler);
132     fileMenu.add(saveMenuItem);
133
134     saveAsMenuItem = new JMenuItem("SaveAs...");
135     saveAsMenuItem.addActionListener(actionHandler);
136     fileMenu.add(saveAsMenuItem);
137
138     closeMenuItem = new JMenuItem("Close");
139     closeMenuItem.addActionListener(actionHandler);
140     fileMenu.add(closeMenuItem);
141
142     exitMenuItem = new JMenuItem("Exit");
143     exitMenuItem.addActionListener(actionHandler);
144     fileMenu.add(exitMenuItem);
145
146     // keys menu
147

148     JMenu keyMenu = new JMenu("Keys");
149     menuBar.add(keyMenu);
150
151     generateKeyMenuItem = new JMenuItem("New...");
152     generateKeyMenuItem.addActionListener(actionHandler);
153     keyMenu.add(generateKeyMenuItem);
154
155     deleteKeyMenuItem = new JMenuItem("Delete");
156     deleteKeyMenuItem.addActionListener(actionHandler);
157     keyMenu.add(deleteKeyMenuItem);
158
159     verifyChainMenuItem = new JMenuItem("Verify Chain");
160     verifyChainMenuItem.addActionListener(actionHandler);
161     keyMenu.add(verifyChainMenuItem);
162
163     // trustees menu
164

165     JMenu trusteeMenu = new JMenu("Trustees");
166     menuBar.add(trusteeMenu);
167
168     addTrusteeMenuItem = new JMenuItem("add...");
169     addTrusteeMenuItem.addActionListener(actionHandler);
170     trusteeMenu.add(addTrusteeMenuItem);
171
172     deleteTrusteeMenuItem = new JMenuItem("Delete");
173     deleteTrusteeMenuItem.addActionListener(actionHandler);
174     trusteeMenu.add(deleteTrusteeMenuItem);
175
176     // certs menu
177

178     JMenu certMenu = new JMenu("Certificates");
179     menuBar.add(certMenu);
180
181     createCertMenuItem = new JMenuItem("Create");
182     createCertMenuItem.addActionListener(actionHandler);
183     certMenu.add(createCertMenuItem);
184
185     exportCertMenuItem = new JMenuItem("Export");
186     exportCertMenuItem.addActionListener(actionHandler);
187     certMenu.add(exportCertMenuItem);
188
189     importCertMenuItem = new JMenuItem("Import");
190     importCertMenuItem.addActionListener(actionHandler);
191     certMenu.add(importCertMenuItem);
192
193     deleteCertMenuItem = new JMenuItem("Delete");
194     deleteCertMenuItem.addActionListener(actionHandler);
195     certMenu.add(deleteCertMenuItem);
196
197     tree=new KSEntryTree();
198     JScrollPane treeScrollPane = tree.getPane();
199         
200     getContentPane().setBackground(Color.white);
201     getContentPane().add(treeScrollPane);
202
203     pack();
204     setVisible(true);
205     }
206
207     /**
208      * @return false, if we have to cancel the operation, true otherwise
209      */

210
211     public boolean close()
212     {
213     if( ks == null )
214         return true;
215
216     if( dirty )
217     {
218         int option = JOptionPane.showConfirmDialog(null,
219                                "KeyStore modified, save changes?",
220                                "Close",
221                                JOptionPane.YES_NO_CANCEL_OPTION,
222                                JOptionPane.INFORMATION_MESSAGE);
223         if( option == JOptionPane.CANCEL_OPTION)
224         return false;
225         if( option == JOptionPane.YES_OPTION)
226         save();
227
228     }
229     ks = null;
230     ksPassword = null;
231     tree.clean();
232     repaint();
233     return true;
234     }
235
236     private void _exit()
237     {
238     if( close())
239         System.exit(0);
240     }
241
242     private void load()
243     {
244     if( ks != null )
245     {
246         if( !close())
247         return;
248     }
249
250     int returnVal = chooser.showOpenDialog(this);
251     if( returnVal == JFileChooser.APPROVE_OPTION )
252         ksFileName = chooser.getSelectedFile().getAbsolutePath();
253     else
254         return;
255
256     ksPassword = UserSponsor.getPasswd("Password for KeyStore " + ksFileName);
257
258     try
259     {
260         setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
261         ks = KeyStoreUtil.getKeyStore( ksFileName,ksPassword );
262         setCursor(java.awt.Cursor.getDefaultCursor());
263     }
264     catch( Exception JavaDoc e )
265     {
266         JOptionPane.showMessageDialog(null,
267                       e.getClass().getName() + ":" + e.getMessage(),
268                       "Exception",
269                       JOptionPane.ERROR_MESSAGE);
270         setCursor(java.awt.Cursor.getDefaultCursor());
271         return;
272     }
273
274     setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
275     tree.load( ks);
276     repaint();
277     setCursor(java.awt.Cursor.getDefaultCursor());
278     dirty = false;
279     }
280
281     private void save()
282     {
283     if( ks == null || !dirty )
284         return;
285
286     if( ksFileName == null )
287         saveAs();
288     else
289     {
290         try
291         {
292         setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
293         FileOutputStream out = new FileOutputStream(ksFileName);
294         for( Enumeration e = tree.getNodes() ; e.hasMoreElements(); )
295         {
296             TreeNode node = (TreeNode)e.nextElement();
297             if( node instanceof KeyNode )
298             ((KeyNode)node).store();
299             else if ( node instanceof TrustNode )
300             ((TrustNode)node).store();
301         }
302             
303         ks.store( out, ksPassword );
304         }
305         catch( Exception JavaDoc io )
306         {
307         io.printStackTrace();
308         }
309         dirty = false;
310         setCursor(java.awt.Cursor.getDefaultCursor());
311     }
312     }
313
314     private void saveAs()
315     {
316     if( ks == null || !dirty )
317         return;
318
319     int returnVal = chooser.showSaveDialog(this);
320     if( returnVal == JFileChooser.APPROVE_OPTION )
321         ksFileName = chooser.getSelectedFile().getAbsolutePath();
322     else
323         return;
324
325     if( ksPassword == null )
326     {
327         String JavaDoc passwd = JOptionPane.showInputDialog( "Please enter Password to save KeyStore");
328         if( passwd != null )
329         ksPassword = passwd.toCharArray();
330         else
331         return;
332     }
333     setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
334     try
335     {
336         FileOutputStream out = new FileOutputStream(ksFileName);
337         for( Enumeration e = tree.getNodes() ; e.hasMoreElements(); )
338         {
339         TreeNode node = (TreeNode)e.nextElement();
340         if( node instanceof KeyNode )
341             ((KeyNode)node).store();
342         else if ( node instanceof TrustNode )
343             ((TrustNode)node).store();
344         }
345         ks.store( out, ksPassword );
346         setCursor(java.awt.Cursor.getDefaultCursor());
347     }
348     catch( Exception JavaDoc e )
349     {
350         e.printStackTrace();
351     }
352     setCursor(java.awt.Cursor.getDefaultCursor());
353     dirty = false;
354     }
355
356     private void newFile()
357     {
358     if( ks != null )
359     {
360         if( !close())
361         return;
362     }
363
364     setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
365     try
366     {
367         try
368         {
369             ks = KeyStore.getInstance( "IAIKKeyStore", "IAIK" );
370         }
371         catch ( java.security.NoSuchProviderException JavaDoc ex )
372         {
373             System.err.println ( ex.toString ());
374             ks = KeyStore.getInstance("jks");
375         }
376         ks.load( null, new char[0] );
377     }
378     catch( Exception JavaDoc e )
379     {
380         showException( e );
381         return;
382     }
383
384     tree.load(ks);
385     repaint();
386     setCursor(java.awt.Cursor.getDefaultCursor());
387     dirty = false;
388     }
389
390     private void exportCert(java.security.cert.Certificate JavaDoc cert)
391     {
392     if( cert == null )
393         return;
394     JFileChooser exporter = new JFileChooser();
395     exporter.setDialogTitle("Export Certificate to File");
396     exporter.setApproveButtonText("Export");
397
398     int returnVal = exporter.showSaveDialog(this);
399     if( returnVal == JFileChooser.APPROVE_OPTION )
400     {
401         String JavaDoc fileName = exporter.getSelectedFile().getAbsolutePath();
402         try
403         {
404         FileOutputStream out = new FileOutputStream(fileName);
405         if( out == null )
406             throw new IOException("File " + fileName + " not found.");
407         out.write(cert.getEncoded());
408         out.close();
409         }
410         catch( Exception JavaDoc e )
411         {
412         e.printStackTrace();
413         }
414     }
415     }
416
417
418     private void exportCert()
419     {
420     java.security.cert.Certificate JavaDoc cert = null;
421     try
422     {
423         KSNode node = tree.getSelectedNode();
424             
425             if( node != null )
426             {
427                 exportCert( node.getCert() );
428             }
429     }
430     catch ( Exception JavaDoc e )
431     {
432         showException( e );
433         return;
434     }
435     }
436
437
438     private void createCert()
439     {
440     if( ks == null )
441         return;
442
443     try
444     {
445         iaik.x509.X509Certificate cert;
446         String JavaDoc targetAlias = tree.getSelectedAlias();
447         
448         Vector aliasVector = new Vector();
449         for( Enumeration aliasCandidates= tree.getNodes(); aliasCandidates.hasMoreElements();)
450         {
451         TreeNode tn = (TreeNode)aliasCandidates.nextElement();
452         if( tn instanceof KeyNode)
453             aliasVector.add( ((KeyNode)tn).getAlias());
454         }
455
456         String JavaDoc signerAliases[] = new String JavaDoc[aliasVector.size()];
457         for( int i = 0; i < signerAliases.length; i++)
458         signerAliases[i]= (String JavaDoc)aliasVector.elementAt(i);
459
460         String JavaDoc subjectAliases[];
461
462         if( targetAlias != null )
463         subjectAliases = new String JavaDoc[] { targetAlias };
464         else
465         subjectAliases = signerAliases;
466
467         UserSponsor us = new UserSponsor("Create Certificate",
468                          "Please select Certificate parameters",
469                          new String JavaDoc[]{"Role Name\n(only needed for role certs)"},
470                          new String JavaDoc[]{"Subject Key Alias","Signer Key Alias","Certificate Type"},
471                          new String JavaDoc[][]{subjectAliases, signerAliases, {"Public Key Cert", "Role Cert"}},
472                          new String JavaDoc[]{"Password of signer\nprivate key"}
473                          );
474         String JavaDoc[] paramHolder = new String JavaDoc[1];
475         String JavaDoc[] typeHolder = new String JavaDoc[3];
476         char[][] passwordHolder= new char[1][];
477
478         if( us.getInput( paramHolder, typeHolder, passwordHolder))
479         {
480         setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
481
482         String JavaDoc value = null;
483         String JavaDoc signerAlias = null;
484         String JavaDoc certType = null;
485         char[] password = new char[0];
486         
487         if( paramHolder[0] != null )
488             value = paramHolder[0];
489         
490         if( targetAlias == null && typeHolder[0] != null )
491             targetAlias = typeHolder[0];
492
493         if( typeHolder[1] != null )
494             signerAlias = typeHolder[1];
495
496         if( typeHolder[2] != null )
497             certType = typeHolder[2];
498         
499         if( signerAlias == null || signerAlias.length() == 0 )
500             throw new IllegalArgumentException JavaDoc("No alias for key entry!");
501
502         // get selected alias or new alias name and a password
503
if( passwordHolder[0] != null )
504             password = passwordHolder[0];
505         
506         KeyNode snode = ( KeyNode )(tree.getNode(signerAlias)); // bnv: key might not yet be in ks
507
KSNode tnode = tree.getNode(targetAlias);
508
509         System.out.println ( "signerAlias is " + signerAlias );
510         java.security.PrivateKey JavaDoc signPrivKey = snode.getKey ( password );
511
512         if( certType.equals("Role Cert"))
513         {
514 System.out.println("creating role cert");
515
516             if ( signPrivKey == null )
517             {
518             System.out.println ( "signPrivKey is null" );
519             java.security.KeyPair JavaDoc kp = KeyStoreUtil.getKeyPair(ks, signerAlias, password);
520             signPrivKey = kp.getPrivate();
521             snode.setKey ( signPrivKey, password );
522             }
523             iaik.x509.X509Certificate pubKeyCert = tnode.getCert();
524             java.security.PublicKey JavaDoc subjectPubKey = pubKeyCert.getPublicKey();
525
526             cert = CertUtils.certifyRoleMembership(value,
527                                CertUtils.createName(targetAlias),
528                                CertUtils.createName(signerAlias),
529                                subjectPubKey,
530                                signPrivKey
531                                );
532             // bnv: will build a new certificate chain for targetAlias
533
System.out.println("bnv: will build a new certificate chain for targetAlias");
534             java.security.cert.Certificate JavaDoc [] signerCerts = snode.getCertificateChain ();
535             iaik.x509.X509Certificate[] certs =
536             new iaik.x509.X509Certificate [ 1 + signerCerts.length ];
537             certs[ 0 ] = cert;
538             for ( int i = 1; i <= signerCerts.length; i++ ) {
539                 certs[ i ] = ( iaik.x509.X509Certificate )signerCerts[ i - 1 ];
540             }
541             // ks.setKeyEntry( targetAlias, ks.getKey(targetAlias, password),password, certs);
542
// bnv: old certificate chain for targetAlias is removed and new one inserted
543
System.out.println("bnv: old certificate chain for targetAlias is removed and new one inserted");
544             tree.removeCerts ( targetAlias );
545             tree.addCerts ( targetAlias, certs );
546
547             repaint ();
548             // exportCert( cert );
549

550         }
551         else if( certType.equals("Public Key Cert"))
552         {
553 System.out.println("creating public key cert");
554
555             cert = CertUtils.createPublicKeyCert ( CertUtils.createName(targetAlias),
556                                CertUtils.createName(signerAlias),
557                                tnode.getCert().getPublicKey(),
558                                signPrivKey
559                              );
560             
561
562             iaik.x509.X509Certificate[] certs = new iaik.x509.X509Certificate [ 2 ];
563             certs[ 0 ] = cert;
564             certs[ 1 ] = (iaik.x509.X509Certificate)snode.getCert();
565             if( tnode instanceof TrustNode )
566             {
567             // act like a CA
568
// ks.setCertificateEntry( targetAlias, cert );
569
exportCert(cert);
570             }
571             else
572             {
573             tree.addCert( targetAlias, -1, certs[0] );
574             tree.addCert( targetAlias, -1, certs[1] );
575             }
576             repaint ();
577             // exportCert(pkCert);
578

579         }
580         else
581         {
582             throw new IllegalArgumentException JavaDoc("Unknown Certificate Type: " + certType);
583         }
584         }
585     }
586     catch ( Exception JavaDoc e )
587     {
588         showException( e );
589     }
590     setCursor(java.awt.Cursor.getDefaultCursor());
591     }
592
593     public void importCert()
594     {
595     if( ks == null )
596         return;
597
598     String JavaDoc fileName = null;
599     String JavaDoc alias = null;
600  
601     MutableTreeNode node = tree.getSelectedNode();
602     if( node == null )
603         return;
604
605     if( node instanceof CertNode )
606         return;
607
608     if( node instanceof KeyNode )
609     {
610         alias = ((KeyNode)node).getAlias();
611         ((KeyNode)node).checkAccess();
612     }
613     
614     if( alias == null )
615         return;
616
617     // char[] password = null;
618
// char[][] passwordHolder = new char[1][];
619

620 // UserSponsor us = new UserSponsor("Password",
621
// "Please enter password for key alias " + alias ,
622
// null, new String[]{"Password"}
623
// );
624
// us.getInput( null, passwordHolder);
625

626 // if( passwordHolder[0] != null )
627
// password = passwordHolder[0];
628
// else
629
// return;
630

631     int returnVal = chooser.showOpenDialog(this);
632
633     if( returnVal == JFileChooser.APPROVE_OPTION )
634         fileName = chooser.getSelectedFile().getAbsolutePath();
635     else
636         return;
637
638     try
639     {
640         setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
641         FileInputStream in = new FileInputStream(fileName);
642
643         java.security.cert.CertificateFactory JavaDoc certFactory =
644         java.security.cert.CertificateFactory.getInstance("X.509", "IAIK");
645     
646         iaik.x509.X509Certificate cert =
647         (iaik.x509.X509Certificate)certFactory.generateCertificate(in);
648
649         // java.security.cert.Certificate[] oldCerts = ks.getCertificateChain(alias);
650

651         iaik.x509.X509Certificate[] oldCerts = ((KeyNode)node).getCertificateChain();
652
653         int ci = 0;
654         for( Enumeration e = ((KeyNode)node).children(); e.hasMoreElements(); ci++ )
655         {
656         CertNode certNode = (CertNode)e.nextElement();
657         oldCerts[ci] = certNode.getCert();
658         }
659
660         iaik.x509.X509Certificate[] newCerts =
661         new iaik.x509.X509Certificate[(oldCerts != null ? oldCerts.length+1: 1 )];
662
663         for( int i = 0; i < oldCerts.length; i++ )
664         newCerts[i] = oldCerts[i];
665
666         newCerts[newCerts.length-1] = cert;
667
668         java.security.PrivateKey JavaDoc pk =
669         (java.security.PrivateKey JavaDoc)tree.getKeyNode(alias).getKey();
670
671         tree.addCert( alias, newCerts.length-1, cert );
672
673         dirty = true;
674         setCursor(java.awt.Cursor.getDefaultCursor());
675     }
676     catch( Exception JavaDoc e )
677     {
678         showException(e);
679     }
680
681     repaint();
682     }
683
684
685     /*
686      * Imports a certificate from file; the user is asked for the file location.
687      *
688      * @return - the certificate stored in the file.
689      */

690
691     public iaik.x509.X509Certificate importCertificate()
692     {
693     String JavaDoc fileName = null;
694     int returnVal = chooser.showOpenDialog ( this );
695     if ( returnVal == JFileChooser.APPROVE_OPTION )
696         fileName = chooser.getSelectedFile ().getAbsolutePath ();
697     else
698         return null;
699
700     try
701     {
702         FileInputStream in = new FileInputStream ( fileName );
703
704         java.security.cert.CertificateFactory JavaDoc certFactory =
705         java.security.cert.CertificateFactory.getInstance ( "X.509", "IAIK" );
706     
707         iaik.x509.X509Certificate cert =
708         ( iaik.x509.X509Certificate )certFactory.generateCertificate ( in );
709         cert.verify( cert.getPublicKey ());
710         return cert;
711     }
712     catch ( Exception JavaDoc e )
713     {
714         showException ( e );
715         return null;
716     }
717     }
718
719
720     /*
721      * Imports a certificate chain from file; the user is asked for the file location.
722      *
723      * The certificate of the user is the first one in the list
724      * and the top level certificate is the last one.
725      * chain[0] = user certificate signed issuer1
726      * chain[1] = issuer1 certificate signed issuer2
727      * ...
728      * chain[n] = self signed CA certificate
729      *
730      * @return - true if we can verify all the certificates in the chain
731      * and if CA is a trusted signer.
732      *
733      * @param chain the certificate chain to verify
734      * @param keyStore - the keyStore to search for trusted signers
735      */

736     /*
737     public iaik.x509.X509Certificate [] importCertificateChain()
738     {
739     String fileName = null;
740
741     int returnVal = chooser.showOpenDialog(this);
742     if( returnVal == JFileChooser.APPROVE_OPTION )
743         fileName = chooser.getSelectedFile().getAbsolutePath();
744     else
745         return null;
746
747     try
748     {
749         FileInputStream in = new FileInputStream(fileName);
750
751         java.security.cert.CertificateFactory certFactory =
752         java.security.cert.CertificateFactory.getInstance( "X.509" );
753     
754         Collection c = certFactory.generateCertificates ( in );
755         iaik.x509.X509Certificate [] certs =
756         new iaik.x509.X509Certificate [ c.size () ];
757         Iterator i = c.iterator (); int j = 0;
758         while ( i.hasNext ())
759         {
760             certs[ j ] = ( iaik.x509.X509Certificate ) i.next ();
761         System.out.println ( certs [ j ]);
762         }
763         if ( CertUtils.verifyCertificateChain ( certs, ks ))
764         return certs;
765         else return null;
766     }
767     catch ( Exception e )
768     {
769         showException ( e );
770         return null;
771     }
772     }
773     */

774
775     /*
776      * Imports a certificate from file; the user is asked for the file location.
777      * It then sets this certificate in the KeyStore Entry.
778      *
779      */

780
781     /*
782     public void putCertificate()
783     {
784     if( ks == null ) return;
785
786     MutableTreeNode node = tree.getSelectedNode();
787     if( node == null )
788         return;
789
790     String alias = node.getAlias();
791
792     java.security.cert.X509Certificate[] newCerts = importCertificateChain ();
793     
794     try
795     {
796         if( ks.isKeyEntry ( alias ))
797         {
798             // get password from user and then the key pair.
799         char[] password = null;
800         char[][] passwordHolder = new char[1][];
801         UserSponsor us = new UserSponsor( "Password",
802                           "Please enter password for key alias " + alias ,
803                           null, new String[] { "Password" }
804                         );
805         us.getInput ( null, passwordHolder );
806           
807         if ( passwordHolder[ 0 ] != null )
808         {
809              password = passwordHolder[ 0 ];
810              java.security.Key key = ks.getKey ( alias, password );
811              ks.setKeyEntry ( alias,
812                       key,
813                       password,
814                       newCerts
815                     );
816              node.setKey((java.security.PrivateKey)key);
817         }
818         else
819             return;
820         }
821         else
822         if ( newCerts.length == 1 )
823             ks.setCertificateEntry ( alias, newCerts[ 0 ] );
824         else
825         return;
826         tree.addCert( alias, 0, newCerts );
827         dirty = true;
828     }
829     catch ( Exception e )
830     {
831         showException(e);
832     }
833     repaint ();
834     }
835     */

836
837     /*
838      * Imports a certificate from file; the user is asked for the file location.
839      * It then sets this certificate in a new KeyStore Trusted Certificate Entry.
840      *
841      */

842
843     private void addTrustee()
844     {
845         iaik.x509.X509Certificate cert = importCertificate();
846         if ( cert == null )
847     {
848         System.out.println ( "cert is null" );
849         return;
850     }
851         iaik.asn1.structures.Name subject = (iaik.asn1.structures.Name)cert.getSubjectDN ();
852         String JavaDoc caAlias = subject.getRDN ( ObjectID.commonName );
853         iaik.asn1.structures.Name issuer = (iaik.asn1.structures.Name) cert.getIssuerDN ();
854         String JavaDoc test = issuer.getRDN ( ObjectID.commonName );
855         
856     // String caAlias = cert.getSubjectDN ().getName ();
857
try
858     {
859         if ( caAlias.equals ( test ))
860         {
861             tree.addTrustedCert( caAlias, cert );
862         }
863         else
864         {
865         throw new RuntimeException JavaDoc("subject != issuer: " + caAlias + test );
866         }
867
868         repaint ();
869         dirty = true;
870     }
871     catch ( Exception JavaDoc e )
872     {
873         showException(e);
874     }
875         
876     }
877
878     private void deleteNode()
879     {
880     MutableTreeNode node = tree.getSelectedNode();
881     if( node == null )
882         return;
883
884     int option = JOptionPane.showConfirmDialog( null,
885                             "This will delete the selected entry! Continue?",
886                             "Delete",
887                             JOptionPane.OK_CANCEL_OPTION,
888                             JOptionPane.INFORMATION_MESSAGE);
889     if( option == JOptionPane.OK_OPTION )
890     {
891         try
892         {
893         node.removeFromParent();
894         tree.removeSelectedNode();
895         tree.reload();
896         dirty = true;
897         }
898         catch ( Exception JavaDoc e )
899         {
900         showException( e );
901         }
902     }
903     }
904
905
906
907     private void generateKeys()
908     throws NoKeyStoreException, NoSuchAlgorithmException, KeyStoreException
909     {
910     if( ks == null )
911         throw new NoKeyStoreException();
912
913     // get algorithm and key size from user
914
String JavaDoc [] keyparams = new String JavaDoc [] {"Algorithm", "KeyLength" };
915     char[][] passwds= new char[1][];
916
917     String JavaDoc listOptions[][] = {{"RSA","DSA"}, {"1024","2048"}};
918     
919         UserSponsor us = new UserSponsor("Generate Keys",
920                      "Please select Key Generation parameters",
921                      new String JavaDoc[]{"New Key Alias"},
922                      keyparams,
923                      listOptions,
924                                          new String JavaDoc[]{"Password"});
925
926         String JavaDoc[] aliasHolder = new String JavaDoc[1];
927
928     if( us.getInput( aliasHolder, keyparams, passwds) )
929     {
930         String JavaDoc algorithm = "DSA";
931         int keylength = 1024;
932         String JavaDoc alias = "<unknown>";
933
934         /* password to protect key entry */
935         char[] password = new char[0];
936        
937         if( keyparams[0] != null )
938         algorithm = keyparams[0];
939
940         if( keyparams[1] != null )
941         keylength = Integer.parseInt(keyparams[1]);
942
943         alias = aliasHolder[0];
944
945         // get selected alias
946
if( alias == null || alias.length() == 0 )
947         throw new IllegalArgumentException JavaDoc("No alias for key entry!");
948
949         // get key password
950
if( passwds[0] != null )
951         password = passwds[0];
952
953         // generate keys
954
KeyPairGenerator generator = null;
955
956         setCursor(java.awt.Cursor.getPredefinedCursor( java.awt.Cursor.WAIT_CURSOR ));
957     
958         try
959         {
960         generator = KeyPairGenerator.getInstance(algorithm, "IAIK");
961         }
962         catch (NoSuchProviderException ex)
963         {
964         throw new NoSuchAlgorithmException("Provider IAIK not found!");
965         }
966     
967         generator.initialize(keylength);
968         java.security.KeyPair JavaDoc keyPair = generator.generateKeyPair();
969     
970         // write a self-signed cert and store it in the keystore
971
iaik.x509.X509Certificate[] chain = null;
972         iaik.x509.X509Certificate selfsignedCert = null;
973         try
974         {
975         iaik.asn1.structures.Name dName = CertUtils.createName(alias);
976         selfsignedCert = CertUtils.createPublicKeyCert(dName, dName,
977                                    keyPair.getPublic(),
978                                    keyPair.getPrivate());
979
980         }
981         catch(java.security.InvalidKeyException JavaDoc ike)
982         {
983         throw new java.lang.Error JavaDoc("Internal Error: invalid keys generated!");
984         }
985         catch(java.security.cert.CertificateException JavaDoc ext)
986         {
987         ext.printStackTrace(); // should not happen
988
}
989         catch(iaik.x509.X509ExtensionException ext)
990         {
991         ext.printStackTrace(); // should not happen
992
}
993         dirty = true;
994         tree.addKey(alias, keyPair.getPrivate(), password );
995
996         repaint();
997
998         tree.addCert(alias, 0, selfsignedCert);
999         setCursor(java.awt.Cursor.getDefaultCursor());
1000        repaint();
1001    }
1002    }
1003    
1004    private void verifyChain()
1005    {
1006    if( ks == null )
1007        return;
1008
1009    String JavaDoc fileName = null;
1010    String JavaDoc alias = null;
1011 
1012    MutableTreeNode node = tree.getSelectedNode();
1013    if( node == null )
1014        return;
1015
1016    if( node instanceof KeyNode )
1017    {
1018        alias = ((KeyNode)node).getAlias();
1019        iaik.x509.X509Certificate[] chain =((KeyNode)node).getCertificateChain();
1020        int len = chain.length;
1021        try
1022        {
1023        chain[len-1].verify( chain [ len - 1 ].getPublicKey ());
1024
1025        for ( int i = len - 1; i > 0; i-- )
1026            chain[ i - 1 ].verify( chain[ i ].getPublicKey ());
1027
1028        if( tree.isTrusted( chain[ len - 1 ] ))
1029        {
1030            JOptionPane.showMessageDialog( null,
1031                            "Verification successful",
1032                            "Certificate Chain Verification",
1033                            JOptionPane.INFORMATION_MESSAGE);
1034        }
1035        else
1036        {
1037            JOptionPane.showMessageDialog( null,
1038                            "Verification failed, last chain element not trusted",
1039                            "Certificate Chain Verification",
1040                            JOptionPane.ERROR_MESSAGE);
1041        }
1042        }
1043        catch ( Exception JavaDoc ex )
1044        {
1045        showException( ex );
1046        }
1047    }
1048    
1049    }
1050
1051
1052
1053    public void showException(Exception JavaDoc e )
1054    {
1055    e.printStackTrace();
1056    JOptionPane.showMessageDialog(null,
1057                      e.getClass().getName() + ":" + e.getMessage(),
1058                      "Exception",
1059                      JOptionPane.ERROR_MESSAGE);
1060    }
1061
1062    public static void main(String JavaDoc[] args)
1063    {
1064    iaik.security.provider.IAIK.addAsProvider();
1065    new KeyStoreManager();
1066    }
1067
1068
1069    private class EventHandler
1070    implements /* MouseListener, ListSelectionListener, TreeSelectionListener,*/ ActionListener
1071    {
1072    /**
1073     * This method responds to menu selections.
1074     *
1075     * @param event
1076     */

1077    public void actionPerformed(ActionEvent event)
1078    {
1079        Object JavaDoc source = event.getSource();
1080        
1081        if (source instanceof JMenuItem)
1082        {
1083        try
1084        {
1085            if ((JMenuItem) source == exitMenuItem)
1086            _exit();
1087            if ((JMenuItem) source == openMenuItem)
1088            load();
1089            if ((JMenuItem) source == closeMenuItem)
1090            close();
1091            if ((JMenuItem) source == newMenuItem)
1092            newFile();
1093            if ((JMenuItem) source == saveMenuItem)
1094            save();
1095            if ((JMenuItem) source == saveAsMenuItem)
1096            saveAs();
1097
1098            if ((JMenuItem) source == generateKeyMenuItem)
1099            generateKeys();
1100            if ((JMenuItem) source == deleteKeyMenuItem)
1101            deleteNode();
1102            if ((JMenuItem) source == verifyChainMenuItem)
1103            verifyChain();
1104
1105            if ((JMenuItem) source == addTrusteeMenuItem)
1106            addTrustee();
1107            if ((JMenuItem) source == deleteTrusteeMenuItem)
1108            deleteNode();
1109
1110            if ((JMenuItem) source == exportCertMenuItem)
1111            exportCert();
1112            if ((JMenuItem) source == createCertMenuItem)
1113            createCert();
1114            if ((JMenuItem) source == importCertMenuItem)
1115            importCert();
1116            if ((JMenuItem) source == deleteCertMenuItem)
1117            deleteNode();
1118        }
1119        catch( NoKeyStoreException nke)
1120        {
1121            JOptionPane.showMessageDialog(null,
1122                          "Please select a valid key store",
1123                          "No Key Store selected",
1124                          JOptionPane.ERROR_MESSAGE);
1125        }
1126        catch( Exception JavaDoc e )
1127        {
1128            e.printStackTrace();
1129            JOptionPane.showMessageDialog(null,
1130                          e.getClass().getName() + ":" + e.getMessage(),
1131                          "Exception",
1132                          JOptionPane.ERROR_MESSAGE);
1133        }
1134        }
1135    }
1136    }
1137}
1138
1139
1140
1141
1142
1143
1144
Popular Tags