aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/plugin/desktoputil/X509CertificatePanel.java
blob: 53580307e47d03ab50c4f0a5d5dacafc6fa6b3e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.plugin.desktoputil;

import java.awt.*;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.security.interfaces.*;
import java.util.*;

import javax.naming.*;
import javax.naming.ldap.*;
import javax.security.auth.x500.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.tree.*;

import org.jitsi.service.resources.*;

/**
 * Panel that shows the content of an X509Certificate.
 */
public class X509CertificatePanel
    extends TransparentPanel
{
    private static final long serialVersionUID = -8368302061995971947L;

    private final JEditorPane infoTextPane = new JEditorPane();

    private final ResourceManagementService R
            = DesktopUtilActivator.getResources();

    /**
     * Constructs a X509 certificate panel from a single certificate.
     * If a chain is available instead use the second constructor.
     * This constructor is kept for backwards compatibility and for convenience
     * when there is only one certificate of interest.
     *
     * @param certificate <tt>X509Certificate</tt> object
     */
    public X509CertificatePanel(Certificate certificate)
    {
        this(new Certificate[]
        {
            certificate
        });
    }

    /**
     * Constructs a X509 certificate panel.
     *
     * @param certificates <tt>X509Certificate</tt> objects
     */
    public X509CertificatePanel(Certificate[] certificates)
    {
        setLayout(new BorderLayout(5, 5));

        // Certificate chain list
        TransparentPanel topPanel = new TransparentPanel(new BorderLayout());
        topPanel.add(new JLabel("<html><body><b>"
                + R.getI18NString("service.gui.CERT_INFO_CHAIN")
                + "</b></body></html>"), BorderLayout.NORTH);

        DefaultMutableTreeNode top = new DefaultMutableTreeNode();
        DefaultMutableTreeNode previous = top;
        for (int i = certificates.length - 1; i >= 0; i--)
        {
            Certificate cert = certificates[i];
            DefaultMutableTreeNode next = new DefaultMutableTreeNode(cert);
            previous.add(next);
            previous = next;
        }
        JTree tree = new JTree(top);
        tree.setBorder(new BevelBorder(BevelBorder.LOWERED));
        tree.setRootVisible(false);
        tree.setExpandsSelectedPaths(true);
        tree.getSelectionModel().setSelectionMode(
                TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.setCellRenderer(new DefaultTreeCellRenderer()
        {

            @Override
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value, boolean sel, boolean expanded, boolean leaf,
                    int row, boolean hasFocus)
            {
                JLabel component = (JLabel) super.getTreeCellRendererComponent(
                        tree, value, sel, expanded, leaf, row, hasFocus);
                if (value instanceof DefaultMutableTreeNode)
                {
                    Object o = ((DefaultMutableTreeNode) value).getUserObject();
                    if (o instanceof X509Certificate)
                    {
                        component.setText(
                                getSimplifiedName((X509Certificate) o));
                    }
                    else
                    {
                        // We don't know how to represent this certificate type,
                        // let's use the first 20 characters
                        String text = o.toString();
                        if (text.length() > 20)
                        {
                            text = text.substring(0, 20);
                        }
                        component.setText(text);
                    }
                }
                return component;
            }

        });
        tree.getSelectionModel().addTreeSelectionListener(
                new TreeSelectionListener()
        {

            @Override
            public void valueChanged(TreeSelectionEvent e)
            {
                valueChangedPerformed(e);
            }
        });
        tree.setSelectionPath(new TreePath(((
                (DefaultTreeModel)tree.getModel()).getPathToRoot(previous))));
        topPanel.add(tree, BorderLayout.CENTER);

        add(topPanel, BorderLayout.NORTH);

        // Certificate details pane
        Caret caret = infoTextPane.getCaret();
        if (caret instanceof DefaultCaret)
        {
            ((DefaultCaret) caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
        }

        /*
         * Make JEditorPane respect our default font because we will be using it
         * to just display text.
         */
        infoTextPane.putClientProperty(
                JEditorPane.HONOR_DISPLAY_PROPERTIES,
                true);

        infoTextPane.setOpaque(false);
        infoTextPane.setEditable(false);
        infoTextPane.setContentType("text/html");
        infoTextPane.setText(toString(certificates[0]));

        final JScrollPane certScroll = new JScrollPane(infoTextPane);
        certScroll.setPreferredSize(new Dimension(300, 500));
        add(certScroll, BorderLayout.CENTER);
    }

    /**
     * Creates a String representation of the given object.
     * @param certificate to print
     * @return the String representation
     */
    private String toString(Object certificate)
    {
        final StringBuilder sb = new StringBuilder();
        sb.append("<html><body>\n");

        if (certificate instanceof X509Certificate)
        {
            renderX509(sb, (X509Certificate) certificate);
        }
        else
        {
            sb.append("<pre>\n");
            sb.append(certificate.toString());
            sb.append("</pre>\n");
        }

        sb.append("</body></html>");
        return sb.toString();
    }

    /**
     * Appends an HTML representation of the given X509Certificate. 
     * @param sb StringBuilder to append to
     * @param certificate to print
     */
    private void renderX509(StringBuilder sb, X509Certificate certificate)
    {
        X500Principal issuer = certificate.getIssuerX500Principal();
        X500Principal subject = certificate.getSubjectX500Principal();

        sb.append("<table cellspacing='1' cellpadding='1'>\n");

        // subject
        addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_TO"));
        try
        {
            for(Rdn name : new LdapName(subject.getName()).getRdns())
            {
                String nameType = name.getType();
                String lblKey = "service.gui.CERT_INFO_" + nameType;
                String lbl = R.getI18NString(lblKey);

                if ((lbl == null) || ("!" + lblKey + "!").equals(lbl))
                    lbl = nameType;

                final String value;
                Object nameValue = name.getValue();

                if (nameValue instanceof byte[])
                {
                    byte[] nameValueAsByteArray = (byte[]) nameValue;

                    value
                        = getHex(nameValueAsByteArray) + " ("
                            + new String(nameValueAsByteArray) + ")";
                }
                else
                    value = nameValue.toString();

                addField(sb, lbl, value);
            }
        }
        catch (InvalidNameException ine)
        {
            addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), 
                    subject.getName());
        }

        // issuer
        addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_BY"));
        try
        {
            for(Rdn name : new LdapName(issuer.getName()).getRdns())
            {
                String nameType = name.getType();
                String lblKey = "service.gui.CERT_INFO_" + nameType;
                String lbl = R.getI18NString(lblKey);

                if ((lbl == null) || ("!" + lblKey + "!").equals(lbl))
                    lbl = nameType;

                final String value;
                Object nameValue = name.getValue();

                if (nameValue instanceof byte[])
                {
                    byte[] nameValueAsByteArray = (byte[]) nameValue;

                    value
                        = getHex(nameValueAsByteArray) + " ("
                            + new String(nameValueAsByteArray) + ")";
                }
                else
                    value = nameValue.toString();

                addField(sb, lbl, value);
            }
        }
        catch (InvalidNameException ine)
        {
            addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), 
                    issuer.getName());
        }

        // validity
        addTitle(sb, R.getI18NString("service.gui.CERT_INFO_VALIDITY"));
        addField(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_ON"),
                certificate.getNotBefore().toString());
        addField(sb, R.getI18NString("service.gui.CERT_INFO_EXPIRES_ON"),
                certificate.getNotAfter().toString());

        addTitle(sb, R.getI18NString("service.gui.CERT_INFO_FINGERPRINTS"));
        try
        {
            String sha256String = getThumbprint(certificate, "SHA-256");
            String sha1String = getThumbprint(certificate, "SHA1");

            addField(sb, "SHA256:", sha256String, 48);
            addField(sb, "SHA1:", sha1String, 72);
        }
        catch (CertificateException e)
        {
            // do nothing as we cannot show this value
        }

        addTitle(sb, R.getI18NString("service.gui.CERT_INFO_CERT_DETAILS"));

        addField(sb, R.getI18NString("service.gui.CERT_INFO_SER_NUM"), 
                certificate.getSerialNumber().toString());

        addField(sb, R.getI18NString("service.gui.CERT_INFO_VER"), 
                String.valueOf(certificate.getVersion()));

        addField(sb, R.getI18NString("service.gui.CERT_INFO_SIGN_ALG"),
                String.valueOf(certificate.getSigAlgName()));

        addTitle(sb, R.getI18NString("service.gui.CERT_INFO_PUB_KEY_INFO"));

        addField(sb, R.getI18NString("service.gui.CERT_INFO_ALG"),
            certificate.getPublicKey().getAlgorithm());

        if(certificate.getPublicKey().getAlgorithm().equals("RSA"))
        {
            RSAPublicKey key = (RSAPublicKey)certificate.getPublicKey();

            addField(sb,
                R.getI18NString("service.gui.CERT_INFO_PUB_KEY"),
                R.getI18NString("service.gui.CERT_INFO_KEY_BITS_PRINT",
                    new String[]{
                        String.valueOf(
                            (key.getModulus().toByteArray().length-1)*8)
                    }),
                getHex(key.getModulus().toByteArray()),
                48);

            addField(sb, R.getI18NString("service.gui.CERT_INFO_EXP"), 
                    key.getPublicExponent().toString());

            addField(sb, R.getI18NString("service.gui.CERT_INFO_KEY_SIZE"),
                    R.getI18NString(
                    "service.gui.CERT_INFO_KEY_BITS_PRINT",
                    new String[]{
                        String.valueOf(key.getModulus().bitLength())}));
        }
        else if(certificate.getPublicKey().getAlgorithm().equals("DSA"))
        {
            DSAPublicKey key =
                (DSAPublicKey)certificate.getPublicKey();

            addField(sb, "Y:", key.getY().toString(16));
        }

        addField(sb, R.getI18NString("service.gui.CERT_INFO_SIGN"),
            R.getI18NString(
                    "service.gui.CERT_INFO_KEY_BITS_PRINT",
                    new String[]{
                        String.valueOf(certificate.getSignature().length*8),
                    }),
                getHex(certificate.getSignature()),
                48);

        sb.append("</table>\n");
    }

    /**
     * Add a title.
     *
     * @param sb StringBuilder to append to
     * @param title to print
     */
    private void addTitle(StringBuilder sb, String title)
    {
        sb.append("<tr><td colspan='2'")
                .append(" style='margin-top: 5pt; white-space: nowrap'><p><b>")
                .append(title).append("</b></p></td></tr>\n");
    }

    /**
     * Add a field.
     * @param sb StringBuilder to append to
     * @param field name of the certificate field
     * @param value to print
     */
    private void addField(StringBuilder sb, String field, String value)
    {
        addField(sb, field, value, null, 0);
    }

    /**
     * Add a field.
     * @param sb StringBuilder to append to
     * @param field name of the certificate field
     * @param value to print
     * @param wrap force-wrap after number of characters
     */
    private void addField(StringBuilder sb, String field, String value,
        int wrap)
    {
        addField(sb, field, value, null, wrap);
    }

    /**
     * Add a field.
     * @param sb StringBuilder to append to
     * @param field name of the certificate field
     * @param value to print (not wrapped)
     * @param otherValue second line of value to print (wrapped)
     * @param wrap force-wrap after number of characters
     */
    private void addField(StringBuilder sb, String field, String value,
        String otherValue, int wrap)
    {
        sb.append("<tr><td style='margin-left: 5pt; margin-right: 25pt;")
            .append("white-space: nowrap' valign='top'>")
            .append(field).append("</td><td><span");

        if (otherValue != null)
        {
            sb.append('>').append(value).append("</span><br/><span");
            value = otherValue;
        }

        if (wrap > 0)
        {
            sb.append(" style='font-family:monospace'>");
            for (int i = 0; i < value.length(); i++)
            {
                if (i % wrap == 0 && i > 0)
                {
                    sb.append("<br/>");
                }

                sb.append(value.charAt(i));
            }
        }
        else
        {
            sb.append(">");
            sb.append(value);
        }

        sb.append("</span></td></tr>");
    }

    /**
     * Converts the byte array to hex string.
     * @param raw the data.
     * @return the hex string.
     */
    private String getHex( byte [] raw )
    {
        if (raw == null)
            return null;

        StringBuilder hex = new StringBuilder(2 * raw.length);
        Formatter f = new Formatter(hex);
        try
        {
            for (byte b : raw)
                f.format("%02X:", b);
        }
        finally
        {
            f.close();
        }
        return hex.substring(0, hex.length() - 1);
    }

    /**
     * Calculates the hash of the certificate known as the "thumbprint"
     * and returns it as a string representation.
     *
     * @param cert The certificate to hash.
     * @param algorithm The hash algorithm to use.
     * @return The SHA-1 hash of the certificate.
     * @throws CertificateException
     */
    private static String getThumbprint(X509Certificate cert, String algorithm)
        throws CertificateException
    {
        MessageDigest digest;
        try
        {
            digest = MessageDigest.getInstance(algorithm);
        }
        catch (NoSuchAlgorithmException e)
        {
            throw new CertificateException(e);
        }

        byte[] encodedCert = cert.getEncoded();
        StringBuilder sb = new StringBuilder(encodedCert.length * 2);
        Formatter f = new Formatter(sb);
        try
        {
            for (byte b : digest.digest(encodedCert))
                f.format("%02X:", b);
        }
        finally
        {
            f.close();
        }

        return sb.substring(0, sb.length() - 1);
    }

    /**
     * Construct a "simplified name" based on the subject DN from the
     * certificate. The purpose is to have something shorter to display in the
     * list. The name used is one of the following DN parts, if
     * available, otherwise the complete DN:
     * 'CN', 'OU' or else 'O'.
     * @param cert to read subject DN from
     * @return the simplified name
     */
    private static String getSimplifiedName(X509Certificate cert)
    {
        final HashMap<String, String> parts = new HashMap<String, String>();
        try
        {
            for (Rdn name : new LdapName(
                    cert.getSubjectX500Principal().getName()).getRdns())
            {
                if (name.getType() != null && name.getValue() != null)
                {
                    parts.put(name.getType(), name.getValue().toString());
                }
            }
        }
        catch (InvalidNameException ignored) // NOPMD
        {
        }

        String result = parts.get("CN");
        if (result == null)
        {
            result = parts.get("OU");
        }
        if (result == null)
        {
            result = parts.get("O");
        }
        if (result == null)
        {
            result = cert.getSubjectX500Principal().getName();
        }
        return result;
    }

    /**
     * Called when the selection changed in the tree.
     * Loads the selected certificate.
     * @param e the event
     */
    private void valueChangedPerformed(TreeSelectionEvent e)
    {
        Object o = e.getNewLeadSelectionPath().getLastPathComponent();
        if (o instanceof DefaultMutableTreeNode)
        {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) o;
            infoTextPane.setText(toString(node.getUserObject()));
        }
    }
}