Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java security evolution and concepts, Part 5

J2SE 1.4 offers numerous improvements to Java security

  • Print
  • Feedback

Page 5 of 6

Java Certification Path programming model

Next, we see an example of validating a Certification Path of X.509 certificates. The following steps illustrate how to accomplish that task:

    // Fetch or build a certificate chain
    Certificate[] certArray = pks.getCertificateChain("rags");
    // Convert chain to a List
    List certList = Arrays.asList(certArray);
    // Instantiate a CertificateFactory for X.509 
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Extract the certification path from
    // the List of Certificates
     CertPath cp = cf.generateCertPath(certList);
    // Create CertPathValidator that implements the "PKIX" algorithm
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
     // Set the Trust anchor
    TrustAnchor anchor = new TrustAnchor((X509Certificate)tks.getCertificate("ca"), null);
    // Set the PKIX parameters
    PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
    params.setRevocationEnabled(false);
    // Validate and obtain results
    try {
        PKIXCertPathValidatorResult result =
            (PKIXCertPathValidatorResult) cpv.validate(cp, params);
     } catch (CertPathValidatorException cpve) {
        System.out.println("Validation failure, cert[" 
            + cpve.getIndex() + "] :" + cpve.getMessage());
     }


The code snippet above illustrates the validation of a certificate chain from the keystore using a trust anchor obtained from a truststore.

Java Certification Path example programs



For the purposes of the examples, we have disabled revocation checking to make the sample code easier to execute. The PKIX validation algorithm requires us to check the revocation status of each certificate in a chain. The user should be aware of the security risks associated with explicitly disabling certificate revocation checking.

To illustrate the programming model highlighted above, we validate a self-certified certificate chain using the same key as trust anchor. The example is not a useful real-life example, but nevertheless illustrates the API's use:

Example 1, Step 1. Create a keystore with a key, which also self-certifies it.

C:\rags>keytool -genkey -alias rags -keystore certpath.keystore
Enter keystore password:  changeit
What is your first and last name?
  [Unknown]:  Rags Srinivas
What is the name of your organizational unit?
  [Unknown]:  SDN
What is the name of your organization?
  [Unknown]:  Sun
What is the name of your City or Locality?
  [Unknown]:  Burlington
What is the name of your State or Province?
  [Unknown]:  MA
What is the two-letter country code for this unit?
  [Unknown]:  US
Is CN=Rags Srinivas, OU=SDN, O=Sun, L=Burlington, ST=MA, C=US correct?
  [no]:  yes
Enter key password for <rags>
        (RETURN if same as keystore password):


Example 1, Step 2. Verify whether the certificate chain has been properly generated. The certificate chain length should be 1 and the owner and issuer must be identical.

C:\rags>keytool -list -v -alias rags -keystore certpath.keystore
Enter keystore password:  changeit
Alias name: rags
Creation date: Dec 10, 2001
Entry type: keyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Rags Srinivas, OU=SDN, O=Sun, L=Burlington, ST=MA, C=US
Issuer: CN=Rags Srinivas, OU=SDN, O=Sun, L=Burlington, ST=MA, C=US
Serial number: 3c148eca
Valid from: Mon Dec 10 05:30:34 EST 2001 until: Sun Mar 10 05:30:34 EST 2002
Certificate fingerprints:
         MD5:  97:40:C2:87:14:FD:54:1F:E3:EB:3E:27:C0:34:70:A8
         SHA1: B1:0E:0A:78:EA:10:D9:21:31:1F:DB:F2:2F:26:8B:97:77:5D:07:69


Example 1, Step 3. Compile and run the following program, which reads the self-certified chain from the keystore and validates it against the same certificate. The example program ignores some of the possible exceptions that could be generated.

/**
 * ValidateSelfCert : validates an X.509 certification path
 *      using a PKIX CertPathValidator
 *
 * Synopsis: java ValidateSelfCert keystore password alias
 *
 * The program validates the certificate chain in the keystore
 *  referred by the "alias".
 */
import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.io.*;
class ValidateSelfCert
{
    public static void main(String args[])
    {
        // Instantiate a KeyStore with type JKS
        try {
            if (args.length != 3)
                throw new Exception("ValidateCert " + "keystore " + "password " + "alias");
           KeyStore ks = KeyStore.getInstance("JKS");
            // Load the contents of the KeyStore
            ks.load(new FileInputStream(args[0]),
                args[1].toCharArray());
             // Fetch certificate chain stored with alias "rags"
             java.security.cert.Certificate[] certArray = ks.getCertificateChain(args[2]);
             if (certArray == null)
                throw new Exception("Alias " + args[2] + " is not a certificate chain");
             // Convert chain to a List
             List certList = Arrays.asList(certArray);
             // Instantiate a CertificateFactory for X.509
             CertificateFactory cf = CertificateFactory.getInstance("X.509");
             // Extract the certification path from
             // the List of Certificates
             CertPath cp = cf.generateCertPath(certList);
             // Create CertPathValidator that implements the "PKIX" algorithm
             CertPathValidator cpv = null;
             cpv = CertPathValidator.getInstance("PKIX");
             // Set the Trust anchor
             TrustAnchor anchor = new TrustAnchor((X509Certificate)ks.getCertificate(args[2]), null);
             // Set the PKIX parameters
             PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
             params.setRevocationEnabled(false);
             // Validate and obtain results
             try {
                 PKIXCertPathValidatorResult result =
                     (PKIXCertPathValidatorResult) cpv.validate(cp, params);
                 PolicyNode policyTree = result.getPolicyTree();
                 PublicKey subjectPublicKey = result.getPublicKey();
                 System.out.println("Certificate validated");
                 System.out.println("Policy Tree:\n" + policyTree);
                 System.out.println("Subject Public key:\n" +subjectPublicKey);
             } catch (CertPathValidatorException cpve) {
                 System.out.println("Validation failure, cert[" 
                     + cpve.getIndex() + "] :" + cpve.getMessage());
             }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


You should see output resembling:

C:\rags>java ValidateSelfCert certpath.keystore changeit rags
Certificate validated
Policy Tree:
null
Subject Public key:
Sun DSA Public Key
    Parameters:DSA
        p:     fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
    455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
    6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
    83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
        q:     9760508f 15230bcc b292b982 a2eb840b f0581cf5
        g:     f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
    5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
    3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
    cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a
  y:
    5834e353 dbc0be85 fce9c28d 1679066c b2a93d23 651f731b 40c96e2f 445db11b
    82209777 2cce98a8 65aa5545 5a0d4e3a 45b52fe3 24276c7b 7f8f5189 162626cc
    bf98703f 9350b49f 7ae22330 dfe11f89 928f3acc 69e69419 d73ca568 a0f459c1
    743028b3 b59977a3 66b0383c aaf01645 efa7091d 493e6b8c 15f06391 c780f6e2


The example above illustrates a certification path validation. However, the example seems unrealistic since the validation concerns a self-certified certificate.

  • Print
  • Feedback

Resources
  • Java security resources from java.sun.com:
  • Security-related Java Specification Requests at the Java Community Process:
  • Other important Java security resources:
  • JavaWorld's Java security resources:
  • "Construct Secure Networked Applications with Certificates," Todd Sundsted (JavaWorld):
  • You'll find a wealth of IT-related articles from our sister publications at IDG.net