1 /*
2  * @(#) $Id: ValidateCertPathCommand.java,v 1.2 2003/07/08 08:13:52 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10package org.jstk.cert;
11
12import java.util.Iterator;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.Vector;
16import java.security.cert.*;
17import java.security.PublicKey;
18import java.security.KeyStore;
19import java.io.FileInputStream;
20import java.io.BufferedInputStream;
21import org.jstk.cert.rep.FileBasedRepository;
22
23import org.jstk.*;
24
25public class ValidateCertPathCommand extends JSTKCommandAdapter {
26    private static HashMap defaults = new HashMap();
27    static {
28        defaults.put("cerfile", "my.cer");
29        defaults.put("truststore", "my.ts");
30        defaults.put("storetype", "JCEKS");
31        defaults.put("crlfile", "my.crl");
32    }
33
34    public String briefDescription(){
35        String briefDesc = "display contents of a Certificate or Certificate Chain";
36        return briefDesc;
37    }
38
39    public String optionsDescription(){
40        String optionsDesc =
41            "  -cerfile <cerfile>  : File having the certificate chain.[" +
42            defaults.get("cerfile") + "]\n" +
43            "  -truststore <file>  : keystore with trusted certificates.[" +
44            defaults.get("truststore") + "]\n" +
45            "  -storetype <type>   : keystore type (JKS or JCEKS).[" +
46            defaults.get("storetype") + "]\n" +
47            "  -repfile <repfile>  : repository file.\n" +
48            "  -crlfile <crlfile>  : CRL file.[" +
49            defaults.get("crlfile") + "]\n";
50        return optionsDesc;
51    }
52    public String[] useForms(){
53        String[] useForms = {
54            "[-cerfile <cerfile>]"
55        };
56        return useForms;
57    }
58    public String[] sampleUses(){
59        String[] sampleUses = {
60            "",
61            "-cerfile test.cer"
62        };
63        return sampleUses;
64    }
65
66
67    public Object execute(JSTKArgs args) throws JSTKException{
68        try {
69            args.setDefaults(defaults);
70            String cerfile = args.get("cerfile");
71            String trustStoreFile = args.get("truststore");
72            String storeType = args.get("storetype");
73            String crlfile = args.get("crlfile");
74            String repfile = args.get("repfile");
75
76            CertificateFactory cf = CertificateFactory.getInstance("X.509");
77
78            CertPath cp;
79            StringBuffer sb = new StringBuffer();
80            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(cerfile));
81            bis.mark(1024);
82            try {
83                try {
84                    cp = cf.generateCertPath(bis);
85                } catch (CertificateException ce){  // Try PKCS7 format.
86                    bis.reset();
87                    cp = cf.generateCertPath(bis, "PKCS7");
88                }
89                bis.close();
90            } catch (CertificateException ce){  // Not a certpath.
91                bis.reset();
92                Certificate cert = cf.generateCertificate(bis);
93                bis.close();
94                throw new JSTKException("Validation of Certificate not supported.");
95            }
96
97            CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
98
99            // Create the PKIX parameters.
00            FileInputStream fis = new FileInputStream(trustStoreFile);
01            KeyStore trustStore = KeyStore.getInstance(storeType);
02            trustStore.load(fis, null);
03            PKIXParameters pkixParams = new PKIXParameters(trustStore);
04            pkixParams.setRevocationEnabled(false);
05
06            // Check for CRL
07            if (crlfile != null && (new java.io.File(crlfile)).exists()){
08                BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(crlfile));
09                CRL crl = cf.generateCRL(bis1);
10                Vector params = new Vector();
11                params.add(crl);
12                CollectionCertStoreParameters csParams = new CollectionCertStoreParameters(params);
13                CertStore cs = CertStore.getInstance("Collection", csParams);
14                pkixParams.addCertStore(cs);
15                pkixParams.setRevocationEnabled(true);
16            }
17
18            // Check for Repositroy
19            if (repfile != null && (new java.io.File(repfile)).exists()){
20                FileBasedRepository fbr = new FileBasedRepository(repfile);
21                Collection params = fbr.getRepository();
22                CollectionCertStoreParameters csParams = new CollectionCertStoreParameters(params);
23                CertStore cs = CertStore.getInstance("Collection", csParams);
24                pkixParams.addCertStore(cs);
25                //pkixParams.setRevocationEnabled(true);
26            }
27
28            try {
29                PKIXCertPathValidatorResult result =
30                        (PKIXCertPathValidatorResult)cpv.validate(cp, pkixParams);
31                PolicyNode policyTree = result.getPolicyTree();
32                PublicKey subjectPublicKey = result.getPublicKey();
33                sb.append("Validation succeeded.");
34            } catch (CertPathValidatorException cpve){
35                sb.append("Validation failed. cert[" + cpve.getIndex() + "] :" + cpve.getMessage());
36            }
37
38            return new JSTKResult(null, true, sb.toString());
39        } catch (Exception exc){
40            throw new JSTKException("VerifyCertCommand execution failed", exc);
41        }
42    }
43
44    public static void main(String[] args) throws Exception {
45        JSTKOptions opts = new JSTKOptions();
46        opts.parse(args, 0);
47        ValidateCertPathCommand validateCPCmd = new ValidateCertPathCommand();
48        JSTKResult result = (JSTKResult)validateCPCmd.execute(opts);
49        System.out.println(result.getText());
50        System.exit(result.isSuccess()? 0 : 1);
51    }
52}