KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ca > commons > security > cert > CertDetailsViewPanel


1
2 package com.ca.commons.security.cert;
3
4 import java.awt.*;
5 import java.awt.event.*;
6 import javax.swing.*;
7 import javax.swing.event.*;
8 import javax.swing.table.*;
9 import javax.swing.border.*;
10 import java.util.*;
11 import java.io.*;
12 import java.lang.String JavaDoc;
13
14 import java.security.cert.*;
15 import java.security.*;
16
17 import java.security.interfaces.DSAPublicKey JavaDoc;
18 import java.security.interfaces.RSAPublicKey JavaDoc;
19
20 import com.ca.commons.security.asn1.*;
21 import com.ca.commons.security.cert.extensions.*;
22 import com.ca.commons.cbutil.*;
23
24 /**
25  * Second tab: Display details information about the certificate.
26  * Show combo <All>, Version 1 Fields Only, Extensions Only, Critical
27  * Extensions Only, Properties Only. Field-Value table, Field View text area,
28  * &Edit Properties... button disabled, &Copy to File... button.
29  *
30  * @author vbui
31  */

32 public class CertDetailsViewPanel extends JPanel
33 {
34     private X509Certificate cert = null;
35
36     // visual elements
37
private CBToolBarButton editPropertiesButton = new CBToolBarButton("&Edit Properties...", "Edit Properties...");
38     private CBToolBarButton copyToFileButton = new CBToolBarButton("&Copy to File...", "Copy to File...");
39
40     private JLabel showLabel = new JLabel("Show:");
41
42     private String JavaDoc[] showOptions =
43             {
44                     "<All>", "Version 1 Fields Only",
45                     "Extensions Only", "Critical Extensions Only",
46                     "Properties Only"
47             };
48     private JComboBox showCombo = new JComboBox(showOptions);
49
50     // table to display cert details with sample data
51
private JTable certDetailsTable = new JTable();
52     private JTextArea fieldText = new JTextArea(5, 20);
53
54     /**
55      * Constructor.
56      */

57     public CertDetailsViewPanel(X509Certificate cert)
58     {
59         this.cert = cert;
60
61         // certDetailsTable cell renderer
62
certDetailsTable.setDefaultRenderer(JLabel.class,
63                                  new LabelRenderer(true));
64
65         // increase row height to fit labels with graphics
66
certDetailsTable.setRowHeight(19);
67
68         certDetailsTable.setShowGrid(false);
69
70         // prepare visual elements
71
editPropertiesButton.setWidthHeight(110, 23);
72         copyToFileButton.setWidthHeight(110, 23);
73
74         editPropertiesButton.setEnabled(false);
75
76         // fieldText.setFont(new Font("Monospaced", Font.PLAIN, 11));
77

78         showCombo.setPreferredSize(new Dimension(200, 23));
79         showCombo.setMinimumSize(new Dimension(200, 23));
80
81         certDetailsTable.setModel(new CertDetailsTableModel(cert, 0));
82         certDetailsTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
83         certDetailsTable.getSelectionModel().addListSelectionListener(
84                 new ListSelectionListener()
85         {
86             public void valueChanged(ListSelectionEvent e)
87             {
88                 certDetailsTable_selectionChanged(e);
89             }
90         });
91
92         // layout
93
JPanel buttonsPanel = new JPanel();
94         buttonsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
95
96         // buttonsPanel.add(editPropertiesButton);
97

98         buttonsPanel.add(copyToFileButton);
99
100         setLayout(new GridBagLayout());
101         add(showLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
102                 GridBagConstraints.WEST, GridBagConstraints.NONE,
103                 new Insets(10, 10, 10, 10), 0, 0));
104         add(showCombo, new GridBagConstraints(1, 0, 2, 1, 1.0, 0.0,
105                 GridBagConstraints.WEST, GridBagConstraints.NONE,
106                 new Insets(10, 0, 10, 10), 0, 0));
107         add(new JScrollPane(certDetailsTable), new GridBagConstraints(0, 1, 3, 1, 1.0, 1.0,
108                 GridBagConstraints.CENTER, GridBagConstraints.BOTH,
109                 new Insets(0, 10, 10, 10), 0, 0));
110         add(new JScrollPane(fieldText), new GridBagConstraints(0, 2, 3, 1, 1.0, 1.0,
111                 GridBagConstraints.CENTER, GridBagConstraints.BOTH,
112                 new Insets(5, 10, 6, 10), 0, 0));
113         add(buttonsPanel, new GridBagConstraints(0, 3, 3, 1, 1.0, 0.0,
114                 GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
115                 new Insets(0, 10, 6, 5), 0, 0));
116
117         // add listeners
118
editPropertiesButton.addActionListener(new ActionListener()
119         {
120             public void actionPerformed(ActionEvent e)
121             {
122                 editPropertiesButton_actionPerformed(e);
123             }
124         });
125
126         copyToFileButton.addActionListener(new ActionListener()
127         {
128             public void actionPerformed(ActionEvent e)
129             {
130                 copyToFileButton_actionPerformed(e);
131             }
132         });
133
134         showCombo.addItemListener(new ItemListener()
135         {
136             public void itemStateChanged(ItemEvent e)
137             {
138                 showCombo_itemStateChanged(e);
139             }
140         });
141     }
142
143     /**
144      * Edit properties action.
145      */

