Source Code Cross Referenced for X509CertImplTest.java in  » Apache-Harmony-Java-SE » org-package » org » apache » harmony » security » tests » provider » cert » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Apache Harmony Java SE » org package » org.apache.harmony.security.tests.provider.cert 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         *  Licensed to the Apache Software Foundation (ASF) under one or more
003:         *  contributor license agreements.  See the NOTICE file distributed with
004:         *  this work for additional information regarding copyright ownership.
005:         *  The ASF licenses this file to You under the Apache License, Version 2.0
006:         *  (the "License"); you may not use this file except in compliance with
007:         *  the License.  You may obtain a copy of the License at
008:         *
009:         *     http://www.apache.org/licenses/LICENSE-2.0
010:         *
011:         *  Unless required by applicable law or agreed to in writing, software
012:         *  distributed under the License is distributed on an "AS IS" BASIS,
013:         *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014:         *  See the License for the specific language governing permissions and
015:         *  limitations under the License.
016:         */
017:        /**
018:         * @author Alexander Y. Kleymenov
019:         * @version $Revision$
020:         */package org.apache.harmony.security.tests.provider.cert;
021:
022:        import java.io.ByteArrayInputStream;
023:        import java.io.IOException;
024:        import java.math.BigInteger;
025:        import java.security.KeyPair;
026:        import java.security.KeyPairGenerator;
027:        import java.security.PrivateKey;
028:        import java.security.PublicKey;
029:        import java.security.Signature;
030:        import java.security.cert.CertificateEncodingException;
031:        import java.security.cert.CertificateExpiredException;
032:        import java.security.cert.CertificateNotYetValidException;
033:        import java.security.cert.CertificateParsingException;
034:        import java.security.cert.X509Certificate;
035:        import java.util.Arrays;
036:        import java.util.Collection;
037:        import java.util.Date;
038:        import java.util.Iterator;
039:        import java.util.List;
040:        import java.util.Set;
041:
042:        import javax.security.auth.x500.X500Principal;
043:
044:        import junit.framework.Test;
045:        import junit.framework.TestCase;
046:        import junit.framework.TestSuite;
047:
048:        import org.apache.harmony.security.asn1.ObjectIdentifier;
049:        import org.apache.harmony.security.provider.cert.X509CertImpl;
050:        import org.apache.harmony.security.tests.support.cert.TestUtils;
051:        import org.apache.harmony.security.x501.Name;
052:        import org.apache.harmony.security.x509.AlgorithmIdentifier;
053:        import org.apache.harmony.security.x509.AlternativeName;
054:        import org.apache.harmony.security.x509.AuthorityKeyIdentifier;
055:        import org.apache.harmony.security.x509.BasicConstraints;
056:        import org.apache.harmony.security.x509.CRLDistributionPoints;
057:        import org.apache.harmony.security.x509.Certificate;
058:        import org.apache.harmony.security.x509.CertificatePolicies;
059:        import org.apache.harmony.security.x509.DistributionPoint;
060:        import org.apache.harmony.security.x509.DistributionPointName;
061:        import org.apache.harmony.security.x509.ExtendedKeyUsage;
062:        import org.apache.harmony.security.x509.Extension;
063:        import org.apache.harmony.security.x509.Extensions;
064:        import org.apache.harmony.security.x509.GeneralName;
065:        import org.apache.harmony.security.x509.GeneralNames;
066:        import org.apache.harmony.security.x509.GeneralSubtree;
067:        import org.apache.harmony.security.x509.GeneralSubtrees;
068:        import org.apache.harmony.security.x509.InhibitAnyPolicy;
069:        import org.apache.harmony.security.x509.KeyUsage;
070:        import org.apache.harmony.security.x509.NameConstraints;
071:        import org.apache.harmony.security.x509.PolicyConstraints;
072:        import org.apache.harmony.security.x509.PolicyInformation;
073:        import org.apache.harmony.security.x509.ReasonFlags;
074:        import org.apache.harmony.security.x509.SubjectKeyIdentifier;
075:        import org.apache.harmony.security.x509.SubjectPublicKeyInfo;
076:        import org.apache.harmony.security.x509.TBSCertificate;
077:        import org.apache.harmony.security.x509.Validity;
078:
079:        /**
080:         * X509CertImplTest
081:         */
082:        public class X509CertImplTest extends TestCase {
083:
084:            //
085:            // The values of certificate's fields:
086:            //
087:
088:            int version = 2; //v3
089:            BigInteger serialNumber = BigInteger.valueOf(555L);
090:
091:            // Algorithm name and its OID (http://oid.elibel.tm.fr)
092:            String algOID = "1.2.840.10040.4.3";
093:            String algName = "SHA1withDSA";
094:
095:            // DER boolean false encoding (http://asn1.elibel.tm.fr)
096:            // Makes no sense. For testing purposes we need just provide 
097:            // some ASN.1 structure:
098:            byte[] algParams = { 1, 1, 0 };
099:            String issuerName = "O=Certificate Issuer";
100:            long notBefore = 1000000000L;
101:            long notAfter = 2000000000L;
102:            String subjectName = "O=Subject Organization";
103:
104:            // keys are using to make signature and to verify it
105:            static PublicKey publicKey;
106:            static PrivateKey privateKey;
107:            byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; // random value
108:            byte[] keyEncoding = null;
109:            boolean[] issuerUniqueID = new boolean[] { true, false, true,
110:                    false, true, false, true, false }; // random value
111:            boolean[] subjectUniqueID = new boolean[] { false, true, false,
112:                    true, false, true, false, true }; // random value
113:
114:            // Extensions' values
115:            byte[] extValEncoding = new byte[] { 1, 1, 1 }; // random value
116:            boolean[] extnKeyUsage = new boolean[] { true, false, true, false,
117:                    true, false, true, false, true }; // random value
118:            List extnExtendedKeyUsage = Arrays.asList(new int[][] {
119:
120:            // Extended key usage values as specified in rfc 3280
121:                    // (http://www.ietf.org/rfc/rfc3280.txt):
122:                    ObjectIdentifier.toIntArray("2.5.29.37.0"), // Any extended key usage
123:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.1"), // TLS Web server authentication
124:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.1"), // TLS Web server authentication
125:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.2"), // TLS Web client authentication
126:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.3"), // Code Signing
127:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.4"), // E-mail protection
128:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.5"), // IP security end system
129:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.6"), // IP security tunnel termination
130:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.7"), // IP security user
131:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.8"), // Timestamping
132:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.7.3.9"), // OCSP signing
133:                    ObjectIdentifier.toIntArray("1.3.6.1.5.5.8.2.2"), // iKEIntermediate
134:                    ObjectIdentifier.toIntArray("1.3.6.1.4.1.311.10.3.3"), // MS Server Gated Cryptography
135:                    ObjectIdentifier.toIntArray("2.16.840.1.113730.4.1"), // Netscape Server Gated Cryptography
136:            });
137:            static NameConstraints nameConstraints;
138:            int extnBCLen = 5;
139:            static GeneralNames extnSANames;
140:            static GeneralNames extnIANames;
141:
142:            static {
143:                try {
144:                    extnSANames = new GeneralNames(Arrays
145:                            .asList(new GeneralName[] {
146:                                    new GeneralName(1, "rfc@822.Name"),
147:                                    new GeneralName(2, "dNSName"),
148:                                    new GeneralName(4, "O=Organization"),
149:                                    new GeneralName(6,
150:                                            "http://uniform.Resource.Id"),
151:                                    new GeneralName(7, "255.255.255.0"),
152:                                    new GeneralName(8, "1.2.3.4444.55555") }));
153:                    GeneralSubtrees permittedNames = new GeneralSubtrees()
154:                            .addSubtree(
155:                                    new GeneralSubtree(new GeneralName(1,
156:                                            "rfc@822.Name"), 1, 2)).addSubtree(
157:                                    new GeneralSubtree(new GeneralName(2,
158:                                            "dNSName"))).addSubtree(
159:                                    new GeneralSubtree(new GeneralName(8,
160:                                            "1.2.3.4444.55555"), 2));
161:                    GeneralSubtrees excludedNames = new GeneralSubtrees()
162:                            .addSubtree(
163:                                    new GeneralSubtree(new GeneralName(1,
164:                                            "rfc@822.BadName"), 1, 2))
165:                            .addSubtree(
166:                                    new GeneralSubtree(new GeneralName(2,
167:                                            "BadDNSName"))).addSubtree(
168:                                    new GeneralSubtree(new GeneralName(8,
169:                                            "2.3.4.4444.222"), 2));
170:                    nameConstraints = new NameConstraints(permittedNames,
171:                            excludedNames);
172:                } catch (IOException e) {
173:                    // should not be thrown
174:                    e.printStackTrace();
175:                    extnSANames = new GeneralNames();
176:                    nameConstraints = new NameConstraints();
177:                }
178:                extnIANames = extnSANames;
179:
180:                try {
181:                    KeyPairGenerator keyGen = KeyPairGenerator
182:                            .getInstance("DSA");
183:                    keyGen.initialize(1024);
184:                    KeyPair keyPair = keyGen.genKeyPair();
185:                    publicKey = keyPair.getPublic();
186:                    privateKey = keyPair.getPrivate();
187:                } catch (Exception e) {
188:                    e.printStackTrace();
189:                }
190:            }
191:
192:            // Extensions
193:            Extension[] extensions = new Extension[] {
194:
195:            // Supported critical extensions (as specified in rfc 3280
196:                    // http://www.ietf.org/rfc/rfc3280.txt):
197:                    // Key Usage
198:                    new Extension("2.5.29.15", true, new KeyUsage(extnKeyUsage)),
199:                    // Basic Constraints    
200:                    new Extension("2.5.29.19", true, new BasicConstraints(true,
201:                            extnBCLen)),
202:                    // Certificate Policies with ANY policy
203:                    new Extension("2.5.29.32", true, new CertificatePolicies()
204:                            .addPolicyInformation(new PolicyInformation(
205:                                    "2.5.29.32.0"))),
206:                    // Subject Alternative Name
207:                    new Extension("2.5.29.17", true, new AlternativeName(
208:                            AlternativeName.SUBJECT, extnSANames)),
209:                    // Name Constraints
210:                    new Extension("2.5.29.30", true, nameConstraints),
211:                    // Policy Constraints
212:                    new Extension("2.5.29.36", true,
213:                            new PolicyConstraints(1, 2)),
214:                    // Extended Key Usage
215:                    new Extension("2.5.29.37", true, new ExtendedKeyUsage(
216:                            extnExtendedKeyUsage)),
217:                    // Inhibit Any-Policy
218:                    new Extension("2.5.29.54", true, new InhibitAnyPolicy(1)),
219:
220:                    // Unsupported critical extensions:
221:                    new Extension("1.2.77.777", true, extValEncoding),
222:
223:                    // Non-critical extensions (as specified in rfc 3280
224:                    // http://www.ietf.org/rfc/rfc3280.txt):
225:
226:                    // Issuer Alternative Name
227:                    new Extension("2.5.29.18", false, new AlternativeName(
228:                            AlternativeName.ISSUER, extnSANames)),
229:                    // CRL Distribution Points
230:                    new Extension(
231:                            "2.5.29.31",
232:                            false,
233:                            new CRLDistributionPoints(
234:                                    Arrays
235:                                            .asList(new DistributionPoint[] { new DistributionPoint(
236:                                                    new DistributionPointName(
237:                                                            extnSANames),
238:                                                    new ReasonFlags(
239:                                                            extnKeyUsage),
240:                                                    extnSANames), }))),
241:                    // Authority Key Identifier
242:                    new Extension("2.5.29.35", false,
243:                            new AuthorityKeyIdentifier(
244:                                    // random value for key identifier
245:                                    new byte[] { 1, 2, 3, 4, 5 }, extnSANames,
246:                                    serialNumber)),
247:                    // Subject Key Identifier
248:                    new Extension("2.5.29.14", false,
249:                    // random value for key identifier
250:                            new SubjectKeyIdentifier(
251:                                    new byte[] { 1, 2, 3, 4, 5 })),
252:                    // Policy Mappings
253:                    new Extension("2.5.29.33", false, extValEncoding), };
254:            List allCritical = Arrays.asList(new String[] { "2.5.29.15",
255:                    "2.5.29.19", "2.5.29.32", "2.5.29.17", "2.5.29.30",
256:                    "2.5.29.36", "2.5.29.37", "2.5.29.54", "1.2.77.777" });
257:            List allNonCritical = Arrays.asList(new String[] { "2.5.29.18",
258:                    "2.5.29.35", "2.5.29.14", "2.5.29.33", "2.5.29.31" });
259:
260:            public X509Certificate certificate;
261:            byte[] tbsCertEncoding;
262:            byte[] signatureValue;
263:            // to minimize efforts on signature generation the signature will be
264:            // stored in this field
265:            static byte[] signatureValueBytes;
266:            byte[] certEncoding;
267:
268:            /**
269:             * Creates the master certificate on the base of which 
270:             * all functionality will be tested.
271:             * @return
272:             * @throws java.lang.Exception 
273:             */
274:            protected void setUp() throws java.lang.Exception {
275:                AlgorithmIdentifier signature = new AlgorithmIdentifier(algOID,
276:                        algParams);
277:                Name issuer = new Name(issuerName);
278:                Name subject = new Name(subjectName);
279:                Validity validity = new Validity(new Date(notBefore), new Date(
280:                        notAfter));
281:
282:                SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) SubjectPublicKeyInfo.ASN1
283:                        .decode(publicKey.getEncoded());
284:                keyEncoding = subjectPublicKeyInfo.getEncoded();
285:
286:                Extensions exts = new Extensions(Arrays.asList(extensions));
287:
288:                TBSCertificate tbsCertificate = new TBSCertificate(version,
289:                        serialNumber, signature, issuer, validity, subject,
290:                        subjectPublicKeyInfo, issuerUniqueID, subjectUniqueID,
291:                        exts);
292:                tbsCertEncoding = tbsCertificate.getEncoded();
293:
294:                if (signatureValueBytes == null) {
295:                    try {
296:                        Signature sig = Signature.getInstance("DSA");//new byte[32];
297:                        sig.initSign(privateKey);
298:                        sig.update(tbsCertEncoding, 0, tbsCertEncoding.length);
299:                        signatureValueBytes = sig.sign();
300:                    } catch (Exception e) {
301:                        e.printStackTrace();
302:                        signatureValueBytes = new byte[10];
303:                    }
304:                }
305:                if ("testVerify3".equals(getName())) {
306:                    signatureValue = new byte[signatureValueBytes.length];
307:                    // make incorrect signature value:
308:                    System.arraycopy(signatureValueBytes, 0, signatureValue, 0,
309:                            signatureValueBytes.length);
310:                    signatureValue[20]++;
311:                } else {
312:                    signatureValue = signatureValueBytes;
313:                }
314:
315:                Certificate cert = new Certificate(tbsCertificate, signature,
316:                        signatureValue);
317:
318:                certEncoding = cert.getEncoded();
319:
320:                cert = (Certificate) Certificate.ASN1.decode(certEncoding);
321:                certificate = new X509CertImpl(cert);
322:            }
323:
324:            public void testCreation() throws Exception {
325:                ByteArrayInputStream bis = new ByteArrayInputStream(
326:                        certEncoding);
327:                certificate = new X509CertImpl(bis);
328:            }
329:
330:            /**
331:             * checkValidity() method testing.
332:             */
333:            public void testCheckValidity1() {
334:                try {
335:                    certificate.checkValidity();
336:                    fail("CertificateExpiredException should be thrown.");
337:                } catch (CertificateNotYetValidException e) {
338:                    fail("Unexpected CertificateNotYetValidException was thrown.");
339:                } catch (CertificateExpiredException e) {
340:                }
341:            }
342:
343:            /**
344:             * checkValidity(Date date) method testing.
345:             */
346:            public void testCheckValidity2() {
347:                try {
348:                    certificate.checkValidity(new Date(3000000000L));
349:                    fail("CertificateExpiredException should be thrown.");
350:                } catch (CertificateNotYetValidException e) {
351:                    fail("Unexpected CertificateNotYetValidException was thrown.");
352:                } catch (CertificateExpiredException e) {
353:                }
354:                try {
355:                    certificate.checkValidity(new Date(100000000L));
356:                    fail("CertificateNotYetValidException be thrown.");
357:                } catch (CertificateExpiredException e) {
358:                    fail("Unexpected CertificateExpiredException was thrown.");
359:                } catch (CertificateNotYetValidException e) {
360:                }
361:                try {
362:                    certificate.checkValidity(new Date(1000000000L));
363:                    certificate.checkValidity(new Date(1500000000L));
364:                    certificate.checkValidity(new Date(2000000000L));
365:                } catch (CertificateExpiredException e) {
366:                    fail("Unexpected CertificateExpiredException was thrown.");
367:                } catch (CertificateNotYetValidException e) {
368:                    fail("Unexpected CertificateNotYetValidException was thrown.");
369:                }
370:            }
371:
372:            /**
373:             * @tests java.security.cert.X509Certificate#getVersion()
374:             */
375:            public void testGetVersion() throws IOException {
376:
377:                byte[] x509CertEnc = TestUtils.getX509Certificate_v1();
378:
379:                // test initial version that is 1
380:                assertEquals("Version 1:", 1, new X509CertImpl(x509CertEnc)
381:                        .getVersion());
382:
383:                // as fas as we know offset of version byte in the cert. encoding
384:                // it is possible to change it to test other versions
385:
386:                // offset of version byte in certificate encoding
387:                int offset = 8;
388:
389:                // set version to 2
390:                x509CertEnc[offset] = 1;
391:                assertEquals("Version 2:", 2, new X509CertImpl(x509CertEnc)
392:                        .getVersion());
393:
394:                // set version to 3
395:                x509CertEnc[offset] = 2;
396:                assertEquals("Version 3:", 3, new X509CertImpl(x509CertEnc)
397:                        .getVersion());
398:            }
399:
400:            /**
401:             * getSerialNumber() method testing.
402:             */
403:            public void testGetSerialNumber() {
404:                assertEquals("Incorrect value of version", serialNumber,
405:                        certificate.getSerialNumber());
406:            }
407:
408:            /**
409:             * getIssuerDN() method testing.
410:             */
411:            public void testGetIssuerDN() {
412:                assertEquals("Incorrect issuer", new X500Principal(issuerName)
413:                        .getName(), certificate.getIssuerDN().getName());
414:            }
415:
416:            /**
417:             * getIssuerX500Principal() method testing.
418:             */
419:            public void testGetIssuerX500Principal() {
420:                assertEquals("Incorrect issuer", new X500Principal(issuerName),
421:                        certificate.getIssuerX500Principal());
422:            }
423:
424:            /**
425:             * getSubjectDN() method testing.
426:             */
427:            public void testGetSubjectDN() {
428:                assertEquals("Incorrect subject",
429:                        new X500Principal(subjectName).getName(), certificate
430:                                .getSubjectDN().getName());
431:            }
432:
433:            /**
434:             * getSubjectX500Principal() method testing.
435:             */
436:            public void testGetSubjectX500Principal() {
437:                assertEquals("Incorrect subject",
438:                        new X500Principal(subjectName), certificate
439:                                .getSubjectX500Principal());
440:            }
441:
442:            /**
443:             * getNotBefore() method testing.
444:             */
445:            public void testGetNotBefore() {
446:                assertEquals("Incorrect notBefore date", new Date(notBefore),
447:                        certificate.getNotBefore());
448:            }
449:
450:            /**
451:             * getNotAfter() method testing.
452:             */
453:            public void testGetNotAfter() {
454:                assertEquals("Incorrect notAfter date", new Date(notAfter),
455:                        certificate.getNotAfter());
456:            }
457:
458:            public static void printAsHex(int perLine, String prefix,
459:                    String delimiter, byte[] data) {
460:                for (int i = 0; i < data.length; i++) {
461:                    String tail = Integer.toHexString(0x000000ff & data[i]);
462:                    if (tail.length() == 1) {
463:                        tail = "0" + tail;
464:                    }
465:                    System.out.print(prefix + "0x" + tail + delimiter);
466:
467:                    if (((i + 1) % perLine) == 0) {
468:                        System.out.println();
469:                    }
470:                }
471:                System.out.println();
472:            }
473:
474:            /**
475:             * getTBSCertificate() method testing.
476:             */
477:            public void testGetTBSCertificate() {
478:                try {
479:                    if (!Arrays.equals(tbsCertEncoding, certificate
480:                            .getTBSCertificate())) {
481:                        System.out
482:                                .println("TBSCertificate encoding missmatch:");
483:                        System.out.println("Expected:");
484:                        printAsHex(20, "", " ", tbsCertEncoding);
485:                        System.out.println("Got:");
486:                        printAsHex(20, "", " ", certificate.getTBSCertificate());
487:                        fail("Incorrect encoding of TBSCertificate.");
488:                    }
489:                } catch (CertificateEncodingException e) {
490:                    fail("Unexpected CertificateEncodingException was thrown.");
491:                }
492:            }
493:
494:            /**
495:             * getSignature() method testing.
496:             */
497:            public void testGetSignature() {
498:                if (!Arrays.equals(signatureValue, certificate.getSignature())) {
499:                    fail("Incorrect Signature value.");
500:                }
501:            }
502:
503:            /**
504:             * getSigAlgName() method testing.
505:             */
506:            public void testGetSigAlgName() {
507:                assertEquals("Incorrect value of signature algorithm name",
508:                        algName, certificate.getSigAlgName());
509:            }
510:
511:            /**
512:             * getSigAlgOID() method testing.
513:             */
514:            public void testGetSigAlgOID() {
515:                assertEquals("Incorrect value of signature algorithm OID",
516:                        algOID, certificate.getSigAlgOID());
517:            }
518:
519:            /**
520:             * getSigAlgParams() method testing.
521:             */
522:            public void testGetSigAlgParams() {
523:                if (!Arrays.equals(algParams, certificate.getSigAlgParams())) {
524:                    fail("Incorrect SigAlgParams value.");
525:                }
526:            }
527:
528:            /**
529:             * getIssuerUniqueID() method testing.
530:             */
531:            public void testGetIssuerUniqueID() {
532:                if (!Arrays.equals(issuerUniqueID, certificate
533:                        .getIssuerUniqueID())) {
534:                    fail("Incorrect issuerUniqueID value.");
535:                }
536:            }
537:
538:            /**
539:             * getSubjectUniqueID() method testing.
540:             */
541:            public void testGetSubjectUniqueID() {
542:                if (!Arrays.equals(subjectUniqueID, certificate
543:                        .getSubjectUniqueID())) {
544:                    fail("Incorrect subjectUniqueID value.");
545:                }
546:            }
547:
548:            /**
549:             * getKeyUsage() method testing.
550:             */
551:            public void testGetKeyUsage() {
552:                boolean[] ku = certificate.getKeyUsage();
553:                if ((ku == null) || (ku.length < extnKeyUsage.length)) {
554:                    fail("Incorrect Key Usage value.");
555:                }
556:                for (int i = 0; i < extnKeyUsage.length; i++) {
557:                    if (extnKeyUsage[i] != ku[i]) {
558:                        fail("Incorrect Key Usage value.");
559:                    }
560:                }
561:            }
562:
563:            /**
564:             * getExtendedKeyUsage() method testing.
565:             */
566:            public void testGetExtendedKeyUsage() throws Exception {
567:                List exku = certificate.getExtendedKeyUsage();
568:                if ((exku == null)
569:                        || (exku.size() != extnExtendedKeyUsage.size())) {
570:                    fail("Incorrect Extended Key Usage value.");
571:                }
572:                for (int i = 0; i < extnExtendedKeyUsage.size(); i++) {
573:                    String ku = ObjectIdentifier
574:                            .toString((int[]) extnExtendedKeyUsage.get(i));
575:                    if (!exku.contains(ku)) {
576:                        fail("Missing value:" + ku);
577:                    }
578:                }
579:            }
580:
581:            /**
582:             * getBasicConstraints() method testing.
583:             */
584:            public void testGetBasicConstraints() {
585:                assertEquals(extnBCLen, certificate.getBasicConstraints());
586:            }
587:
588:            /**
589:             * getSubjectAlternativeNames() method testing.
590:             */
591:            public void testGetSubjectAlternativeNames() {
592:                try {
593:                    Collection certSans = certificate
594:                            .getSubjectAlternativeNames();
595:                    if (certSans == null) {
596:                        fail("Returned value should not be null.");
597:                    }
598:                    List sans = extnSANames.getPairsList();
599:                    if (sans.size() != certSans.size()) {
600:                        fail("Size of returned collection does not match to the actual");
601:                    }
602:                    Iterator it = certSans.iterator();
603:                    while (it.hasNext()) {
604:                        List extnSan = (List) it.next();
605:                        Integer tag = (Integer) extnSan.get(0);
606:                        for (int i = 0; i < sans.size(); i++) {
607:                            List san = (List) sans.get(i);
608:                            if (tag.equals(san.get(0))) {
609:                                assertEquals(
610:                                        "Incorrect value of Subject Alternative Name",
611:                                        extnSan.get(1), san.get(1));
612:                            }
613:                        }
614:                    }
615:                } catch (CertificateParsingException e) {
616:                    fail("Subject Alternative Name extension was incorrectly encoded.");
617:                }
618:            }
619:
620:            /**
621:             * getIssuerAlternativeNames() method testing.
622:             */
623:            public void testGetIssuerAlternativeNames() {
624:                try {
625:                    Collection certIans = certificate
626:                            .getIssuerAlternativeNames();
627:                    if (certIans == null) {
628:                        fail("Returned value should not be null.");
629:                    }
630:                    List ians = extnSANames.getPairsList();
631:                    if (ians.size() != certIans.size()) {
632:                        fail("Size of returned collection does not match to the actual");
633:                    }
634:                    Iterator it = certIans.iterator();
635:                    while (it.hasNext()) {
636:                        List extnIan = (List) it.next();
637:                        Integer tag = (Integer) extnIan.get(0);
638:                        for (int i = 0; i < ians.size(); i++) {
639:                            List ian = (List) ians.get(i);
640:                            if (tag.equals(ian.get(0))) {
641:                                assertEquals(
642:                                        "Incorrect value of Issuer Alternative Name",
643:                                        extnIan.get(1), ian.get(1));
644:                            }
645:                        }
646:                    }
647:                } catch (CertificateParsingException e) {
648:                    fail("Issuer Alternative Name extension was incorrectly encoded.");
649:                }
650:            }
651:
652:            /**
653:             * getEncoded() method testing.
654:             */
655:            public void testGetEncoded() {
656:                try {
657:                    if (!Arrays.equals(certEncoding, certificate.getEncoded())) {
658:                        fail("Incorrect encoding of Certificate.");
659:                    }
660:                } catch (CertificateEncodingException e) {
661:                    fail("Unexpected CertificateEncodingException was thrown.");
662:                }
663:            }
664:
665:            /**
666:             * getPublicKey() method testing.
667:             */
668:            public void testGetPublicKey() {
669:                if (!Arrays.equals(keyEncoding, certificate.getPublicKey()
670:                        .getEncoded())) {
671:                    fail("Incorrect Public Key.");
672:                }
673:            }
674:
675:            /**
676:             * getExtensionValue(String oid) method testing.
677:             */
678:            public void testGetExtensionValue() {
679:                for (int i = 0; i < extensions.length; i++) {
680:                    String id = extensions[i].getExtnID();
681:                    byte[] certExtnValue = certificate.getExtensionValue(id);
682:                    byte[] certExtnValue2Check = extensions[i]
683:                            .getRawExtnValue();
684:                    certificate.getExtensionValue(id);
685:                    if (!Arrays.equals(certExtnValue2Check, certExtnValue)) {
686:                        System.out.println("Extension encoding mismatch for "
687:                                + id);
688:                        System.out.println("Expected:");
689:                        printAsHex(20, "", " ", certExtnValue2Check);
690:                        System.out.println("But has been got:");
691:                        if (certExtnValue == null) {
692:                            System.out.println("null");
693:                        } else {
694:                            printAsHex(20, "", " ", certExtnValue);
695:                        }
696:                        fail("The values for extension " + id + " differ.");
697:                    }
698:                }
699:                assertNull("Null value should be returned in the case of "
700:                        + "nonexisting extension", certificate
701:                        .getExtensionValue("1.1.1.1"));
702:            }
703:
704:            /**
705:             * getCriticalExtensionOIDs() method testing.
706:             */
707:            public void testGetCriticalExtensionOIDs() {
708:                Set certCEOids = certificate.getCriticalExtensionOIDs();
709:                if (!(certCEOids.containsAll(allCritical) && allCritical
710:                        .containsAll(certCEOids))) {
711:                    fail("Incorrect value of Critical Extension OIDs");
712:                }
713:            }
714:
715:            /**
716:             * getNonCriticalExtensionOIDs() method testing.
717:             */
718:            public void testGetNonCriticalExtensionOIDs() {
719:                Set certNCEOids = certificate.getNonCriticalExtensionOIDs();
720:                if (!(certNCEOids.containsAll(allNonCritical) && allNonCritical
721:                        .containsAll(certNCEOids))) {
722:                    fail("Incorrect value of Non Critical Extension OIDs");
723:                }
724:            }
725:
726:            /**
727:             * hasUnsupportedCriticalExtension() method testing.
728:             */
729:            public void testHasUnsupportedCriticalExtension() {
730:                assertTrue(
731:                        "Incorrect value of hasUnsupportedCriticalExtension",
732:                        certificate.hasUnsupportedCriticalExtension());
733:
734:                if (!certificate.hasUnsupportedCriticalExtension()) {
735:                    fail("Incorrect value of hasUnsupportedCriticalExtension");
736:                }
737:            }
738:
739:            /**
740:             * toString() method testing.
741:             */
742:            public void testToString() {
743:                assertNotNull("String representation should not be null",
744:                        certificate.toString());
745:            }
746:
747:            /**
748:             * TODO
749:             * verify(PublicKey key) method testing.
750:             */
751:            public void testVerify1() throws Exception {
752:                certificate.verify(publicKey);
753:            }
754:
755:            /**
756:             * TODO
757:             * verify(PublicKey key, String sigProvider) method testing.
758:             */
759:            public void testVerify2() throws Exception {
760:                certificate.verify(publicKey, Signature.getInstance(
761:                        "SHA1withDSA").getProvider().getName());
762:            }
763:
764:            /**
765:             * TODO
766:             * verify(PublicKey key) method testing.
767:             */
768:            public void testVerify3() throws Exception {
769:                try {
770:                    certificate.verify(publicKey);
771:                    fail("Incorrect signature successfully verified.");
772:                } catch (Exception e) {
773:                }
774:            }
775:
776:            public static Test suite() {
777:                return new TestSuite(X509CertImplTest.class);
778:            }
779:
780:            public static void main(String[] args) throws Exception {
781:                junit.textui.TestRunner.run(suite());
782:            }
783:        }
w___ww_._j__a___v_a2_s__._c_om | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.