pki

Java(TM) PKI API Programmer's Guide JavaTM PKI Programmer's Guide Overview Acknowledgments Who Should Read This DocumentRelated DocumentationIntroduction Core Classes and Interfaces Basic Classes The CertPath Class The CertificateFactory Class The CertPathParameters Interface Certification Path Validation Classes The CertPathValidator Class The CertPathValidatorResult Interface Certification Path Building Classes The CertPathBuilder Class The CertPathBuilderResult Interface Certificate/CRL Storage Classes The CertStore Class The CertStoreParameters Interface The LDAPCertStoreParameters Class The CollectionCertStoreParameters Class The CertSelector and CRLSelector Interfaces The X509CertSelector Class The X509CRLSelector Class PKIX Classes The TrustAnchor Class The PKIXParameters Class The PKIXCertPathValidatorResult Class The PolicyNode Interface and PolicyQualifierInfo Class The PKIXBuilderParameters Class The PKIXCertPathBuilderResult Class The PKIXCertPathChecker Class Implementing a Service Provider Appendix A: Standard Names Appendix B: The "SUN" Provider Appendix C: On-Line Certificate Status Protocol (OCSP) Support Overview The JavaTM Certification Path API consists of classes and interfaces for handling certification paths (also known as "certificate chains"). A certification path is an ordered list of certificates. If a certification path meets certain validation rules, it may be used to securely establish the mapping of a public key to a subject. This API defines interfaces and abstract classes for creating, building, and validating certification paths. Implementations may be plugged in using a provider-based interface. The API is based on the Cryptographic Service Provider architecture, described in the Java Cryptography Architecture Reference Guide. The API also includes algorithm-specific classes for building and validating X.509 certification paths according to the PKIX standards. The PKIX standards are developed by the IETF PKIX working group. This API was originally specified using the Java Community ProcessSM program as JavaTM Specification Request (JSR) 000055. The API was included in the JavaTM SDK, starting with Java 2 Standard Edition (JDK), v 1.4. Please refer to the JSR 055 Home Page for more information on the JSR. Acknowledgments The author would like to thank the individuals who contributed to the Certification Path API and provided useful comments and technical advice. Special thanks to the members of the Sun Microsystems Laboratories team who designed and developed the Certification Path API which provided the basis of the work for the Java Community Process. This team includes Anne Anderson, Yassir Elley, Geoff Goodell, Steve Hanna, Sean Mullan, Radia Perlman, and Seth Proctor. The expert group helped improve and refine the API using the Java Community Process and includes the following members: Peter Hesse, CygnaCom Solutions, An Entrust Technologies Company Sean Mullan, Sun Microsystems (Specification Lead) Anthony Nadalin, IBM Bob Naugle, Bluestone Software Hemma Prafullchandra, VeriSign Ming Yung, DSTC Maxine Erlund, Steve Hanna, Phil Rosenzweig and Bob Sproull of Sun Microsystems provided leadership and vision. The members of the Java Security, Networking and Naming Group of Sun Microsystems contributed invaluable comments and support, especially Sharon Liu, Jeff Nisewanger, Gary Ellison, and Andreas Sterbenz. Helpful comments and advice were received from many in the technical community, especially Mary Dageforde, Edward Dobner, Tom Gindin, Jan Luehe, David Kuehr-McLaren, Parag Salvi, Alexei Semidetnov, and Yanni Zhang. Who Should Read This Document This document is intended for two classes of experienced developers: those who want to design secure applications that build or validate certification paths. those who want to write a service provider implementation for building or validating certification paths. Related Documentation This document assumes you have already read the following documents: X.509 Certificates and Certificate Revocation Lists (CRLs) Java Cryptography Architecture Reference Guide How to Implement a Provider for the Java Cryptography Architecture Introduction Users of public key applications and systems must be confident that a subject's public key is genuine, i.e., that the associated private key is owned by the subject. Public key certificates are used to establish this trust. A public key (or identity) certificate is a binding of a public key to an identity, which is digitally signed by the private key of another entity, often called a Certification Authority (CA). We shall use the term CA to refer to an entity that signs a certificate for the remainder of this section. If the user does not have a trusted copy of the public key of the CA that signed the subject's public key certificate, then another public key certificate vouching for the signing CA is required. This logic can be applied recursively, until a chain of certificates (or a certification path) is discovered from a trust anchor or a most-trusted CA to the target subject (commonly referred to as the end-entity). The most-trusted CA is usually specified by a certificate issued to a CA that the user directly trusts. In general, a certification path is an ordered list of certificates, usually comprised of the end-entity's public key certificate and zero or more additional certificates. A certification path typically has one or more encodings, allowing it to be safely transmitted across networks and to different operating system architectures. Figure 1 illustrates a certification path from a most-trusted CA's public key (CA 1) to the target subject (Alice). The certification path establishes trust in Alice's public key through an intermediate CA named CA2. Figure 1: Certification Path A certification path must be validated before it can be relied on to establish trust in a subject's public key. Validation can consist of various checks on the certificates contained in the certification path, such as verifying the signatures and checking that each certificate has not been revoked. The PKIX standards define an algorithm for validating certification paths consisting of X.509 certificates. Often a user may not have a certification path from a most-trusted CA to the subject. Providing services to build or discover certification paths is an important feature of public key enabled systems. RFC 2587 defines an LDAP (Lightweight Directory Access Protocol) schema definition which facilitates the discovery of X.509 certification paths using the LDAP directory service protocol. Building and validating certification paths is an important part of many standard security protocols such as SSL/TLS, S/MIME, and IPSEC. The JavaTM Certification Path API provides a set of classes and interfaces for developers who need to integrate this functionality into their applications. This API benefits two types of developers: those who need to write service provider implementations for a specific certification path building or validation algorithm; and those who need to access standard algorithms for creating, building, and validating certification paths in an implementation-independent manner. Core Classes and Interfaces The core classes of the Java Certification Path API consist of interfaces and classes that support certification path functionality in an algorithm- and implementation -independent manner. The API also includes a set of algorithm-specific classes for the PKIX standards that are discussed in the section titled PKIX Classes. The API builds on and extends the existing JavaTM Standard Edition (JDK) java.security.cert package for handling certificates. The core classes can be broken up into 4 class categories: Basic, Validation, Building, and Storage: Basic Certification Path Classes CertPath, CertificateFactory, CertPathParameters Certification Path Validation Classes CertPathValidator, CertPathValidatorResult Certification Path Building Classes CertPathBuilder, CertPathBuilderResult Certificate/CRL Storage Classes CertStore, CertStoreParameters, CertSelector, CRLSelector The following sections describe the most commonly used methods of each class and interface. Usage examples for some of the classes are interspersed throughout the guide. The complete reference documentation for the relevant Certification Path API classes can be found in: java.security.cert package summary Most of the classes and interfaces in the CertPath API are not thread-safe. However, there are some exceptions which will be noted in this guide and the API specification. Multiple threads that need to access a single non-thread-safe object concurrently should synchronize amongst themselves and provide the necessary locking. Multiple threads each manipulating separate objects need not synchronize. Basic Certification Path Classes The basic certification path classes provide fundamental functionality for encoding and representing certification paths. The key basic class in the Java Certification Path API is CertPath, which encapsulates the universal aspects shared by all types of certification paths. An application uses an instance of the CertificateFactory class to create a CertPath object. The CertPath Class The CertPath class is an abstract class for certification paths. It defines the functionality shared by all certification path objects. Various certification path types can be implemented by subclassing the CertPath class, even though they may have different contents and ordering schemes. All CertPath objects are serializable, immutable and thread-safe and share the following characteristics: A type This corresponds to the type of the certificates in the certification path, for example: X.509. The type of a CertPath is obtained using the method: public String getType() See Appendix A in the Java Cryptography Architecture Reference Guide for information about standard certificate types. A list of certificates The getCertificates method returns the list of certificates in the certification path: public abstract List getCertificates() This method returns a List of zero or more java.security.cert.Certificate objects. The returned List and the Certificates contained within it are immutable, in order to protect the contents of the CertPath object. The ordering of the certificates returned depends on the type. By convention, the certificates in a CertPath object of type X.509 are ordered starting with the target certificate and ending with a certificate issued by the trust anchor. That is, the issuer of one certificate is the subject of the following one. The certificate representing the TrustAnchor should not be included in the certification path. Unvalidated X.509 CertPaths may not follow this convention. PKIX CertPathValidators will detect any departure from these conventions that cause the certification path to be invalid and throw a CertPathValidatorException. One or more encodings Each CertPath object supports one or more encodings. These are external encoded forms for the certification path, used when a standard representation of the path is needed outside the Java Virtual Machine (as when transmitting the path over a network to some other party). Each path can be encoded in a default format, the bytes of which are returned using the method: public abstract byte[] getEncoded() Alternatively, the getEncoded(String) method returns a specific supported encoding by specifying the encoding format as a String (ex: "PKCS7"). A list of standard encoding formats are defined in Appendix A. public abstract byte[] getEncoded(String encoding) Also, the getEncodings method returns an iterator over the supported encoding format Strings (the default encoding format is returned first): public abstract Iterator getEncodings() All CertPath objects are also Serializable. CertPath objects are resolved into an alternate CertPathRep object during serialization. This allows a CertPath object to be serialized into an equivalent representation regardless of its underlying implementation. CertPath objects are generated from an encoded byte array or list of Certificates using a CertificateFactory. Alternatively, a CertPathBuilder may be used to try to find a CertPath from a most-trusted CA to a particular subject. Once a CertPath object has been created, it may be validated by passing it to the validate method of CertPathValidator. Each of these concepts are explained in more detail in subsequent sections. The CertificateFactory Class The CertificateFactory class is an engine class that defines the functionality of a certificate factory. In releases prior to JDK, v 1.4 it was used to generate Certificate and CRL objects. It was enhanced in JDK, v 1.4 to also be used to generate certification path (CertPath) objects. A CertificateFactory should not be confused with a CertPathBuilder. A CertPathBuilder (discussed later) is used to discover or find a certification path when one does not exist. In contrast, a CertificateFactory is used when a certification path has already been discovered and the caller needs to instantiate a CertPath object from its contents which exist in a different form such as an encoded byte array or an array of Certificates. Creating a CertificateFactory Object See the CertificateFactory section in the Java Cryptography Architecture Reference Guide for details on creating a CertificateFactory object. Generating CertPath Objects A CertificateFactory instance generates CertPath objects from a List of Certificate objects or from an InputStream that contains the encoded form of a CertPath. Just like a CertPath, each CertificateFactory supports a default encoding format for certification paths (ex: PKCS#7). To generate a CertPath object and initialize it with the data read from an input stream (in the default encoding format), use the generateCertPath method: public final CertPath generateCertPath(InputStream inStream) or from a particular encoding format: public final CertPath generateCertPath(InputStream inStream, String encoding) To find out what encoding formats are supported, use the getCertPathEncodings method (the default encoding is returned first): public final Iterator getCertPathEncodings() To generate a certification path object from a List of Certificate objects, use the following method: public final CertPath generateCertPath(List certificates) A CertificateFactory always returns CertPath objects that consist of Certificates that are of the same type as the factory. For example, a CertificateFactory of type X.509 returns CertPath objects consisting of certificates that are an instance of java.security.cert.X509Certificate. The following code sample illustrates generating a certification path from a PKCS#7 encoded certificate reply stored in a file: // open an input stream to the file FileInputStream fis = new FileInputStream(filename); // instantiate a CertificateFactory for X.509 CertificateFactory cf = CertificateFactory.getInstance("X.509"); // extract the certification path from // the PKCS7 SignedData structure CertPath cp = cf.generateCertPath(fis, "PKCS7"); // print each certificate in the path List certs = cp.getCertificates(); for (Certificate cert : certs) { System.out.println(cert); } Here's another code sample that fetches a certificate chain from a KeyStore and converts it to a CertPath using a CertificateFactory: // instantiate a KeyStore with type JKS KeyStore ks = KeyStore.getInstance("JKS"); // load the contents of the KeyStore ks.load(new FileInputStream("./keystore"), "password".toCharArray()); // fetch certificate chain stored with alias "sean" Certificate[] certArray = ks.getCertificateChain("sean"); // 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); Note that there is an existing method in CertificateFactory named generateCertificates that parses a sequence of Certificates. For encodings consisting of multiple certificates, use generateCertificates when you want to parse a collection of possibly unrelated certificates. Otherwise, use generateCertPath when you want to generate a CertPath and subsequently validate it with a CertPathValidator (discussed later). The CertPathParameters Interface The CertPathParameters interface is a transparent representation of the set of parameters used with a particular certification path builder or validation algorithm. Its main purpose is to group (and provide type safety for) all certification path parameter specifications. The CertPathParameters interface extends the Cloneable interface and defines a clone() method that does not throw an exception. All concrete implementations of this interface should implement and override the Object.clone() method, if necessary. This allows applications to clone any CertPathParameters object. Objects implementing the CertPathParameters interface are passed as arguments to methods of the CertPathValidator and CertPathBuilder classes. Typically, a concrete implementation of the CertPathParameters interface will hold a set of input parameters specific to a particular certification path build or validation algorithm. For example, the PKIXParameters class is an implementation of the CertPathParameters interface that holds a set of input parameters for the PKIX certification path validation algorithm. One such parameter is the set of most-trusted CAs that the caller trusts for anchoring the validation process. This parameter among others is discussed in more detail in the section discussing the PKIXParameters class. Certification Path Validation Classes The Java Certification Path API includes classes and interfaces for validating certification paths. An application uses an instance of the CertPathValidator class to validate a CertPath object. If successful, the result of the validation algorithm is returned in an object implementing the CertPathValidatorResult interface. The CertPathValidator Class The CertPathValidator class is an engine class used to validate a certification path. Creating a CertPathValidator Object As with all engine classes, the way to get a CertPathValidator object for a particular validation algorithm is to call one of the getInstance static factory methods on the CertPathValidator class: public static CertPathValidator getInstance(String algorithm) public static CertPathValidator getInstance(String algorithm, String provider) public static CertPathValidator getInstance(String algorithm, Provider provider) The algorithm parameter is the name of a certification path validation algorithm (for example, "PKIX"). Standard CertPathValidator algorithm names are listed in Appendix A. Validating a Certification Path Once a CertPathValidator object is created, paths can be validated by calling the validate method, passing it the certification path to be validated and a set of algorithm-specific parameters: public final CertPathValidatorResult validate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException If the validation algorithm is successful, the result is returned in an object implementing the CertPathValidatorResult interface. Otherwise, a CertPathValidatorException is thrown. The CertPathValidatorException contains methods that return the CertPath, and if relevant, the index of the certificate that caused the algorithm to fail and the root exception or cause of the failure. Note that the CertPath and CertPathParameters passed to the validate method must be of a type that is supported by the validation algorithm. Otherwise, an InvalidAlgorithmParameterException is thrown. For example, a CertPathValidator instance that implements the PKIX algorithm validates CertPath objects of type X.509 and CertPathParameters that are an instance of PKIXParameters. The CertPathValidatorResult Interface The CertPathValidatorResult interface is a transparent representation of the successful result or output of a certification path validation algorithm. Its main purpose is to group (and provide type safety for) all validation results. Like the CertPathParameters interface, CertPathValidatorResult extends Cloneable and defines a clone() method that does not throw an exception. This allows applications to clone any CertPathValidatorResult object. Objects implementing the CertPathValidatorResult interface are returned by the validate method of CertPathValidator (only when successful; otherwise a CertPathValidatorException is thrown with a description of the failure). Typically, a concrete implementation of the CertPathValidatorResult interface will hold a set of output parameters specific to a particular certification path validation algorithm. For example, the PKIXCertPathValidatorResult class is an implementation of the CertPathValidatorResult interface which contains methods to get the output parameters of the PKIX certification path validation algorithm. One such parameter is the valid policy tree. This parameter among others is discussed in more detail in the section discussing the PKIXCertPathValidatorResult class. Here's a simplified code sample that illustrates how to create a CertPathValidator and use it to validate a certification path. The sample assumes that the CertPath and CertPathParameters objects which are passed to the validate method have been previously created; a more complete example will be illustrated in the section describing the PKIX classes. // create CertPathValidator that implements the "PKIX" algorithm CertPathValidator cpv = null; try { cpv = CertPathValidator.getInstance("PKIX"); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae); System.exit(1); } // validate certification path ("cp") with specified parameters ("params") try { CertPathValidatorResult cpvResult = cpv.validate(cp, params); } catch (InvalidAlgorithmParameterException iape) { System.err.println("validation failed: " + iape); System.exit(1); } catch (CertPathValidatorException cpve) { System.err.println("validation failed: " + cpve); System.err.println("index of certificate that caused exception: " + cpve.getIndex()); System.exit(1); } Certification Path Building Classes The Java Certification Path API includes classes for building (or discovering) certification paths. An application uses an instance of the CertPathBuilder class to build a CertPath object. If successful, the result of the build is returned in an object implementing the CertPathBuilderResult interface. The CertPathBuilder Class The CertPathBuilder class is an engine class used to build a certification path. Creating a CertPathBuilder Object As with all engine classes, the way to get a CertPathBuilder object for a particular build algorithm is to call one of the getInstance static factory method on the CertPathBuilder class: public static CertPathBuilder getInstance(String algorithm) public static CertPathBuilder getInstance(String algorithm, String provider) public static CertPathBuilder getInstance(String algorithm, Provider provider) The algorithm parameter is the name of a certification path builder algorithm (for example, "PKIX"). Standard CertPathBuilder algorithm names are listed in Appendix A. Building a Certification Path Once a CertPathBuilder object is created, paths can be constructed by calling the build method, passing it an algorithm-specific parameter specification: public final CertPathBuilderResult build(CertPathParameters params) throws CertPathBuilderException, InvalidAlgorithmParameterException If the build algorithm is successful, the result is returned in an object implementing the CertPathBuilderResult interface. Otherwise, a CertPathBuilderException is thrown containing information about the failure; for example, the underlying exception (if any) and an error message. Note that the CertPathParameters passed to the build method must be of a type that is supported by the build algorithm. Otherwise, an InvalidAlgorithmParameterException is thrown. The CertPathBuilderResult Interface The CertPathBuilderResult interface is a transparent representation of the result or output of a certification path builder algorithm. This interface contains a method to return the certification path that has been successfully built: public CertPath getCertPath() The purpose of the CertPathBuilderResult interface is to group (and provide type safety for) all build results. Like the CertPathValidatorResult interface, CertPathBuilderResult extends Cloneable and defines a clone() method that does not throw an exception. This allows applications to clone any CertPathBuilderResult object. Objects implementing the CertPathBuilderResult interface are returned by the build method of CertPathBuilder. Here's a simplified code sample that illustrates how to create a CertPathBuilder and use it to build a certification path. The sample assumes that the CertPathParameters object which is passed to the build method has been previously created; a more complete example will be illustrated in the section describing the PKIX classes. // create CertPathBuilder that implements the "PKIX" algorithm CertPathBuilder cpb = null; try { cpb = CertPathBuilder.getInstance("PKIX"); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae); System.exit(1); } // build certification path using specified parameters ("params") try { CertPathBuilderResult cpbResult = cpb.build(params); CertPath cp = cpbResult.getCertPath(); System.out.println("build passed, path contents: " + cp); } catch (InvalidAlgorithmParameterException iape) { System.err.println("build failed: " + iape); System.exit(1); } catch (CertPathBuilderException cpbe) { System.err.println("build failed: " + cpbe); System.exit(1); } Certificate/CRL Storage Classes The Java Certification Path API also includes the CertStore class for retrieving certificates and CRLs from a repository. This is useful because it allows a caller to specify the repository a CertPathValidator or CertPathBuilder implementation should use to find certificates and CRLs (see the addCertStores method of PKIXParameters for an example). A CertPathValidator implementation may use the CertStore object that the caller specifies as a callback mechanism to fetch CRLs for performing revocation checks. Similarly, a CertPathBuilder may use the CertStore as a callback mechanism to fetch certitificates and, if performing revocation checks, CRLs. The CertStore Class The CertStore class is an engine class used to provide the functionality of a certificate and certificate revocation list (CRL) repository. It can be used by CertPathBuilder and CertPathValidator implementations to find certificates and CRLs or as a general purpose certificate and CRL retrieval mechanism. Unlike the java.security.KeyStore class, which provides access to a cache of private keys and trusted certificates, a CertStore is designed to provide access to a potentially vast repository of untrusted certificates and CRLs. For example, an LDAP implementation of CertStore provides access to certificates and CRLs stored in one or more directories using the LDAP protocol. All public methods of CertStore objects are thread-safe. That is, multiple threads may concurrently invoke these methods on a single CertStore object (or more than one) with no ill effects. This allows a CertPathBuilder to search for a CRL while simultaneously searching for further certificates, for instance. Creating a CertStore Object As with all engine classes, the way to get a CertStore object for a particular repository type is to call one of the getInstance static factory methods on the CertStore class: public static CertStore getInstance(String type, CertStoreParameters params) public static CertStore getInstance(String type, CertStoreParameters params, String provider) public static CertStore getInstance(String type, CertStoreParameters params, Provider provider) The type parameter is the name of a certificate repository type (for example, "LDAP"). Standard CertStore types are listed in Appendix A. The initialization parameters (params) are specific to the repository type. For example, the initialization parameters for a server-based repository may include the hostname and the port of the server. An InvalidAlgorithmParameterException is thrown if the parameters are invalid for this CertStore type. The getCertStoreParameters method returns the CertStoreParameters that were used to initialize a CertStore: public final CertStoreParameters getCertStoreParameters() Retrieving Certificates Once you have created a CertStore object, you can retrieve certificates from the repository using the getCertificates method. This method takes a CertSelector (discussed in more detail later) object as an argument, which specifies a set of selection criteria for determining which certificates should be returned: public final Collection getCertificates(CertSelector selector) throws CertStoreException This method returns a Collection of java.security.cert.Certificate objects that satisfy the selection criteria. An empty Collection is returned if there are no matches. A CertStoreException is usually thrown if an unexpected error condition is encountered, such as a communications failure with a remote repository. For some CertStore implementations, it may not be feasible to search the entire repository for certificates or CRLs that match the specified selection criteria. In these instances, the CertStore implementation may use information that is specified in the selectors to locate certificates and CRLs. For instance, an LDAP CertStore may not search all entries in the directory. Instead, it may just search entries that are likely to contain the certificates it is looking for. If the CertSelector provided does not provide enough information for the LDAP CertStore to determine which entries it should look in, the LDAP CertStore may throw a CertStoreException. Retrieving CRLs You can also retrieve CRLs from the repository using the getCRLs method. This method takes a CRLSelector (discussed in more detail later) object as an argument, which specifies a set of selection criteria for determining which CRLs should be returned: public final Collection getCRLs(CRLSelector selector) throws CertStoreException This method returns a Collection of java.security.cert.CRL objects that satisfy the selection criteria. An empty Collection is returned if there are no matches. The CertStoreParameters Interface The CertStoreParameters interface is a transparent representation of the set of parameters used with a particular CertStore. Its main purpose is to group (and provide type safety for) all certificate storage parameter specifications. The CertStoreParameters interface extends the Cloneable interface and defines a clone method that does not throw an exception. Implementations of this interface should implement and override the Object.clone() method, if necessary. This allows applications to clone any CertStoreParameters object. Objects implementing the CertStoreParameters interface are passed as arguments to the getInstance method of the CertStore class. Two classes implementing the CertStoreParameters interface are defined in this API: the LDAPCertStoreParameters and the CollectionCertStoreParameters classes. The LDAPCertStoreParameters Class The LDAPCertStoreParameters class is an implementation of the CertStoreParameters interface and holds a set of minimal initialization parameters (host and port number of the directory server) for retrieving certificates and CRLs from a CertStore of type LDAP. Please refer to the LDAPCertStoreParameters API documentation for more detailed information on this class. The CollectionCertStoreParameters Class The CollectionCertStoreParameters class is an implementation of the CertStoreParameters interface and holds a set of initialization parameters for retrieving certificates and CRLs from a CertStore of type Collection. Please refer to the CollectionCertStoreParameters API documentation for more detailed information on this class. The CertSelector and CRLSelector Interfaces The CertSelector and CRLSelector interfaces are a specification of the set of criteria for selecting certificates and CRLs from a collection or large group of certificates and CRLs. The interfaces group and provide type safety for all selector specifications. Each selector interface extends Cloneable and defines a clone() method that does not throw an exception. This allows applications to clone any CertSelector or CRLSelector object. The CertSelector and CRLSelector interfaces each define a method named match. The match method takes a Certificate or CRL object as an argument and returns true if the object satisfies the selection criteria. Otherwise, it returns false. The match method for the CertSelector interface is defined as follows: public boolean match(Certificate cert) and for the CRLSelector interface: public boolean match(CRL crl) Typically, objects implementing these interfaces are passed as parameters to the getCertificates and getCRLs methods of the CertStore class. These methods return a Collection of Certificates or CRLs from the CertStore repository that match the specified selection criteria. CertSelectors may also be used to specify the validation constraints on a target or end-entity certificate in a certification path (see for example, the PKIXParameters.setTargetCertConstraints method. The X509CertSelector Class The X509CertSelector class is an implementation of the CertSelector interface that defines a set of criteria for selecting X.509 certificates. An X509Certificate object must match all of the specified criteria to be selected by the match method. The selection criteria are designed to be used by a CertPathBuilder implementation to discover potential certificates as it builds an X.509 certification path. For example, the setSubject method of X509CertSelector allows a PKIX CertPathBuilder to filter out X509Certificates that do not match the issuer name of the preceding X509Certificate in a partially completed chain. By setting this and other criteria in an X509CertSelector object, a CertPathBuilder is able to discard irrelevant certificates and more easily find an X.509 certification path that meets the requirements specified in the CertPathParameters object. Please refer to http://www.ietf.org/rfc/rfc3280.txt for definitions of the X.509 certificate extensions mentioned in this section. Creating an X509CertSelector Object An X509CertSelector object is created by calling the default constructor: public X509CertSelector() No criteria are initially set (any X509Certificate will match). Setting Selection Criteria The selection criteria allow a caller to match on different components of an X.509 certificate. A few of the methods for setting selection criteria are described here. Please refer to the X509CertSelector API documentation for details on the other methods. The setIssuer methods set the issuer criterion: public void setIssuer(X500Principal issuer) public void setIssuer(String issuerDN) public void setIssuer(byte[] issuerDN) The specified distinguished name (in X500Principal, RFC 2253 String or ASN.1 DER encoded form) must match the issuer distinguished name in the certificate. If null, any issuer distinguished name will do. Note that use of an X500Principal to represent a distinguished name is preferred because it is more efficient and suitably typed. Similarly, the setSubject methods set the subject criterion: public void setSubject(X500Principal subject) public void setSubject(String subjectDN) public void setSubject(byte[] subjectDN) The specified distinguished name (in X500Principal, RFC 2253 String or ASN.1 DER encoded form) must match the subject distinguished name in the certificate. If null, any subject distinguished name will do. The setSerialNumber method sets the serialNumber criterion: public void setSerialNumber(BigInteger serial) The specified serial number must match the certificate serial number in the certificate. If null, any certificate serial number will do. The setAuthorityKeyIdentifier method sets the authorityKeyIdentifier criterion: public void setAuthorityKeyIdentifier(byte[] authorityKeyID) The certificate must contain an Authority Key Identifier extension matching the specified value. If null, no check will be done on the authorityKeyIdentifier criterion. The setCertificateValid method sets the certificateValid criterion: public void setCertificateValid(Date certValid) The specified date must fall within the certificate validity period for the certificate. If null, any date is valid. The setKeyUsage method sets the keyUsage criterion: public void setKeyUsage(boolean[] keyUsage) The certificate's Key Usage Extension must allow the specified key usage values (those which are set to true). If null, no keyUsage check will be done. Getting Selection Criteria The current values for each of the selection criteria can be retrieved using an appropriate get method. Please refer to the X509CertSelector API documentation for further details on these methods. Example Here is an example of retrieving X.509 certificates from an LDAP CertStore with the X509CertSelector class. First, we create the LDAPCertStoreParameters object that we will use to initialize the CertStore object with the hostname and port of the LDAP server: LDAPCertStoreParameters lcsp = new LDAPCertStoreParameters("ldap.sun.com", 389); Next, create the CertStore object, and pass it the LDAPCertStoreParameters object, as in the following statement: CertStore cs = CertStore.getInstance("LDAP", lcsp); This call creates a CertStore object that retrieves certificates and CRLs from an LDAP repository using the schema defined in RFC 2587. The following block of code establishes an X509CertSelector to retrieve all unexpired (as of the current date and time) end-entity certificates issued to a particular subject with 1) a key usage that allows digital signatures, and 2) a subject alternative name with a specific email address: X509CertSelector xcs = new X509CertSelector(); // select only unexpired certificates xcs.setCertificateValid(new Date()); // select only certificates issued to // 'CN=alice, O=xyz, C=us' xcs.setSubject(new X500Principal("CN=alice, O=xyz, C=us")); // select only end-entity certificates xcs.setBasicConstraints(-2); // select only certificates with a digitalSignature // keyUsage bit set (set the first entry in the // boolean array to true) boolean[] keyUsage = {true}; xcs.setKeyUsage(keyUsage); // select only certificates with a subjectAltName of // 'alice@xyz.com' (1 is the integer value of // an RFC822Name) xcs.addSubjectAlternativeName(1, "alice@xyz.com"); Then we pass the selector to the getCertificates method of our CertStore object that we previously created: Collection certs = cs.getCertificates(xcs); A PKIX CertPathBuilder may use similar code to help discover and sort through potential certificates by discarding those that do not meet validation constraints or other criteria. The X509CRLSelector Class The X509CRLSelector class is an implementation of the CRLSelector interface that defines a set of criteria for selecting X.509 CRLs. An X509CRL object must match all of the specified criteria to be selected by the match method. The selection criteria are designed to be useful to a CertPathValidator or CertPathBuilder implementation that must retrieve CRLs from a repository to check the revocation status of certificates in an X.509 certification path. For example, the setDateAndTime method of X509CRLSelector allows a PKIX CertPathValidator to filter out X509CRLs that have been issued after or expire before the time indicated. By setting this and other criteria in an X509CRLSelector object, it allows the CertPathValidator to discard irrelevant CRLs and more easily check if a certificate has been revoked. Please refer to http://www.ietf.org/rfc/rfc3280.txt for definitions of the X.509 CRL fields and extensions mentioned in this section. Creating an X509CRLSelector Object An X509CRLSelector object is created by calling the default constructor: public X509CRLSelector() No criteria are initially set (any X509CRL will match). Setting Selection Criteria The selection criteria allow a caller to match on different components of an X.509 CRL. Most of the methods for setting selection criteria are described here. Please refer to the X509CRLSelector API documentation for details on the remaining methods. The setIssuers and setIssuerNames methods set the issuerNames criterion: public void setIssuers(Collection issuers) public void setIssuerNames(Collection names) The issuer distinguished name in the CRL must match at least one of the specified distinguished names. The setIssuers method is preferred as the use of X500Principals to represent distinguished names is more efficient and suitably typed. For the setIssuerNames method, each entry of the names argument is either a String or a byte array (representing the name, in RFC 2253 or ASN.1 DER encoded form, respectively). If null, any issuer distinguished name will do. The setMinCRLNumber and setMaxCRLNumber methods set the minCRLNumber and maxCRLNumber criterion: public void setMinCRLNumber(BigInteger minCRL) public void setMaxCRLNumber(BigInteger maxCRL) The CRL must have a CRL Number extension whose value is greater than or equal to the specified value if the setMinCRLNumber method is called, and less than or equal to the specified value if the setMaxCRLNumber method is called. If the value passed to one of these methods is null, the corresponding check is not done. The setDateAndTime method sets the dateAndTime criterion: public void setDateAndTime(Date dateAndTime) The specified date must be equal to or later than the value of the thisUpdate component of the CRL and earlier than the value of the nextUpdate component. If null, no dateAndTime check will be done. The setCertificateChecking method sets the certificate whose revocation status is being checked: public void setCertificateChecking(X509Certificate cert) This is not a criterion. Rather, it is optional information that may help a CertStore find CRLs that would be relevant when checking revocation for the specified certificate. If null is specified, then no such optional information is provided. An application should always call this method when checking revocation for a particular certificate, as it may provide the CertStore with more information for finding the correct CRLs and filtering out irrelevant ones. Getting Selection Criteria The current values for each of the selection criteria can be retrieved using an appropriate get method. Please refer to the X509CRLSelector API documentation for further details on these methods. Example Creating an X509CRLSelector to retrieve CRLs from an LDAP repository is similar to the X509CertSelector example. Suppose we want to retrieve all current (as of the current date and time) CRLs issued by a specific CA and with a minimum CRL number. First, we create an X509CRLSelector object and call the appropriate methods to set the selection criteria: X509CRLSelector xcrls = new X509CRLSelector(); // select CRLs satisfying current date and time xcrls.setDateAndTime(new Date()); // select CRLs issued by 'O=xyz, C=us' xcrls.addIssuerName("O=xyz, C=us"); // select only CRLs with a CRL number at least '2' xcrls.setMinCRLNumber(new BigInteger("2")); Then we pass the selector to the getCRLs method of our CertStore object (created in the X509CertSelector example): Collection crls = cs.getCRLs(xcrls); PKIX Classes The Java Certification Path API also includes a set of algorithm-specific classes modelled for use with the PKIX certification path validation algorithm defined in RFC 3280: Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile. The TrustAnchor Class This class represents a "most-trusted CA", which is used as a trust anchor for validating X.509 certification paths. A most-trusted CA includes the public key of the CA, the CA's name, and any constraints upon the set of paths which may be validated using this key. These parameters can be specified in the form of a trusted X509Certificate or as individual parameters. All TrustAnchor objects are immutable and thread-safe. That is, multiple threads may concurrently invoke the methods defined in this class on a single TrustAnchor object (or more than one) with no ill effects. Requiring TrustAnchor objects to be immutable and thread-safe allows them to be passed around to various pieces of code without worrying about coordinating access. Note that although this class is described as a PKIX class it may be used with other X.509 certification path validation algorithms. Creating a TrustAnchor Object To instantiate a TrustAnchor object, a caller must specify "the most-trusted CA" as a trusted X509Certificate or public key and distinguished name pair. The caller may also optionally specify name constraints that are applied to the trust anchor by the validation algorithm during initialization. Note that support for name constraints on trust anchors is not required by the PKIX algorithm, therefore a PKIX CertPathValidator or CertPathBuilder may choose not to support this parameter and instead throw an exception. Use one of the following constructors to create a TrustAnchor object: public TrustAnchor(X509Certificate trustedCert, byte[] nameConstraints) public TrustAnchor(X500Principal caPrincipal, PublicKey pubKey, byte[] nameConstraints) public TrustAnchor(String caName, PublicKey pubKey, byte[] nameConstraints) The nameConstraints parameter is specifed as a byte array containing the ASN.1 DER encoding of a NameConstraints extension. An IllegalArgumentException is thrown if the name constraints cannot be decoded (are not formatted correctly). Getting Parameter Values Each of the parameters can be retrieved using a corresponding get method: public final X509Certificate getTrustedCert() public final X500Principal getCA() public final String getCAName() public final PublicKey getCAPublicKey() public final byte[] getNameConstraints() Note that the getTrustedCert method returns null if the trust anchor was specified as a public key and name pair. Likewise, the getCA, getCAName and getCAPublicKey methods return null if the trust anchor was specified as an X509Certificate. The PKIXParameters Class This class (which implements the CertPathParameters interface) specifies the set of input parameters defined by the PKIX certification path validation algorithm. It also includes a few additional useful parameters. An X.509 CertPath object and a PKIXParameters object are passed as arguments to the validate method of a CertPathValidator instance implementing the PKIX algorithm. The CertPathValidator uses the parameters to initialize the PKIX certification path validation algorithm. Creating a PKIXParameters Object To instantiate a PKIXParameters object, a caller must specify "the most-trusted CA(s)" as defined by the PKIX validation algorithm. The most-trusted CAs can be specified using one of two constructors: public PKIXParameters(Set trustAnchors) throws InvalidAlgorithmParameterException public PKIXParameters(KeyStore keystore) throws KeyStoreException, InvalidAlgorithmParameterException The first constructor allows the caller to specify the most-trusted CAs as a Set of TrustAnchor objects. Alternatively, a caller can use the second constructor and specify a KeyStore instance containing trusted certificate entries, each of which will be considered as a most-trusted CA. Setting Parameter Values Once a PKIXParameters object has been created, a caller can set (or replace the current value of) various parameters. A few of the methods for setting parameters are described here. Please refer to the PKIXParameters API documentation for details on the other methods. The setInitialPolicies method sets the initial policy identifiers, as specified by the PKIX validation algorithm. The elements of the Set are object identifiers (OIDs) represented as a String. If the initialPolicies parameter is null or not set, any policy is acceptable: public void setInitialPolicies(Set initialPolicies) The setDate method sets the time for which the validity of the path should be determined. If the date parameter is not set or is null, the current date is used: public void setDate(Date date) The setPolicyMappingInhibited method sets the value of the policy mapping inhibited flag. The default value for the flag, if not specified, is false: public void setPolicyMappingInhibited(boolean val) The setExplicitPolicyRequired method sets the value of the explicit policy required flag. The default value for the flag, if not specified, is false: public void setExplicitPolicyRequired(boolean val) Tразделы газонокосилка dolmar французский вина хендэ соната облицовка панель рассылка корреспонденция софт автошкола крот dr кулер 775 предохранитель пкт услуга кострома заказать обед стеклянный перегородка бейсболки заказ апгрейд обезьяна пежо 407 электропечь dimplex model lee rc дермато-венеролог фарфор магнитный доска вагонка половой доска помидор купля i`m o.k./герои гроб lida консультирование организация пекарня пластиковый пакет природа охота утюг доставка канцелярия близорукость время ярославль холодный обзвон метрореклама нижнийновгород скс автошкола пежо 307 поливомоечная машина меховой холодильник сенсорный дисплей перевод денег холодный обзвон брусок алмазный прайс сушильный машина циклон цол кадровый владимир стеклянный перегородка автоматический резка карл гиря снос любой конструкция купить угольник nokia 3230 купить медикаметозное безоперационное прерывание беременность креатин mobihel краска зеркало babyliss кайт серфинг утюг концентрирование кислорода операторский центр педагогика психология стимулирующий лотерея summer кухонный мужчина выходной зеркало babyliss международный конкурс mobilux толщиномер сервис альфа лаваль оркестр креольский танго багетный мастерский фарфор бахила купить блендер кофе дорога лак orly зубной боль диспетчеризация продажа кофе электрокотел государственный герб герб вышивка охота легавый цвет камуфлир креатин флагшток внутренний использование гелусил лак гнб mobil pegasus pki