146     private void editPropertiesButton_actionPerformed(ActionEvent e)
147     {
148         System.out.println("Edit the selected property ");
149     }
150
151     /**
152      * Copy to file action.
153      */

154     private void copyToFileButton_actionPerformed(ActionEvent e)
155     {
156         String JavaDoc filename = CBUtility.chooseFileToSave(this, "Please specify a location to save this certificate",
157                 new String JavaDoc[] {"der"}, "Certificate file (*.der)");
158         if (filename == null) return;
159
160         if (!filename.toLowerCase().endsWith(".der"))
161             filename = filename + ".der";
162
163         if (!CBUtility.okToWriteFile(CBUtility.getParentFrame(this), filename))
164         {
165             return;
166         }
167
168         try
169         {
170             FileOutputStream fos = new FileOutputStream(filename);
171             byte[] derout = cert.getEncoded();
172             fos.write(derout);
173             fos.close();
174         }
175         catch (Exception JavaDoc ex)
176         {
177             JOptionPane.showMessageDialog(this,
178                     ex.getMessage(),
179                     "Error!", JOptionPane.ERROR_MESSAGE);
180         }
181     }
182
183     /**
184      * Selection on the cert details table changed.
185      */

186     private void certDetailsTable_selectionChanged(ListSelectionEvent e)
187     {
188         int selectedRow = certDetailsTable.getSelectedRow();
189         if (selectedRow >= 0)
190         {
191             String JavaDoc selectedValue=certDetailsTable.getValueAt(selectedRow, 1).toString();
192             CertDetailsTableModel model = (CertDetailsTableModel) certDetailsTable.getModel();
193
194             Object JavaDoc details = model.getDetails(selectedValue);
195
196             if (details != null)
197                 fieldText.setText(details.toString());
198             else
199                 fieldText.setText(selectedValue);
200         }
201     }
202
203     /**
204      * Selection on the show combo box changed.
205      */

