1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18/**
19* @author Vladimir N. Molotkov
20* @version $Revision$
21*/
22
23package org.apache.harmony.security.tests.support.cert;
24
25import tests.support.resource.Support_Resources;
26
27import java.io.BufferedInputStream;
28import java.io.ByteArrayInputStream;
29import java.io.IOException;
30import java.math.BigInteger;
31import java.security.InvalidAlgorithmParameterException;
32import java.security.KeyStore;
33import java.security.NoSuchAlgorithmException;
34import java.security.cert.CertPath;
35import java.security.cert.CertPathBuilder;
36import java.security.cert.CertPathParameters;
37import java.security.cert.CertPathValidatorException;
38import java.security.cert.CertStore;
39import java.security.cert.Certificate;
40import java.security.cert.CertificateException;
41import java.security.cert.CertificateFactory;
42import java.security.cert.CollectionCertStoreParameters;
43import java.security.cert.PKIXBuilderParameters;
44import java.security.cert.PKIXCertPathChecker;
45import java.security.cert.PolicyNode;
46import java.security.cert.PolicyQualifierInfo;
47import java.security.cert.TrustAnchor;
48import java.security.cert.X509CertSelector;
49import java.security.cert.X509Certificate;
50import java.util.ArrayList;
51import java.util.Collection;
52import java.util.Collections;
53import java.util.HashSet;
54import java.util.Iterator;
55import java.util.List;
56import java.util.Set;
57
58/**
59 * java.security.cert test utilities
60 *
61 */
62public class TestUtils {
63    // Certificate type used during testing
64    private static final String certType = "X.509";
65    // Key store type used during testing
66    private static final String keyStoreType = "BKS";
67    // The file name prefix to load keystore from
68    private static final String keyStoreFileName = "test." + keyStoreType
69            + ".ks";
70    //
71    // The file name suffixes to load keystore from
72    //  *.ks1 - keystore containing untrusted certificates only
73    //  *.ks2 - keystore containing trusted certificates only
74    //  *.ks3 - keystore containing both trusted and untrusted certificates
75    //
76    public static final int UNTRUSTED = 1;
77    public static final int TRUSTED = 2;
78    public static final int TRUSTED_AND_UNTRUSTED = 3;
79    //
80    // Common passwords for all test keystores
81    //
82    private final static char[] storepass =
83        new char[] {'s','t','o','r','e','p','w','d'};
84
85    /**
86     * Creates <code>TrustAnchor</code> instance
87     * constructed using self signed test certificate
88     *
89     * @return <code>TrustAnchor</code> instance
90     */
91    public static TrustAnchor getTrustAnchor() {
92        CertificateFactory cf = null;
93        try {
94            cf = CertificateFactory.getInstance(certType);
95        } catch (CertificateException e) {
96            // requested cert type is not available in the
97            // default provider package or any of the other provider packages
98            // that were searched
99            throw new RuntimeException(e);
100        }
101        BufferedInputStream bis = null;
102        try {
103            bis = new BufferedInputStream(new ByteArrayInputStream(
104                    getEncodedX509Certificate()));
105            X509Certificate c1 = (X509Certificate)cf.generateCertificate(bis);
106
107            return new TrustAnchor(c1, null);
108        } catch (Exception e) {
109            // all failures are fatal
110            throw new RuntimeException(e);
111        } finally {
112            if (bis != null) {
113                try {
114                    bis.close() ;
115                } catch (IOException ign) {}
116            }
117        }
118    }
119
120    /**
121     * Creates <code>Set</code> of <code>TrustAnchor</code>s
122     * containing single element (self signed test certificate).
123     * @return Returns <code>Set</code> of <code>TrustAnchor</code>s
124     */
125    public static Set<TrustAnchor> getTrustAnchorSet() {
126        TrustAnchor ta = getTrustAnchor();
127        if (ta == null) {
128            return null;
129        }
130        HashSet<TrustAnchor> set = new HashSet<TrustAnchor>();
131        if (!set.add(ta)) {
132            throw new RuntimeException("Could not create trust anchor set");
133        }
134        return set;
135    }
136
137    /**
138     * Creates test <code>KeyStore</code> instance
139     *
140     * @param initialize
141     *  Do not initialize returned <code>KeyStore</code> if false
142     *
143     * @param testKeyStoreType
144     *  this parameter ignored if <code>initialize</code> is false;
145     *  The following types supported:<br>
146     *  1 - <code>KeyStore</code> with untrusted certificates only<br>
147     *  2 - <code>KeyStore</code> with trusted certificates only<br>
148     *  3 - <code>KeyStore</code> with both trusted and untrusted certificates
149     *
150     * @return Returns test <code>KeyStore</code> instance
151     */
152    public static KeyStore getKeyStore(boolean initialize,
153            int testKeyStoreType) {
154        BufferedInputStream bis = null;
155        try {
156            KeyStore ks = KeyStore.getInstance(keyStoreType);
157            if (initialize) {
158                String fileName = keyStoreFileName + testKeyStoreType;
159                ks.load(Support_Resources.getResourceStream(fileName),
160                        storepass);
161            }
162            return ks;
163        } catch (Exception e) {
164            throw new RuntimeException(e);
165        } finally {
166            if (initialize && bis != null) {
167                try {
168                    bis.close();
169                } catch (IOException ign) {}
170            }
171        }
172    }
173
174    /**
175     * Creates <code>List</code> of <code>CollectionCertStores</code>
176     *
177     * @return The list created
178     *
179     * @throws InvalidAlgorithmParameterException
180     * @throws NoSuchAlgorithmException
181     */
182    public static List<CertStore> getCollectionCertStoresList()
183        throws InvalidAlgorithmParameterException,
184               NoSuchAlgorithmException {
185        CertStore cs = CertStore.getInstance("Collection",
186                new CollectionCertStoreParameters());
187        ArrayList<CertStore> l = new ArrayList<CertStore>();
188        if (!l.add(cs)) {
189            throw new RuntimeException("Could not create cert stores list");
190        }
191        return l;
192    }
193
194    /**
195     * Creates stub implementation of the <code>PKIXCertPathChecker</code>
196     *
197     * @return Stub implementation of the <code>PKIXCertPathChecker</code>
198     */
199    public static PKIXCertPathChecker getTestCertPathChecker() {
200        // stub implementation for testing purposes only
201        return new PKIXCertPathChecker() {
202            private boolean forward = false;
203
204
205            @SuppressWarnings({"unused", "unchecked"})
206            public void check(Certificate arg0, Collection arg1)
207                    throws CertPathValidatorException {
208            }
209
210            public Set<String> getSupportedExtensions() {
211                return null;
212            }
213
214            @SuppressWarnings("unused")
215            public void init(boolean arg0) throws CertPathValidatorException {
216                forward = arg0;
217            }
218
219            public boolean isForwardCheckingSupported() {
220                // just to check this checker state
221                return forward;
222            }
223        };
224    }
225
226    /**
227     * Creates policy tree stub containing two <code>PolicyNode</code>s
228     * for testing purposes
229     *
230     * @return root <code>PolicyNode</code> of the policy tree
231     */
232    public static PolicyNode getPolicyTree() {
233        return new PolicyNode() {
234            final PolicyNode parent = this;
235            public int getDepth() {
236                // parent
237                return 0;
238            }
239
240            public boolean isCritical() {
241                return false;
242            }
243
244            public String getValidPolicy() {
245                return null;
246            }
247
248            public PolicyNode getParent() {
249                return null;
250            }
251
252            public Iterator<PolicyNode> getChildren() {
253                PolicyNode child = new PolicyNode() {
254                    public int getDepth() {
255                        // child
256                        return 1;
257                    }
258
259                    public boolean isCritical() {
260                        return false;
261                    }
262
263                    public String getValidPolicy() {
264                        return null;
265                    }
266
267                    public PolicyNode getParent() {
268                        return parent;
269                    }
270
271                    public Iterator<PolicyNode> getChildren() {
272                        return null;
273                    }
274
275                    public Set<String> getExpectedPolicies() {
276                        return null;
277                    }
278
279                    public Set<? extends PolicyQualifierInfo> getPolicyQualifiers() {
280                        return null;
281                    }
282                };
283                HashSet<PolicyNode> s = new HashSet<PolicyNode>();
284                s.add(child);
285                return s.iterator();
286            }
287
288            public Set<String> getExpectedPolicies() {
289                return null;
290            }
291
292            public Set<? extends PolicyQualifierInfo> getPolicyQualifiers() {
293                return null;
294            }
295        };
296    }
297    // X.509 encoded certificate
298    private static final String ENCODED_X509_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n"
299            + "MIIDHTCCAtsCBEFT72swCwYHKoZIzjgEAwUAMHQxCzAJBgNVBAYTAlJVMQwwCgYDVQQIEwNOU08x\n"
300            + "FDASBgNVBAcTC05vdm9zaWJpcnNrMQ4wDAYDVQQKEwVJbnRlbDEVMBMGA1UECxMMRFJMIFNlY3Vy\n"
301            + "aXR5MRowGAYDVQQDExFWbGFkaW1pciBNb2xvdGtvdjAeFw0wNDA5MjQwOTU2NTlaFw0wNjA1MTcw\n"
302            + "OTU2NTlaMHQxCzAJBgNVBAYTAlJVMQwwCgYDVQQIEwNOU08xFDASBgNVBAcTC05vdm9zaWJpcnNr\n"
303            + "MQ4wDAYDVQQKEwVJbnRlbDEVMBMGA1UECxMMRFJMIFNlY3VyaXR5MRowGAYDVQQDExFWbGFkaW1p\n"
304            + "ciBNb2xvdGtvdjCCAbgwggEsBgcqhkjOOAQBMIIBHwKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3Ujzv\n"
305            + "RADDHj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7\n"
306            + "qdf+t8Yb+DtX58aophUPBPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8V\n"
307            + "IwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9B4JnUVlXjrrU\n"
308            + "WU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCjrh4rs6Z1kW6jfwv6ITVi8ftiegEk\n"
309            + "O8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQBTDv+z0kqA4GFAAKBgQDiNmj9jgWu1ILYqYWcUhNN\n"
310            + "8CjjRitf80yWP/s/565wZz3anb2w72jum63mdShDko9eOOOd1hiVuiBnNhSL7D6JfIYBJvNXr1av\n"
311            + "Gw583BBv12OBgg0eAW/GRWBn2Ak2JjsoBc5x2c1HAEufakep7T6RoC+n3lqbKPKyHWVdfqQ9KTAL\n"
312            + "BgcqhkjOOAQDBQADLwAwLAIUaRS3C9dXcMbrOAhmidFBr7oMvH0CFEC3LUwfLJX5gY8P6uxpkPx3\n"
313            + "JDSM\n" + "-----END CERTIFICATE-----\n";
314
315    public static byte[] getEncodedX509Certificate() {
316        return ENCODED_X509_CERTIFICATE.getBytes();
317    }
318
319    /**
320     * Returns X.509 certificate encoding corresponding to version v1.
321     *
322     * Certificate encoding was created by hands according to X.509 Certificate
323     * ASN.1 notation. The certificate encoding has the following encoded
324     * field values:<br>
325     * - version: 1<br>
326     * - serialNumber: 5<br>
327     * - issuer: CN=Z<br>
328     * - notBefore: 13 Dec 1999 14:15:16<br>
329     * - notAfter: 01 Jan 2000 00:00:00<br>
330     * - subject: CN=Y<br>
331     *
332     * @return X.509 certificate encoding corresponding to version v1.
333     */
334    public static byte[] getX509Certificate_v1() {
335        return new byte[] {
336        // Certificate: SEQUENCE
337            0x30, 0x6B,
338
339            //
340            // TBSCertificate: SEQUENCE {
341            //
342            0x30, 0x5C,
343
344            // version: [0] EXPLICIT Version DEFAULT v1
345            (byte) 0xA0, 0x03, 0x02, 0x01, 0x00,
346
347            // serialNumber: CertificateSerialNumber
348            0x02, 0x01, 0x05,
349
350            // signature: AlgorithmIdentifier
351            0x30, 0x07, // SEQUENCE
352            0x06, 0x02, 0x03, 0x05,//OID
353            0x01, 0x01, 0x07, //ANY
354
355            //issuer: Name
356            0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
357            0x13, 0x01, 0x5A, // CN=Z
358
359            //validity: Validity
360            0x30, 0x1E, // SEQUENCE
361            // notBefore: UTCTime
362            0x17, 0x0D, 0x39, 0x39, 0x31, 0x32, 0x31, 0x33, 0x31, 0x34, 0x31,
363            0x35, 0x31, 0x36, 0x5A, // 13 Dec 1999 14:15:16
364            // notAfter:  UTCTime
365            0x17, 0x0D, 0x30, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30,
366            0x30, 0x30, 0x30, 0x5A, // 01 Jan 2000 00:00:00
367
368            //subject: Name
369            0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
370            0x13, 0x01, 0x59, // CN=Y
371            //SubjectPublicKeyInfo  ::=  SEQUENCE  {
372            //    algorithm            AlgorithmIdentifier,
373            //    subjectPublicKey     BIT STRING  }
374            0x30, 0x0D, // SEQUENCE
375            0x30, 0x07, // SEQUENCE
376            0x06, 0x02, 0x03, 0x05,//OID
377            0x01, 0x01, 0x07, //ANY
378            0x03, 0x02, 0x00, 0x01, // subjectPublicKey
379
380            // issuerUniqueID - missed
381            // subjectUniqueID - missed
382            // extensions - missed
383
384            // } end TBSCertificate
385
386            //
387            // signatureAlgorithm: AlgorithmIdentifier
388            //
389            0x30, 0x07, // SEQUENCE
390            0x06, 0x02, 0x03, 0x05,//OID
391            0x01, 0x01, 0x07, //ANY
392
393            //
394            // signature: BIT STRING
395            //
396            0x03, 0x02, 0x00, 0x01 };
397    }
398
399    /**
400     * Returns X.509 certificate encoding corresponding to version v3.
401     *
402     * Certificate encoding was created by hands according to X.509 Certificate
403     * ASN.1 notation. The certificate encoding has the following encoded
404     * field values:<br>
405     * - version: 3<br>
406     * - serialNumber: 5<br>
407     * - issuer: CN=Z<br>
408     * - notBefore: 13 Dec 1999 14:15:16<br>
409     * - notAfter: 01 Jan 2000 00:00:00<br>
410     * - subject: CN=Y<br>
411     * - extensions:
412     *       1) AuthorityKeyIdentifier(OID=2.5.29.35): no values in it(empty sequence)
413     *
414     * @return X.509 certificate encoding corresponding to version v3.
415     */
416    public static byte[] getX509Certificate_v3() {
417        return new byte[] {
418        // Certificate: SEQUENCE
419            0x30, 0x7D,
420
421            //
422            // TBSCertificate: SEQUENCE {
423            //
424            0x30, 0x6E,
425
426            // version: [0] EXPLICIT Version DEFAULT v1
427            (byte) 0xA0, 0x03, 0x02, 0x01, 0x02,
428
429            // serialNumber: CertificateSerialNumber
430            0x02, 0x01, 0x05,
431
432            // signature: AlgorithmIdentifier
433            0x30, 0x07, // SEQUENCE
434            0x06, 0x02, 0x03, 0x05,//OID
435            0x01, 0x01, 0x07, //ANY
436
437            //issuer: Name
438            0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
439            0x13, 0x01, 0x5A, // CN=Z
440
441            //validity: Validity
442            0x30, 0x1E, // SEQUENCE
443            // notBefore: UTCTime
444            0x17, 0x0D, 0x39, 0x39, 0x31, 0x32, 0x31, 0x33, 0x31, 0x34, 0x31,
445            0x35, 0x31, 0x36, 0x5A, // 13 Dec 1999 14:15:16
446            // notAfter:  UTCTime
447            0x17, 0x0D, 0x30, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30,
448            0x30, 0x30, 0x30, 0x5A, // 01 Jan 2000 00:00:00
449
450            //subject: Name
451            0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03,
452            0x13, 0x01, 0x59, // CN=Y
453            //SubjectPublicKeyInfo  ::=  SEQUENCE  {
454            //    algorithm            AlgorithmIdentifier,
455            //    subjectPublicKey     BIT STRING  }
456            0x30, 0x0D, // SEQUENCE
457            0x30, 0x07, // SEQUENCE
458            0x06, 0x02, 0x03, 0x05,//OID
459            0x01, 0x01, 0x07, //ANY
460            0x03, 0x02, 0x00, 0x01, // subjectPublicKey
461
462            // issuerUniqueID - missed
463            // subjectUniqueID - missed
464            // extensions : [3]  EXPLICIT Extensions OPTIONAL
465            (byte) 0xA3, 0x10,
466            // Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
467            0x30, 0x0E,
468            // Extension  ::=  SEQUENCE  {
469            // extnID      OBJECT IDENTIFIER,
470            // critical    BOOLEAN DEFAULT FALSE,
471            // extnValue   OCTET STRING  }
472
473            // 1) AuthorityKeyIdentifier extension (see HARMONY-3384)
474            0x30, 0x0C,
475            0x06, 0x03, 0x55, 0x1D, 0x23, // OID = 2.5.29.35
476            0x01, 0x01, 0x00, // critical = FALSE
477            0x04, 0x02, 0x30, 0x00, // extnValue: MUST be empty sequence
478            // missed: keyIdentifier
479            // missed: authorityCertIssuer
480            // missed" authorityCertSerialNumber
481
482            // } end TBSCertificate
483
484            //
485            // signatureAlgorithm: AlgorithmIdentifier
486            //
487            0x30, 0x07, // SEQUENCE
488            0x06, 0x02, 0x03, 0x05,//OID
489            0x01, 0x01, 0x07, //ANY
490
491            //
492            // signature: BIT STRING
493            //
494            0x03, 0x02, 0x00, 0x01 };
495    }
496
497    /**
498     * Returns X.509 CRL encoding corresponding to version v1.
499     *
500     * CRL encoding was created by hands according to X.509 CRL ASN.1
501     * notation. The CRL encoding has the following encoded field values:<br>
502     * - version: 1<br>
503     * - issuer: CN=Z<br>
504     * - thisUpdate: 01 Jan 2001 01:02:03<br>
505     *
506     * @return X.509 CRL encoding corresponding to version v1.
507     */
508    public static byte[] getX509CRL_v1() {
509        return new byte[] {
510                //CertificateList: SEQUENCE
511                0x30, 0x35,
512
513                // TBSCertList: SEQUENCE
514                0x30, 0x27,
515                // Version: INTEGER OPTIONAL
516                // 0x02, 0x01, 0x01, - missed here cause it is v1
517                // signature: AlgorithmIdentifier
518                0x30, 0x06, // SEQUENCE
519                0x06, 0x01, 0x01, // OID
520                0x01, 0x01, 0x11, // ANY
521                // issuer: Name
522                0x30, 0x0C, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04,
523                0x03, 0x13, 0x01, 0x5A, // CN=Z
524                // thisUpdate: ChoiceOfTime
525                // GeneralizedTime: 01 Jan 2001 01:02:03
526                0x18, 0x0F, 0x32, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x31,
527                0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x5A,
528
529                // nextUpdate - missed
530                // revokedCertificates - missed
531                // crlExtensions - missed
532
533                // signatureAlgorithm: AlgorithmIdentifier
534                0x30, 0x06, // SEQUENCE
535                0x06, 0x01, 0x01, //OID
536                0x01, 0x01, 0x11, //ANY
537                // signature: BIT STRING
538                0x03, 0x02, 0x00, 0x01 };
539    }
540    //--------------------------------------------------------------------------
541
542    // Second example
543    /**
544     * Certificate:
545     * <pre>
546     * $ openssl req -x509 -nodes -days 365 -subj '/C=AN/ST=Android/O=Android/OU=Android/CN=Android/emailAddress=android' -newkey rsa:1024 -keyout root.pem -out root.pem -text -days 36500
547     * Generating a 1024 bit RSA private key
548     * ..........................................++++++
549     * .................++++++
550     * writing new private key to 'root.pem'
551     * -----BEGIN RSA PRIVATE KEY-----
552     * MIICXwIBAAKBgQDKS+qP2kgqYBtwY4QoJ5p0yyEl35sBr2ZKtAWn6SL4vXgvaIrj
553     * K7vG93CvG239bXfacniGMEBitedBlcqjdPREEY0DQn3jLXyAOd3tnlKcutNH3RjA
554     * fPlnDWNGKLnDdSd9QZEc0G1MsMg/HrERPm1hMfZQG85zdtbYmi2CJ/jS5wIDAQAB
555     * AoGBAIZhvdSHjS7RHwkeonjGLh1tnnx5OI/7AzmWsrci8L9JpZ/gk3pq39dBIhLA
556     * ZuVVpatwJU4GmY65BYEUz0Kb+3JY0PXagypwQKuWs9wb9C0aRnDVy9DNXkbJ+D+L
557     * DNvyZAG5BNknZapxsFSenR5UO4BY08wIsdBtWD/B7YcMTuvxAkEA9zKP18pJCmku
558     * TUDTJkonF/fGvI4PvsBm6YFyINb130yGzKJKCcEn5j2Fm+wF+lGY7nmtUIgQekRm
559     * WkwbjG/v3wJBANGACjKFVIFvuXH6EoyWx90uYw9C8+m2jOtrRaAMfRyUanCvF2Li
560     * ZYOLThPcxv/QvvQAa7RKJjxsK69Ajm+b3fkCQQCR7xWgTVmlfcbJ8LU265v8uFhp
561     * RGzjLe8Td0oLPRxWQXVrJXwUGiYV9MgF7ubwim+AifDZlBo2NF9Ae6Hf3M19AkEA
562     * nJEGDe+a0gj/HHD5f9wHjgLmwTcWNmnZMu8+X3g14DACxCf2YE4183MebLWoevI0
563     * YwIVe+2WWb21gAnM6RghcQJBALq0RZcYkZoQA8qr9TPuuMzi+fF3Y+4m/pDDcCd5
564     * zXbsroEZPdWPfAXKT95juW9yKdVzeOZHO1uwRWmQ9ZlPMhY=
565     * -----END RSA PRIVATE KEY-----
566     * -----
567     * Certificate:
568     *     Data:
569     *         Version: 3 (0x2)
570     *         Serial Number:
571     *             8a:12:37:ed:2d:ad:02:6e
572     *         Signature Algorithm: sha1WithRSAEncryption
573     *         Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android
574     *         Validity
575     *             Not Before: Oct  4 02:20:28 2010 GMT
576     *             Not After : Sep 10 02:20:28 2110 GMT
577     *         Subject: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android
578     *         Subject Public Key Info:
579     *             Public Key Algorithm: rsaEncryption
580     *             RSA Public Key: (1024 bit)
581     *                 Modulus (1024 bit):
582     *                     00:ca:4b:ea:8f:da:48:2a:60:1b:70:63:84:28:27:
583     *                     9a:74:cb:21:25:df:9b:01:af:66:4a:b4:05:a7:e9:
584     *                     22:f8:bd:78:2f:68:8a:e3:2b:bb:c6:f7:70:af:1b:
585     *                     6d:fd:6d:77:da:72:78:86:30:40:62:b5:e7:41:95:
586     *                     ca:a3:74:f4:44:11:8d:03:42:7d:e3:2d:7c:80:39:
587     *                     dd:ed:9e:52:9c:ba:d3:47:dd:18:c0:7c:f9:67:0d:
588     *                     63:46:28:b9:c3:75:27:7d:41:91:1c:d0:6d:4c:b0:
589     *                     c8:3f:1e:b1:11:3e:6d:61:31:f6:50:1b:ce:73:76:
590     *                     d6:d8:9a:2d:82:27:f8:d2:e7
591     *                 Exponent: 65537 (0x10001)
592     *         X509v3 extensions:
593     *             X509v3 Subject Key Identifier:
594     *                 14:7D:36:ED:63:44:BF:4F:DB:7D:28:96:78:6A:E7:EC:CE:2C:40:BF
595     *             X509v3 Authority Key Identifier:
596     *                 keyid:14:7D:36:ED:63:44:BF:4F:DB:7D:28:96:78:6A:E7:EC:CE:2C:40:BF
597     *                 DirName:/C=AN/ST=Android/O=Android/OU=Android/CN=Android/emailAddress=android
598     *                 serial:8A:12:37:ED:2D:AD:02:6E
599     *
600     *             X509v3 Basic Constraints:
601     *                 CA:TRUE
602     *     Signature Algorithm: sha1WithRSAEncryption
603     *         7c:f2:84:c0:ee:40:a5:b9:94:85:19:ab:36:02:1d:17:4b:98:
604     *         f9:b9:c8:c5:1a:b0:c1:4f:0f:1d:1c:e8:c4:cf:c7:87:52:19:
605     *         9e:64:55:35:bb:34:e1:38:2f:27:08:c5:ca:e7:97:02:90:fd:
606     *         27:cd:8e:5a:08:40:f5:34:ff:70:65:c4:d6:1f:70:4f:d6:2c:
607     *         cb:28:d8:ed:91:b7:eb:35:06:cd:0e:02:a8:51:cd:b7:3e:f9:
608     *         85:16:97:31:7b:42:4c:cb:6f:de:4b:dd:ae:5e:9d:ef:84:83:
609     *         89:f9:0f:a6:5f:e4:93:cc:30:b5:e9:1d:f4:08:f4:e6:e9:58:
610     *         4b:ba
611     * -----BEGIN CERTIFICATE-----
612     * MIIDLTCCApagAwIBAgIJAIoSN+0trQJuMA0GCSqGSIb3DQEBBQUAMG0xCzAJBgNV
613     * BAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAwDgYD
614     * VQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMRYwFAYJKoZIhvcNAQkBFgdh
615     * bmRyb2lkMCAXDTEwMTAwNDAyMjAyOFoYDzIxMTAwOTEwMDIyMDI4WjBtMQswCQYD
616     * VQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4G
617     * A1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEWMBQGCSqGSIb3DQEJARYH
618     * YW5kcm9pZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAykvqj9pIKmAbcGOE
619     * KCeadMshJd+bAa9mSrQFp+ki+L14L2iK4yu7xvdwrxtt/W132nJ4hjBAYrXnQZXK
620     * o3T0RBGNA0J94y18gDnd7Z5SnLrTR90YwHz5Zw1jRii5w3UnfUGRHNBtTLDIPx6x
621     * ET5tYTH2UBvOc3bW2Jotgif40ucCAwEAAaOB0jCBzzAdBgNVHQ4EFgQUFH027WNE
622     * v0/bfSiWeGrn7M4sQL8wgZ8GA1UdIwSBlzCBlIAUFH027WNEv0/bfSiWeGrn7M4s
623     * QL+hcaRvMG0xCzAJBgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQK
624     * EwdBbmRyb2lkMRAwDgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMRYw
625     * FAYJKoZIhvcNAQkBFgdhbmRyb2lkggkAihI37S2tAm4wDAYDVR0TBAUwAwEB/zAN
626     * BgkqhkiG9w0BAQUFAAOBgQB88oTA7kCluZSFGas2Ah0XS5j5ucjFGrDBTw8dHOjE
627     * z8eHUhmeZFU1uzThOC8nCMXK55cCkP0nzY5aCED1NP9wZcTWH3BP1izLKNjtkbfr
628     * NQbNDgKoUc23PvmFFpcxe0JMy2/eS92uXp3vhIOJ+Q+mX+STzDC16R30CPTm6VhL
629     * ug==
630     * -----END CERTIFICATE-----
631     * $
632     * </pre>
633     */
634    public static final String rootCert = ""
635            + "-----BEGIN CERTIFICATE-----\n"
636            + "MIIDLTCCApagAwIBAgIJAIoSN+0trQJuMA0GCSqGSIb3DQEBBQUAMG0xCzAJBgNV\n"
637            + "BAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAwDgYD\n"
638            + "VQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMRYwFAYJKoZIhvcNAQkBFgdh\n"
639            + "bmRyb2lkMCAXDTEwMTAwNDAyMjAyOFoYDzIxMTAwOTEwMDIyMDI4WjBtMQswCQYD\n"
640            + "VQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4G\n"
641            + "A1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEWMBQGCSqGSIb3DQEJARYH\n"
642            + "YW5kcm9pZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAykvqj9pIKmAbcGOE\n"
643            + "KCeadMshJd+bAa9mSrQFp+ki+L14L2iK4yu7xvdwrxtt/W132nJ4hjBAYrXnQZXK\n"
644            + "o3T0RBGNA0J94y18gDnd7Z5SnLrTR90YwHz5Zw1jRii5w3UnfUGRHNBtTLDIPx6x\n"
645            + "ET5tYTH2UBvOc3bW2Jotgif40ucCAwEAAaOB0jCBzzAdBgNVHQ4EFgQUFH027WNE\n"
646            + "v0/bfSiWeGrn7M4sQL8wgZ8GA1UdIwSBlzCBlIAUFH027WNEv0/bfSiWeGrn7M4s\n"
647            + "QL+hcaRvMG0xCzAJBgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQK\n"
648            + "EwdBbmRyb2lkMRAwDgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMRYw\n"
649            + "FAYJKoZIhvcNAQkBFgdhbmRyb2lkggkAihI37S2tAm4wDAYDVR0TBAUwAwEB/zAN\n"
650            + "BgkqhkiG9w0BAQUFAAOBgQB88oTA7kCluZSFGas2Ah0XS5j5ucjFGrDBTw8dHOjE\n"
651            + "z8eHUhmeZFU1uzThOC8nCMXK55cCkP0nzY5aCED1NP9wZcTWH3BP1izLKNjtkbfr\n"
652            + "NQbNDgKoUc23PvmFFpcxe0JMy2/eS92uXp3vhIOJ+Q+mX+STzDC16R30CPTm6VhL\n"
653            + "ug==\n"
654            + "-----END CERTIFICATE-----\n";
655
656    /**
657     * Certificate:
658     * <pre>
659     * $ openssl req -nodes -days 365 -subj '/C=AN/ST=Android/L=Android/O=Android/OU=Android/CN=Android Certificate/emailAddress=android' -newkey rsa:1024 -keyout certreq.pem -out certreq.pem -text -days 36500
660     * Generating a 1024 bit RSA private key
661     * .......++++++
662     * ......................++++++
663     * writing new private key to 'certreq.pem'
664     * -----
665     * $ openssl x509 -req -in certreq.pem -CA root.pem -CAcreateserial -out cert.pem -days 36500
666     * Signature ok
667     * subject=/C=AN/ST=Android/L=Android/O=Android/OU=Android/CN=Android Certificate/emailAddress=android
668     * Getting Private key
669     * $ rm root.srl
670     * $ openssl rsa -in certreq.pem
671     * writing RSA key
672     * -----BEGIN RSA PRIVATE KEY-----
673     * MIICXQIBAAKBgQDGvQZRB7fsuLvnZ0Sx43sTCkvwv/SEYrzRumyV16OC+lvKGC2X
674     * lYW9qv7of88hqSVq5823MB+uEP1xZLWaiKkYyEn72RwgV/HqB8KEgGYXEbMKKzUv
675     * j0D1X8kZ/EDGqsZjFKlk/7sZYcg3UqCcGUiEEszTadhyJ6FcowHM1EhrcQIDAQAB
676     * AoGAS4CQn8Qw6ewc5wLipDpqDYfB5grnGExys7MBgcPUyPPYX2TkHUye7LnD8gxs
677     * YrtiDcVW8BuGTZkC0EuUesskgiwGLimNiU3vU3LwH7OvtfUTMdvhv9nd2GFlfiQo
678     * PfwhITZ85GwhDkhiBBXjToDcNc0ntXVgACNAKU1ZlJyoyukCQQDwsGmD0GwKFtJH
679     * cGXI+IK0aB+pXjujZJU/Ikg+eTPMSWDsKD6ReZu9uJJc8W36Xiki/No1/NZvj0gB
680     * MwgIkwh7AkEA02FzaGcWLFSHaRfV1wpx1F3Iuu3X2wWqTzBlhGG9ZDQyy7gWZqHJ
681     * jElCdajiMnbh0mk62hobYy4FcLuvkkJWAwJBAK7FKpkQaqMY1zAQqZg4+4/MW9E8
682     * H8oRa14gopzanYYlcj+JKYWw7CnjMERU+yrl3LEPMdQp9/uh6wMT7y1qtqkCQCNG
683     * mxTsRzYEsUhnkuc9Nfvj3tDbSm+hxWdLw1VRXmLvlx6KTSq5i0IfI7kxAva7Ajq0
684     * Fv845iMqFfxXRhiZe3MCQQCxD0vLzEBegLQPgiavGXfBnRPrRrXgkuAJg7Fq/1Vt
685     * 3InSGat3Tv8GW+pCWWVgmV8iQ4wWReg+Bd03SCSP5uAY
686     * -----END RSA PRIVATE KEY-----
687     * $ openssl x509 -in cert.pem -text
688     * Certificate:
689     *     Data:
690     *         Version: 1 (0x0)
691     *         Serial Number:
692     *             89:34:5f:d5:01:2e:a2:2b
693     *         Signature Algorithm: sha1WithRSAEncryption
694     *         Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android
695     *         Validity
696     *             Not Before: Oct  4 04:41:54 2010 GMT
697     *             Not After : Sep 10 04:41:54 2110 GMT
698     *         Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android Certificate/emailAddress=android
699     *         Subject Public Key Info:
700     *             Public Key Algorithm: rsaEncryption
701     *             RSA Public Key: (1024 bit)
702     *                 Modulus (1024 bit):
703     *                     00:c6:bd:06:51:07:b7:ec:b8:bb:e7:67:44:b1:e3:
704     *                     7b:13:0a:4b:f0:bf:f4:84:62:bc:d1:ba:6c:95:d7:
705     *                     a3:82:fa:5b:ca:18:2d:97:95:85:bd:aa:fe:e8:7f:
706     *                     cf:21:a9:25:6a:e7:cd:b7:30:1f:ae:10:fd:71:64:
707     *                     b5:9a:88:a9:18:c8:49:fb:d9:1c:20:57:f1:ea:07:
708     *                     c2:84:80:66:17:11:b3:0a:2b:35:2f:8f:40:f5:5f:
709     *                     c9:19:fc:40:c6:aa:c6:63:14:a9:64:ff:bb:19:61:
710     *                     c8:37:52:a0:9c:19:48:84:12:cc:d3:69:d8:72:27:
711     *                     a1:5c:a3:01:cc:d4:48:6b:71
712     *                 Exponent: 65537 (0x10001)
713     *     Signature Algorithm: sha1WithRSAEncryption
714     *         80:06:54:ba:4c:a2:0d:2e:6b:d5:b0:b1:89:b2:fa:c2:fd:d6:
715     *         02:ab:74:af:fb:1c:bc:47:43:58:89:57:80:ad:59:79:e9:2e:
716     *         d9:60:a7:a6:0f:9c:10:9f:e1:80:a1:66:19:59:7e:11:28:17:
717     *         17:0a:1d:e9:8d:78:e8:c2:61:36:03:fc:42:b1:54:bd:28:39:
718     *         3c:48:fd:3c:79:e7:ca:1a:16:c3:8a:77:42:07:96:14:8c:d2:
719     *         51:ca:8e:db:b8:82:31:84:5e:3f:68:b1:a5:f0:96:ae:a9:ca:
720     *         86:f3:01:76:63:98:65:dd:41:81:11:d7:71:c8:ae:17:c7:20:
721     *         e7:22
722     * -----BEGIN CERTIFICATE-----
723     * MIICcjCCAdsCCQCJNF/VAS6iKzANBgkqhkiG9w0BAQUFADBtMQswCQYDVQQGEwJB
724     * TjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMH
725     * QW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEWMBQGCSqGSIb3DQEJARYHYW5kcm9p
726     * ZDAgFw0xMDEwMDQwNDQxNTRaGA8yMTEwMDkxMDA0NDE1NFowgYsxCzAJBgNVBAYT
727     * AkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQHEwdBbmRyb2lkMRAwDgYDVQQK
728     * EwdBbmRyb2lkMRAwDgYDVQQLEwdBbmRyb2lkMRwwGgYDVQQDExNBbmRyb2lkIENl
729     * cnRpZmljYXRlMRYwFAYJKoZIhvcNAQkBFgdhbmRyb2lkMIGfMA0GCSqGSIb3DQEB
730     * AQUAA4GNADCBiQKBgQDGvQZRB7fsuLvnZ0Sx43sTCkvwv/SEYrzRumyV16OC+lvK
731     * GC2XlYW9qv7of88hqSVq5823MB+uEP1xZLWaiKkYyEn72RwgV/HqB8KEgGYXEbMK
732     * KzUvj0D1X8kZ/EDGqsZjFKlk/7sZYcg3UqCcGUiEEszTadhyJ6FcowHM1EhrcQID
733     * AQABMA0GCSqGSIb3DQEBBQUAA4GBAIAGVLpMog0ua9WwsYmy+sL91gKrdK/7HLxH
734     * Q1iJV4CtWXnpLtlgp6YPnBCf4YChZhlZfhEoFxcKHemNeOjCYTYD/EKxVL0oOTxI
735     * /Tx558oaFsOKd0IHlhSM0lHKjtu4gjGEXj9osaXwlq6pyobzAXZjmGXdQYER13HI
736     * rhfHIOci
737     * -----END CERTIFICATE-----
738     * $
739     * </pre>
740     */
741    public static final String  endCert = ""
742            + "-----BEGIN CERTIFICATE-----\n"
743            + "MIICcjCCAdsCCQCJNF/VAS6iKzANBgkqhkiG9w0BAQUFADBtMQswCQYDVQQGEwJB\n"
744            + "TjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMH\n"
745            + "QW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEWMBQGCSqGSIb3DQEJARYHYW5kcm9p\n"
746            + "ZDAgFw0xMDEwMDQwNDQxNTRaGA8yMTEwMDkxMDA0NDE1NFowgYsxCzAJBgNVBAYT\n"
747            + "AkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQHEwdBbmRyb2lkMRAwDgYDVQQK\n"
748            + "EwdBbmRyb2lkMRAwDgYDVQQLEwdBbmRyb2lkMRwwGgYDVQQDExNBbmRyb2lkIENl\n"
749            + "cnRpZmljYXRlMRYwFAYJKoZIhvcNAQkBFgdhbmRyb2lkMIGfMA0GCSqGSIb3DQEB\n"
750            + "AQUAA4GNADCBiQKBgQDGvQZRB7fsuLvnZ0Sx43sTCkvwv/SEYrzRumyV16OC+lvK\n"
751            + "GC2XlYW9qv7of88hqSVq5823MB+uEP1xZLWaiKkYyEn72RwgV/HqB8KEgGYXEbMK\n"
752            + "KzUvj0D1X8kZ/EDGqsZjFKlk/7sZYcg3UqCcGUiEEszTadhyJ6FcowHM1EhrcQID\n"
753            + "AQABMA0GCSqGSIb3DQEBBQUAA4GBAIAGVLpMog0ua9WwsYmy+sL91gKrdK/7HLxH\n"
754            + "Q1iJV4CtWXnpLtlgp6YPnBCf4YChZhlZfhEoFxcKHemNeOjCYTYD/EKxVL0oOTxI\n"
755            + "/Tx558oaFsOKd0IHlhSM0lHKjtu4gjGEXj9osaXwlq6pyobzAXZjmGXdQYER13HI\n"
756            + "rhfHIOci\n"
757            + "-----END CERTIFICATE-----\n";
758
759    /**
760     * a self signed certificate
761     */
762    public static X509Certificate rootCertificateSS;
763
764    public static X509Certificate endCertificate;
765
766    public static MyCRL crl;
767
768    public static X509CertSelector theCertSelector;
769
770    public static CertPathBuilder builder;
771    private static CertStore store;
772
773    public static void initCertPathSSCertChain() throws CertificateException,
774            InvalidAlgorithmParameterException, NoSuchAlgorithmException,
775            IOException {
776        // create certificates and CRLs
777        CertificateFactory cf = CertificateFactory.getInstance("X.509");
778        ByteArrayInputStream bi = new ByteArrayInputStream(rootCert.getBytes());
779        rootCertificateSS = (X509Certificate) cf.generateCertificate(bi);
780        bi = new ByteArrayInputStream(endCert.getBytes());
781        endCertificate = (X509Certificate) cf.generateCertificate(bi);
782        BigInteger revokedSerialNumber = BigInteger.valueOf(1);
783        crl = new MyCRL("X.509");
784//        X509CRL rootCRL = X509CRL;
785//        X509CRL interCRL = X509CRLExample.createCRL(interCert, interPair
786//                .getPrivate(), revokedSerialNumber);
787
788        // create CertStore to support path building
789        List<Object> list = new ArrayList<Object>();
790
791        list.add(rootCertificateSS);
792        list.add(endCertificate);
793
794        CollectionCertStoreParameters params = new CollectionCertStoreParameters(
795                list);
796        store = CertStore.getInstance("Collection", params);
797
798        theCertSelector = new X509CertSelector();
799        theCertSelector.setCertificate(endCertificate);
800        theCertSelector.setIssuer(endCertificate.getIssuerX500Principal()
801                .getEncoded());
802
803        // build the path
804        builder = CertPathBuilder.getInstance("PKIX");
805
806    }
807
808    public static CertPathBuilder getCertPathBuilder() {
809        if (builder == null) {
810            throw new RuntimeException(
811            "Call initCertPathSSCertChain prior to initCertPathSSCertChain");
812        }
813        return builder;
814    }
815
816    public static CertPath buildCertPathSSCertChain() throws Exception {
817        return builder.build(getCertPathParameters()).getCertPath();
818    }
819
820    public static CertPathParameters getCertPathParameters()
821            throws InvalidAlgorithmParameterException {
822        if ((rootCertificateSS == null) || (theCertSelector == null)
823                || (builder == null)) {
824            throw new RuntimeException(
825                    "Call initCertPathSSCertChain prior to buildCertPath");
826        }
827        PKIXBuilderParameters buildParams = new PKIXBuilderParameters(
828                Collections.singleton(new TrustAnchor(rootCertificateSS, null)),
829                theCertSelector);
830
831        buildParams.addCertStore(store);
832        buildParams.setRevocationEnabled(false);
833
834        return buildParams;
835
836    }
837}
838