summaryrefslogtreecommitdiffstats
path: root/bcprov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java
blob: 8bb4c3aba3650d729ca8e2e72606118ca2bbef65 (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
package org.bouncycastle.jcajce.provider.asymmetric.x509;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.security.NoSuchProviderException;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.security.auth.x500.X500Principal;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.pkcs.ContentInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.SignedData;
import org.bouncycastle.jcajce.util.BCJcaJceHelper;
import org.bouncycastle.jcajce.util.JcaJceHelper;
import org.bouncycastle.util.io.pem.PemObject;
// BEGIN android-removed
// import org.bouncycastle.util.io.pem.PemWriter;
// END android-removed

/**
 * CertPath implementation for X.509 certificates.
 * <br />
 **/
public  class PKIXCertPath
    extends CertPath
{
    private final JcaJceHelper helper = new BCJcaJceHelper();

    static final List certPathEncodings;

    static
    {
        List encodings = new ArrayList();
        encodings.add("PkiPath");
        // BEGIN android-removed
        // encodings.add("PEM");
        // END android-removed
        encodings.add("PKCS7");
        certPathEncodings = Collections.unmodifiableList(encodings);
    }

    private List certificates;

    /**
     * @param certs
     */
    private List sortCerts(
        List certs)
    {
        if (certs.size() < 2)
        {
            return certs;
        }
        
        X500Principal issuer = ((X509Certificate)certs.get(0)).getIssuerX500Principal();
        boolean         okay = true;
        
        for (int i = 1; i != certs.size(); i++) 
        {
            X509Certificate cert = (X509Certificate)certs.get(i);
            
            if (issuer.equals(cert.getSubjectX500Principal()))
            {
                issuer = ((X509Certificate)certs.get(i)).getIssuerX500Principal();
            }
            else
            {
                okay = false;
                break;
            }
        }
        
        if (okay)
        {
            return certs;
        }
        
        // find end-entity cert
        List retList = new ArrayList(certs.size());
        List orig = new ArrayList(certs);

        for (int i = 0; i < certs.size(); i++)
        {
            X509Certificate cert = (X509Certificate)certs.get(i);
            boolean         found = false;
            
            X500Principal subject = cert.getSubjectX500Principal();
            
            for (int j = 0; j != certs.size(); j++)
            {
                X509Certificate c = (X509Certificate)certs.get(j);
                if (c.getIssuerX500Principal().equals(subject))
                {
                    found = true;
                    break;
                }
            }
            
            if (!found)
            {
                retList.add(cert);
                certs.remove(i);
            }
        }
        
        // can only have one end entity cert - something's wrong, give up.
        if (retList.size() > 1)
        {
            return orig;
        }

        for (int i = 0; i != retList.size(); i++)
        {
            issuer = ((X509Certificate)retList.get(i)).getIssuerX500Principal();
            
            for (int j = 0; j < certs.size(); j++)
            {
                X509Certificate c = (X509Certificate)certs.get(j);
                if (issuer.equals(c.getSubjectX500Principal()))
                {
                    retList.add(c);
                    certs.remove(j);
                    break;
                }
            }
        }
        
        // make sure all certificates are accounted for.
        if (certs.size() > 0)
        {
            return orig;
        }
        
        return retList;
    }

    PKIXCertPath(List certificates)
    {
        super("X.509");
        this.certificates = sortCerts(new ArrayList(certificates));
    }

    /**
     * Creates a CertPath of the specified type.
     * This constructor is protected because most users should use
     * a CertificateFactory to create CertPaths.
     **/
    PKIXCertPath(
        InputStream inStream,
        String encoding)
        throws CertificateException
    {
        super("X.509");
        try
        {
            if (encoding.equalsIgnoreCase("PkiPath"))
            {
                ASN1InputStream derInStream = new ASN1InputStream(inStream);
                ASN1Primitive derObject = derInStream.readObject();
                if (!(derObject instanceof ASN1Sequence))
                {
                    throw new CertificateException("input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath");
                }
                Enumeration e = ((ASN1Sequence)derObject).getObjects();
                certificates = new ArrayList();
                CertificateFactory certFactory = helper.createCertificateFactory("X.509");
                while (e.hasMoreElements())
                {
                    ASN1Encodable element = (ASN1Encodable)e.nextElement();
                    byte[] encoded = element.toASN1Primitive().getEncoded(ASN1Encoding.DER);
                    certificates.add(0, certFactory.generateCertificate(
                        new ByteArrayInputStream(encoded)));
                }
            }
            else if (encoding.equalsIgnoreCase("PKCS7") || encoding.equalsIgnoreCase("PEM"))
            {
                inStream = new BufferedInputStream(inStream);
                certificates = new ArrayList();
                CertificateFactory certFactory= helper.createCertificateFactory("X.509");
                Certificate cert;
                while ((cert = certFactory.generateCertificate(inStream)) != null)
                {
                    certificates.add(cert);
                }
            }
            else
            {
                throw new CertificateException("unsupported encoding: " + encoding);
            }
        }
        catch (IOException ex)
        {
            throw new CertificateException("IOException throw while decoding CertPath:\n" + ex.toString());
        }
        catch (NoSuchProviderException ex)
        {
            throw new CertificateException("BouncyCastle provider not found while trying to get a CertificateFactory:\n" + ex.toString());
        }

        this.certificates = sortCerts(certificates);
    }
    
    /**
     * Returns an iteration of the encodings supported by this
     * certification path, with the default encoding
     * first. Attempts to modify the returned Iterator via its
     * remove method result in an UnsupportedOperationException.
     *
     * @return an Iterator over the names of the supported encodings (as Strings)
     **/
    public Iterator getEncodings()
    {
        return certPathEncodings.iterator();
    }

    /**
     * Returns the encoded form of this certification path, using
     * the default encoding.
     *
     * @return the encoded bytes
     * @exception java.security.cert.CertificateEncodingException if an encoding error occurs
     **/
    public byte[] getEncoded()
        throws CertificateEncodingException
    {
        Iterator iter = getEncodings();
        if (iter.hasNext())
        {
            Object enc = iter.next();
            if (enc instanceof String)
            {
            return getEncoded((String)enc);
            }
        }
        return null;
    }

    /**
     * Returns the encoded form of this certification path, using
     * the specified encoding.
     *
     * @param encoding the name of the encoding to use
     * @return the encoded bytes
     * @exception java.security.cert.CertificateEncodingException if an encoding error
     * occurs or the encoding requested is not supported
     *
     **/
    public byte[] getEncoded(String encoding)
        throws CertificateEncodingException
    {
        if (encoding.equalsIgnoreCase("PkiPath"))
        {
            ASN1EncodableVector v = new ASN1EncodableVector();

            ListIterator iter = certificates.listIterator(certificates.size());
            while (iter.hasPrevious())
            {
                v.add(toASN1Object((X509Certificate)iter.previous()));
            }

            return toDEREncoded(new DERSequence(v));
        }
        else if (encoding.equalsIgnoreCase("PKCS7"))
        {
            ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null);

            ASN1EncodableVector v = new ASN1EncodableVector();
            for (int i = 0; i != certificates.size(); i++)
            {
                v.add(toASN1Object((X509Certificate)certificates.get(i)));
            }
            
            SignedData sd = new SignedData(
                                     new ASN1Integer(1),
                                     new DERSet(),
                                     encInfo, 
                                     new DERSet(v),
                                     null, 
                                     new DERSet());

            return toDEREncoded(new ContentInfo(
                    PKCSObjectIdentifiers.signedData, sd));
        }
        // BEGIN android-removed
        // else if (encoding.equalsIgnoreCase("PEM"))
        // {
        //     ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        //     PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut));
        //
        //     try
        //     {
        //         for (int i = 0; i != certificates.size(); i++)
        //         {
        //             pWrt.writeObject(new PemObject("CERTIFICATE", ((X509Certificate)certificates.get(i)).getEncoded()));
        //         }
        //
        //         pWrt.close();
        //     }
        //     catch (Exception e)
        //     {
        //         throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
        //     }
        //
        //     return bOut.toByteArray();
        // }
        // END android-removed
        else
        {
            throw new CertificateEncodingException("unsupported encoding: " + encoding);
        }
    }

    /**
     * Returns the list of certificates in this certification
     * path. The List returned must be immutable and thread-safe. 
     *
     * @return an immutable List of Certificates (may be empty, but not null)
     **/
    public List getCertificates()
    {
        return Collections.unmodifiableList(new ArrayList(certificates));
    }

    /**
     * Return a DERObject containing the encoded certificate.
     *
     * @param cert the X509Certificate object to be encoded
     *
     * @return the DERObject
     **/
    private ASN1Primitive toASN1Object(
        X509Certificate cert)
        throws CertificateEncodingException
    {
        try
        {
            return new ASN1InputStream(cert.getEncoded()).readObject();
        }
        catch (Exception e)
        {
            throw new CertificateEncodingException("Exception while encoding certificate: " + e.toString());
        }
    }
    
    private byte[] toDEREncoded(ASN1Encodable obj)
        throws CertificateEncodingException
    {
        try
        {
            return obj.toASN1Primitive().getEncoded(ASN1Encoding.DER);
        }
        catch (IOException e)
        {
            throw new CertificateEncodingException("Exception thrown: " + e);
        }
    }
}