206     private void showCombo_itemStateChanged(ItemEvent e)
207     {
208         ((CertDetailsTableModel) certDetailsTable.getModel()).
209                 setViewMode(showCombo.getSelectedIndex());
210         fieldText.setText("");
211     }
212 }
213
214 class LabelRenderer extends JLabel implements TableCellRenderer
215 {
216     Border unselectedBorder = null;
217     Border selectedBorder = null;
218     boolean isBordered = true;
219
220     public LabelRenderer(boolean isBordered)
221     {
222         super();
223         this.isBordered = isBordered;
224         setOpaque(true); //MUST do this for background to show up.
225
}
226
227     public Component getTableCellRendererComponent(
228                             JTable table, Object JavaDoc label,
229                             boolean isSelected, boolean hasFocus,
230                             int row, int column)
231     {
232         setIcon(((JLabel) label).getIcon());
233         setText(((JLabel) label).getText());
234         setBackground(Color.white);
235
236         if (isBordered)
237         {
238             if (isSelected)
239             {
240                 if (selectedBorder == null)
241                 {
242                     selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
243                                               table.getSelectionBackground());
244                 }
245                 setBorder(selectedBorder);
246             }
247             else
248             {
249                 if (unselectedBorder == null)
250                 {
251                     unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
252                                               table.getBackground());
253                 }
254                 setBorder(unselectedBorder);
255             }
256         }
257         return this;
258     }
259 }
260
261 class CertDetailsTableModel extends AbstractTableModel
262 {
263     private String JavaDoc[] headers =
264             {
265                 "Field", "Value"
266             };
267
268     private Vector data = new Vector();
269     private X509Certificate cert = null;
270
271     private Hashtable briefDetails = new Hashtable();
272
273     public Object JavaDoc getDetails(String JavaDoc brief)
274     {
275         return briefDetails.get(brief);
276     }
277
278     /**
279      * Table Model Constructor
280      */

281     public CertDetailsTableModel(X509Certificate cert, int viewMode)
282     {
283         this.cert = cert;
284         setViewMode(viewMode);
285     }
286
287     /**
288      * Sets the view mode in CertDetailsViewPanel. The viewMode determines
289      * which attributes and extensions are shown. <br>
290      * View Modes: <br>
291      * <item>
292      * <li> 0 All
293      * <li> 1 X509 V1 attributes only
294      * <li> 2 Extensions only
295      * <li> 3 Critical Extensions only
296      * <li> 4 Properties only
297      * </item>
298      */

299     public void setViewMode(int viewMode)
300     {
301         data = new Vector();
302
303         if (cert == null)
304             return;
305
306         if (viewMode == 0 || viewMode == 1)
307         {
308             Vector versionRow = new Vector();
309             versionRow.add(new JLabel("Version", CertViewer.attributeIcon, SwingConstants.LEFT));
310             versionRow.add("V" + cert.getVersion());
311             data.add(versionRow);
312
313             Vector serialNumberRow = new Vector();
314             serialNumberRow.add(new JLabel("Serial Number", CertViewer.attributeIcon, SwingConstants.LEFT));
315             serialNumberRow.add(CBParse.bytes2Hex(cert.getSerialNumber().toByteArray()));
316             data.add(serialNumberRow);
317
318             Vector sigAlgRow = new Vector();
319             sigAlgRow.add(new JLabel("Signature Algorithm", CertViewer.attributeIcon, SwingConstants.LEFT));
320             sigAlgRow.add(cert.getSigAlgName());
321             data.add(sigAlgRow);
322
323             Vector issuerRow = new Vector();
324             issuerRow.add(new JLabel("Issuer", CertViewer.attributeIcon, SwingConstants.LEFT));
325             issuerRow.add(cert.getIssuerX500Principal().getName());
326             data.add(issuerRow);
327
328             Vector fromRow = new Vector();
329             fromRow.add(new JLabel("Valid From", CertViewer.attributeIcon, SwingConstants.LEFT));
330             fromRow.add(cert.getNotBefore());
331             data.add(fromRow);
332
333             Vector toRow = new Vector();
334             toRow.add(new JLabel("Valid To", CertViewer.attributeIcon, SwingConstants.LEFT));
335             toRow.add(cert.getNotAfter());
336             data.add(toRow);
337
338             Vector subjectRow = new Vector();
339             subjectRow.add(new JLabel("Subject", CertViewer.attributeIcon, SwingConstants.LEFT));
340
341
342             // debugPrint();
343

344             subjectRow.add(cert.getSubjectX500Principal().getName());
345             data.add(subjectRow);
346
347             Vector publicKeyRow = new Vector();
348             publicKeyRow.add(new JLabel("Public Key", CertViewer.attributeIcon, SwingConstants.LEFT));
349             PublicKey JavaDoc pubKey = cert.getPublicKey();
350             String JavaDoc publicKeyString = pubKey.getAlgorithm();
351             if (pubKey instanceof RSAPublicKey JavaDoc)
352                 publicKeyString = publicKeyString + " (" + ((RSAPublicKey JavaDoc) pubKey).getModulus().bitLength() + " Bits)";
353             else if (pubKey instanceof DSAPublicKey JavaDoc)
354                 publicKeyString = publicKeyString + " (" + ((DSAPublicKey JavaDoc) pubKey).getY().bitLength() + " Bits)";
355             publicKeyRow.add(publicKeyString);
356
357             /*
358             if (pubKey instanceof RSAPublicKey)
359                 briefDetails.put(publicKeyString, CBUtility.bytes2HexSplit(((RSAPublicKey)pubKey).getModulus().toByteArray(), 4, 36));
360             else
361                 briefDetails.put(publicKeyString, StaticUtil.bytes2Hex(pubKey.getEncoded(), 4, 36));
362             */

363
364             data.add(publicKeyRow);
365         }
366
367         if (viewMode == 0 || viewMode == 2)
368         {
369             Set nonCritSet = cert.getNonCriticalExtensionOIDs();
370             if (nonCritSet != null && !nonCritSet.isEmpty())
371             {
372                 for (Iterator i = nonCritSet.iterator(); i.hasNext();)
373                 {
374                     String JavaDoc oid = (String JavaDoc)i.next();
375                     Vector nonCritRow = new Vector();
376                     String JavaDoc extname = getNameFromOID(oid);
377                     nonCritRow.add(new JLabel(extname, CertViewer.extensionIcon, SwingConstants.LEFT));
378                     addExtDetails(nonCritRow,
379                             printext(extname, cert.getExtensionValue(oid)).toString());
380                     data.add(nonCritRow);
381                 }
382             }
383         }
384
385         if (viewMode == 0 || viewMode == 2 || viewMode == 3)
386         {
387             Set critSet = cert.getCriticalExtensionOIDs();
388             if (critSet != null && !critSet.isEmpty())
389             {
390                 for (Iterator i = critSet.iterator(); i.hasNext();)
391                 {
392                     String JavaDoc oid = (String JavaDoc)i.next();
393                     Vector critRow = new Vector();
394                     String JavaDoc extname = getNameFromOID(oid);
395                     critRow.add(new JLabel(extname, CertViewer.criticalExtensionIcon, SwingConstants.LEFT));
396                     addExtDetails(critRow,
397                             printext(extname, cert.getExtensionValue(oid)).toString());
398                     data.add(critRow);
399                 }
400             }
401         }
402
403         if (viewMode == 0 || viewMode == 4)
404         {
405             Vector thumbprintAlgorithmRow = new Vector();
406             thumbprintAlgorithmRow.add(new JLabel("Thumbprint Algorithm", CertViewer.thumbprintIcon, SwingConstants.LEFT));
407             thumbprintAlgorithmRow.add("sha1");
408             data.add(thumbprintAlgorithmRow);
409
410             try
411             {
412                 Vector thumbprintRow = new Vector();
413                 thumbprintRow.add(new JLabel("Thumbprint", CertViewer.thumbprintIcon, SwingConstants.LEFT));
414                 MessageDigest md = MessageDigest.getInstance("SHA");
415                 byte[] hash = md.digest(cert.getEncoded());
416                 thumbprintRow.add(CBParse.bytes2HexSplit(hash, 4));
417                 data.add(thumbprintRow);
418             }
419             catch (Exception JavaDoc ex)
420             {
421                 ex.printStackTrace();
422             }
423         }
424
425         fireTableStructureChanged();
426     }
427
428     private void debugPrint()
429     {
430         System.out.println("get dn: " + cert.getSubjectDN());
431         System.out.println("get dn name: " + cert.getSubjectDN().getName());
432         System.out.println("getName: " + cert.getSubjectX500Principal().getName());
433         System.out.println("rfc2253: " + cert.getSubjectX500Principal().getName("RFC2253"));
434         System.out.println("canonical: " +cert.getSubjectX500Principal().getName("CANONICAL"));
435         System.out.println("toString: " + cert.getSubjectX500Principal().toString());
436         System.out.print("der: ");
437         byte[] bytes = cert.getSubjectX500Principal().getEncoded();
438         for (int i=0; i<bytes.length; i++)
439             System.out.print(" " + bytes[i]);
440         String JavaDoc name = cert.getSubjectX500Principal().getName();
441         System.out.println();
442         System.out.println("default: ");
443
444         bytes = name.getBytes();
445         System.out.println("straight name: " + CBParse.bytes2Hex(bytes));
446         try
447         {
448             System.out.println("unicode: " + CBParse.bytes2Hex(name.getBytes("UTF-16")));
449             System.out.println("utf-8: " + CBParse.bytes2Hex(name.getBytes("UTF-8")));
450         }
451         catch (UnsupportedEncodingException e2)
452         {
453             e2.printStackTrace();
454         }
455
456         System.out.println();
457     }
458
459     private void addExtDetails(Vector row, String JavaDoc extDetails)
460     {
461         StringTokenizer tok = new StringTokenizer(extDetails, "\n");
462         if (tok.countTokens() > 1)
463         {
464             String JavaDoc brief = tok.nextToken();
465             row.addElement(brief);
466             briefDetails.put(brief, extDetails);
467         }
468         else
469         {
470             row.addElement(extDetails);
471         }
472     }
473
474     private String JavaDoc getNameFromOID(String JavaDoc oid)
475     {
476         return ASN1OID.getName(oid);
477     }
478
479     private Object JavaDoc printext(String JavaDoc extname, byte[] extvalue)
480     {
481         try
482         {
483             DERCoder derCoder = new DERCoder();
484             ASN1Object ext = derCoder.decode(extvalue);
485             ASN1Object rext = null;
486
487             if (ext.isASN1Type(ASN1Type.OCTET_STRING))
488                 rext = derCoder.decode((byte[])ext.getValue());
489
490             V3Extension v3e = null;
491             boolean done = false;
492
493             if (extname.equals("Authority Information Access"))
494             {
495                 v3e = new AuthorityInfoAccess();
496                 done = true;
497             }
498             else if (extname.equals("Subject Key Identifier"))
499             {
500                 v3e = new SubjectKeyIdentifier();
501                 done = true;
502             }
503             else if (extname.equals("Key Usage"))
504             {
505                 v3e = new KeyUsage();
506                 done = true;
507             }
508             else if (extname.equals("Subject Alternative Name"))
509             {
510                 v3e = new SubjectAltName();
511                 done = true;
512             }
513             else if (extname.equals("Issuer Alternative Name"))
514             {
515                 v3e = new IssuerAltName();
516                 done = true;
517             }
518             else if (extname.equals("Basic Constraints"))
519             {
520                 v3e = new BasicConstraints();
521                 done = true;
522             }
523             else if (extname.equals("Name Constraints"))
524             {
525                 v3e = new NameConstraints();
526             }
527             else if (extname.equals("Certificate Policies"))
528             {
529                 v3e = new CertificatePolicies();
530                 done = true;
531             }
532             else if (extname.equals("Policy Mappings"))
533             {
534                 v3e = new PolicyMappings();
535             }
536             else if (extname.equals("Authority Key Identifier"))
537             {
538                 v3e = new AuthorityKeyIdentifier();
539                 done = true;
540             }
541             else if (extname.equals("Policy Constraints"))
542             {
543                 v3e = new PolicyConstraints();
544             }
545             else if (extname.equals("Extended Key Usage"))
546             {
547                 v3e = new ExtendedKeyUsage();
548                 done = true;
549             }
550             else if (extname.equals("CRL Distribution Points"))
551             {
552                 v3e = new CRLDistributionPoints();
553                 done = true;
554             }
555             else if (extname.equals("Private Key Usage Period"))
556             {
557                 v3e = new PrivateKeyUsagePeriod();
558                 done = true;
559             }
560             else if (extname.equals("Netscape Cert Type"))
561             {
562                 v3e = new NetscapeCertType();
563                 done = true;
564             }
565             else
566             {
567                 // v3e = new UnknownExtension(new ObjectID(oid, extname));
568
}
569
570             if (!done)
571             {
572                 System.out.println("extname: " + extname);
573                 System.out.println("exttype: " + rext);
574                 System.out.println("extvalu: " + rext.getValue());
575                 System.out.println("extbyte: " + CBParse.bytes2HexSplit((byte[])ext.getValue(), 4, 36));
576             }
577
578             if (v3e != null)
579             {
580                 v3e.init(rext);
581                 if (v3e.toString() == null)
582                     throw new Exception JavaDoc("Could not read extension: " + extname);
583                 return v3e;
584             }
585         }
586         catch (Exception JavaDoc ex)
587         {
588             ex.printStackTrace();
589         }
590
591         return CBParse.bytes2HexSplit(extvalue, 4, 36);
592     }
593
594     public int getRowCount()
595     {
596         return data.size();
597     }
598
599     public int getColumnCount()
600     {
601         return 2;
602     }
603
604     public String JavaDoc getColumnName(int col)
605     {
606         return headers[col];
607     }
608
609     public Object JavaDoc getValueAt(int row, int col)
610     {
611         return ((Vector)data.elementAt(row)).elementAt(col);
612     }
613
614     public Class JavaDoc getColumnClass(int col)
615     {
616         return getValueAt(0, col).getClass();
617     }
618 }
619
Popular Tags