summaryrefslogtreecommitdiffstats
path: root/base/util/src/netscape/security/util/CertPrettyPrint.java
blob: 34dda33b61a111c6b0dbbb46d0e2c2475a87eee4 (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
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;

import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.text.DateFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.TimeZone;

import netscape.security.x509.CertificateExtensions;
import netscape.security.x509.CertificateX509Key;
import netscape.security.x509.Extension;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509CertInfo;
import netscape.security.x509.X509Key;

import org.mozilla.jss.asn1.ASN1Util;
import org.mozilla.jss.asn1.SET;
import org.mozilla.jss.pkcs7.ContentInfo;
import org.mozilla.jss.pkcs7.SignedData;

/**
 * This class will display the certificate content in predefined
 * format.
 *
 * @author Jack Pan-Chen
 * @version $Revision$, $Date$
 */
public class CertPrettyPrint {

    /*==========================================================
     * constants
     *==========================================================*/
    private final static String CUSTOM_LOCALE = "Custom";

    /*==========================================================
     * variables
     *==========================================================*/
    private X509CertImpl mX509Cert = null;
    private PrettyPrintFormat pp = null;
    private byte[] mCert_b = null;

    /*==========================================================
     * constructors
     *==========================================================*/

    public CertPrettyPrint(Certificate cert) {
        if (cert instanceof X509CertImpl)
            mX509Cert = (X509CertImpl) cert;

        pp = new PrettyPrintFormat(":");
    }

    public CertPrettyPrint(byte[] certb) {
        mCert_b = certb;
        pp = new PrettyPrintFormat(":");
    }

    /*==========================================================
     * public methods
     *==========================================================*/

    /**
     * This method return string representation of the certificate
     * in predefined format using specified client local. I18N Support.
     *
     * @param clientLocale Locale to be used for localization
     * @return string representation of the certificate
     */
    public String toString(Locale clientLocale) {

        if (mX509Cert != null)
            return X509toString(clientLocale);
        else if (mCert_b != null)
            return pkcs7toString(clientLocale);
        else
            return null;
    }

    public String pkcs7toString(Locale clientLocale) {
        StringBuffer content=new StringBuffer();

        try {
            mX509Cert = new X509CertImpl(mCert_b);
            return toString(clientLocale);
        } catch (Exception e) {
        }

        ContentInfo ci = null;
        try {
            ci = (ContentInfo)
                    ASN1Util.decode(ContentInfo.getTemplate(), mCert_b);
        } catch (Exception e) {
            return "";
        }

        if (ci.getContentType().equals(ContentInfo.SIGNED_DATA)) {
            SignedData sd = null;
            try {
                sd = (SignedData) ci.getInterpretedContent();
            } catch (Exception e) {
                return "";
            }

            if (sd.hasCertificates()) {
                SET certs = sd.getCertificates();

                for (int i = 0; i < certs.size(); i++) {
                    org.mozilla.jss.pkix.cert.Certificate cert =
                            (org.mozilla.jss.pkix.cert.Certificate) certs.elementAt(i);
                    X509CertImpl certImpl = null;
                    try {
                        certImpl = new X509CertImpl(
                                ASN1Util.encode(cert));
                    } catch (Exception e) {
                    }

                    CertPrettyPrint print = new CertPrettyPrint(certImpl);
                    content.append(print.toString(Locale.getDefault()));
                    content.append("\n");
                }

                return content.toString();
            }
        }

        return content.toString();
    }

    public String stripCertBrackets(String s) {
        if (s == null) {
            return s;
        }

        if ((s.startsWith("-----BEGIN CERTIFICATE-----")) &&
                (s.endsWith("-----END CERTIFICATE-----"))) {
            return (s.substring(27, (s.length() - 25)));
        }

        // To support Thawte's header and footer
        if ((s.startsWith("-----BEGIN PKCS #7 SIGNED DATA-----")) &&
                (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
            return (s.substring(35, (s.length() - 33)));
        }

        return s;
    }

    public String normalizeCertStr(String s) {
        StringBuffer val = new StringBuffer();

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '\n') {
                continue;
            } else if (s.charAt(i) == '\r') {
                continue;
            } else if (s.charAt(i) == '"') {
                continue;
            } else if (s.charAt(i) == ' ') {
                continue;
            }
            val.append(s.charAt(i));
        }
        return val.toString();
    }

    public String X509toString(Locale clientLocale) {

        //get I18N resources
        ResourceBundle resource = ResourceBundle.getBundle(
                PrettyPrintResources.class.getName());
        DateFormat dateFormater = DateFormat.getDateTimeInstance(
                DateFormat.FULL, DateFormat.FULL, clientLocale);
        //get timezone and timezone ID
        String tz = " ";
        String tzid = " ";

        StringBuffer sb = new StringBuffer();

        try {
            X509CertInfo info = (X509CertInfo) mX509Cert.get(
                    X509CertImpl.NAME + "." + X509CertImpl.INFO);
            String serial2 = mX509Cert.getSerialNumber().toString(16).toUpperCase();

            //get correct instance of key
            PublicKey pKey = mX509Cert.getPublicKey();
            X509Key key = null;

            if (pKey instanceof CertificateX509Key) {
                CertificateX509Key certKey = (CertificateX509Key) pKey;

                key = (X509Key) certKey.get(CertificateX509Key.KEY);
            }
            if (pKey instanceof X509Key) {
                key = (X509Key) pKey;
            }

            //take care of spki
            sb.append(pp.indent(4) + resource.getString(
                    PrettyPrintResources.TOKEN_CERTIFICATE) + "\n");
            sb.append(pp.indent(8) + resource.getString(
                    PrettyPrintResources.TOKEN_DATA) + "\n");
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_VERSION) + " v");
            sb.append((mX509Cert.getVersion() + 1) + "\n");
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_SERIAL) + "0x" + serial2 + "\n");
            //XXX I18N Algorithm Name ?
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_SIGALG) + mX509Cert.getSigAlgName() +
                    " - " + mX509Cert.getSigAlgOID() + "\n");
            //XXX I18N IssuerDN ?
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_ISSUER) +
                    mX509Cert.getIssuerDN().toString() + "\n");
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_VALIDITY) + "\n");
            String notBefore = dateFormater.format(mX509Cert.getNotBefore());
            String notAfter = dateFormater.format(mX509Cert.getNotAfter());

            //get timezone and timezone ID
            if (TimeZone.getDefault() != null) {
                tz = TimeZone.getDefault().getDisplayName(
                            TimeZone.getDefault().inDaylightTime(
                                    mX509Cert.getNotBefore()),
                            TimeZone.SHORT,
                            clientLocale);
                tzid = TimeZone.getDefault().getID();
            }
            // Specify notBefore
            if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
                // Do NOT append timezone ID
                sb.append(pp.indent(16)
                        + resource.getString(
                                PrettyPrintResources.TOKEN_NOT_BEFORE)
                        + notBefore
                        + "\n");
            } else {
                // Append timezone ID
                sb.append(pp.indent(16)
                        + resource.getString(
                                PrettyPrintResources.TOKEN_NOT_BEFORE)
                        + notBefore
                        + " " + tzid + "\n");
            }
            // re-get timezone (just in case it is different . . .)
            if (TimeZone.getDefault() != null) {
                tz = TimeZone.getDefault().getDisplayName(
                            TimeZone.getDefault().inDaylightTime(
                                    mX509Cert.getNotAfter()),
                            TimeZone.SHORT,
                            clientLocale);
            }
            // Specify notAfter
            if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
                // Do NOT append timezone ID
                sb.append(pp.indent(16)
                        + resource.getString(
                                PrettyPrintResources.TOKEN_NOT_AFTER)
                        + notAfter
                        + "\n");
            } else {
                // Append timezone ID
                sb.append(pp.indent(16)
                        + resource.getString(
                                PrettyPrintResources.TOKEN_NOT_AFTER)
                        + notAfter
                        + " " + tzid + "\n");
            }
            //XXX I18N SubjectDN ?
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_SUBJECT) +
                    mX509Cert.getSubjectDN().toString() + "\n");
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_SPKI) + "\n");

            PubKeyPrettyPrint pkpp = new PubKeyPrettyPrint(key);

            sb.append(pkpp.toString(clientLocale, 16, 16));

            //take care of extensions
            CertificateExtensions extensions = (CertificateExtensions)
                    info.get(X509CertInfo.EXTENSIONS);

            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_EXTENSIONS) + "\n");
            if (extensions != null)
                for (int i = 0; i < extensions.size(); i++) {
                    Extension ext = extensions.elementAt(i);
                    ExtPrettyPrint extpp = new ExtPrettyPrint(ext, 16);

                    sb.append(extpp.toString());
                }

            //take care of signature
            sb.append(pp.indent(8) + resource.getString(
                    PrettyPrintResources.TOKEN_SIGNATURE) + "\n");
            //XXX I18N Algorithm Name ?
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_ALGORITHM) +
                    mX509Cert.getSigAlgName() + " - " + mX509Cert.getSigAlgOID() + "\n");
            sb.append(pp.indent(12) + resource.getString(
                    PrettyPrintResources.TOKEN_SIGNATURE) + "\n");
            sb.append(pp.toHexString(mX509Cert.getSignature(), 16, 16));

            // fingerprints
            String[] hashes = new String[] { "MD2", "MD5", "SHA1", "SHA256", "SHA512" };
            StringBuffer certFingerprints = new StringBuffer();

            sb.append(pp.indent(8) + "FingerPrint\n");
            for (int i = 0; i < hashes.length; i++) {
                MessageDigest md = MessageDigest.getInstance(hashes[i]);

                md.update(mX509Cert.getEncoded());
                certFingerprints.append(pp.indent(12) + hashes[i] + ":\n" +
                        pp.toHexString(md.digest(), 16, 16));
            }

            sb.append(certFingerprints.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb.toString();
    }

}