Documentation Contents

How to Implement a Provider in the Java Cryptography Architecture


Introduction

The Java platform defines a set of APIs spanning major security areas, including cryptography, public key infrastructure, authentication, secure communication, and access control. These APIs allow developers to easily integrate security into their application code. They were designed around the following principles:

  1. Implementation independence

    Applications do not need to implement security themselves. Rather, they can request security services from the Java platform. Security services are implemented in providers (see below), which are plugged into the Java platform via a standard interface. An application may rely on multiple independent providers for security functionality.

  2. Implementation interoperability

    Providers are interoperable across applications. Specifically, an application is not bound to a specific provider, and a provider is not bound to a specific application.

  3. Algorithm extensibility

    The Java platform includes a number of built-in providers that implement a basic set of security services that are widely used today. However, some applications may rely on emerging standards not yet implemented, or on proprietary services. The Java platform supports the installation of custom providers that implement such services.

A Cryptographic Service Provider (provider) refers to a package (or a set of packages) that supply a concrete implementation of a subset of the cryptography aspects of the JDK Security API.

The java.security.Provider class encapsulates the notion of a security provider in the Java platform. It specifies the provider's name and lists the security services it implements. Multiple providers may be configured at the same time, and are listed in order of preference. When a security service is requested, the highest priority provider that implements that service is selected.

The following figures illustrate these options for requesting a SHA-256 message digest implementation. Both figures show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In the diagram to the left, an application requests a SHA-256 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In the diagram to the right, the application requests the SHA-256 algorithm implementation from a specific provider, ProviderC. This time the implementation from that provider is returned, even though a provider with a higher preference order, ProviderB, also supplies a SHA-256 implementation.

diagram showing an application requesting an SHA-256 algorithem without specifying a provider name diagram showing an application requesting an SHA-256 algorithem from a specific provider
Figure 1a Provider searching Figure 2b Specific provider requested

Description of Figure 1a Provider searching and Figure 1b Specific provider requested

Each installation has one or more provider packages installed. Clients may configure their runtimes with different providers, and specify a preference order for each of them. The preference order is the order in which providers are searched for requested algorithms when no particular provider is requested.

The Oracle version of the Java runtime environment (JRE) comes standard with a default provider, named SUN. Other Java runtime environments may not necessarily supply the SUN provider.

Who Should Read This Document

Programmers that only need to use the Java Security API to access existing cryptography algorithms and other services do not need to read this document.

This document is intended for experienced programmers wishing to create their own provider packages supplying cryptographic service implementations. It documents what you need to do in order to integrate your provider into Java so that your algorithms and other services can be found when Java Security API clients request them.

Related Documentation

This document assumes you have already read the Java Cryptography Architecture Reference Guide.

It documents the packages which contain the various classes and interfaces in the Security API.

Notes on Terminology

Throughout this document, the terms JCA by itself refers to the JCA framework. Whenever this document notes a specific JCA provider, it will be referred to explicitly by the provider name.

Engine Classes and Corresponding Service Provider Interface Classes

An engine class defines a cryptographic service in an abstract fashion (without a concrete implementation).

A cryptographic service is always associated with a particular algorithm or type. It either provides cryptographic operations (like those for digital signatures or message digests, ciphers or key agreement protocols); generates or supplies the cryptographic material (keys or parameters) required for cryptographic operations; or generates data objects (keystores or certificates) that encapsulate cryptographic keys (which can be used in a cryptographic operation) in a secure fashion.

For example, here are four engine classes:

The Java Cryptography Architecture encompasses the classes comprising the Security package that relate to cryptography, including the engine classes. Users of the API request and utilize instances of the engine classes to carry out corresponding operations. The JDK defines the following engine classes:


Note: A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).


An engine class provides the interface to the functionality of a specific type of cryptographic service (independent of a particular cryptographic algorithm). It defines Application Programming Interface (API) methods that allow applications to access the specific type of cryptographic service it provides. The actual implementations (from one or more providers) are those for specific algorithms. For example, the Signature engine class provides access to the functionality of a digital signature algorithm. The actual implementation supplied in a SignatureSpi subclass (see next paragraph) would be that for a specific kind of signature algorithm, such as SHA256withDSA or SHA512withRSA.

The application interfaces supplied by an engine class are implemented in terms of a Service Provider Interface (SPI). That is, for each engine class, there is a corresponding abstract SPI class, which defines the Service Provider Interface methods that cryptographic service providers must implement.

Architecture of Service Provider Interface

Description of Architecture of Service Provider Interface

An instance of an engine class, the "API object", encapsulates (as a private field) an instance of the corresponding SPI class, the "SPI object". All API methods of an API object are declared "final", and their implementations invoke the corresponding SPI methods of the encapsulated SPI object. An instance of an engine class (and of its corresponding SPI class) is created by a call to the getInstance factory method of the engine class.

The name of each SPI class is the same as that of the corresponding engine class, followed by "Spi". For example, the SPI class corresponding to the Signature engine class is the SignatureSpi class.

Each SPI class is abstract. To supply the implementation of a particular type of service and for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.

Another example of an engine class is the MessageDigest class, which provides access to a message digest algorithm. Its implementations, in MessageDigestSpi subclasses, may be those of various message digest algorithms such as SHA256 or SHA384.

As a final example, the KeyFactory engine class supports the conversion from opaque keys to transparent key specifications, and vice versa. See Key Specification Interfaces and Classes Required by Key Factories for details. The actual implementation supplied in a KeyFactorySpi subclass would be that for a specific type of keys, e.g., DSA public and private keys.

Steps to Implement and Integrate a Provider

Follow the steps below to implement a provider and integrate it into the JCA framework:

Step 1: Write your Service Implementation Code

The first thing you need to do is to write the code that provides algorithm-specific implementations of the cryptographic services you want to support.

Note that your provider may supply implementations of cryptographic services already available in one or more of the security components of the JDK.

For cryptographic services not defined in JCA (For example; signatures and message digests), please refer to Java Cryptography Architecture Reference Guide.

For each cryptographic service you wish to implement, create a subclass of the appropriate SPI class. JCA defines the following engine classes:

(See Engine Classes and Corresponding SPI Classes in this document for information on the JCA and other cryptographic classes.)

In your subclass, you need to:

  1. Supply implementations for the abstract methods, whose names usually begin with engine. See Further Implementation Details and Requirements for additional information.
  2. Ensure there is a public constructor without any arguments. Here's why: When one of your services is requested, Java Security looks up the subclass implementing that service, as specified by a property in your "master class" (see Step 3). Java Security then creates the Class object associated with your subclass, and creates an instance of your subclass by calling the newInstance method on that Class object. newInstance requires your subclass to have a public constructor without any parameters.
  3. A default constructor without arguments will automatically be generated if your subclass doesn't have any constructors. But if your subclass defines any constructors, you must explicitly define a public constructor without arguments.

Step 1.1: Additional JCA Provider Requirements and Recommendations for Encryption Implementations

When instantiating a provider's implementation (class) of a Cipher, KeyAgreement, KeyGenerator, MAC or SecretKey factory, the framework will determine the provider's codebase (JAR file) and verify its signature. In this way, JCA authenticates the provider and ensures that only providers signed by a trusted entity can be plugged into JCA. Thus, one requirement for encryption providers is that they must be signed, as described in later steps.

In addition, each provider should perform self-integrity checking to ensure that the JAR file containing its code has not been manipulated in an attempt to invoke provider methods directly rather than through JCA. For further information, see How a Provider Can Do Self-Integrity Checking.

In order for provider classes to become unusable if instantiated by an application directly, bypassing JCA, providers should implement the following:

For providers that may be exported outside the U.S., CipherSpi implementations must include an implementation of the engineGetKeySize method which, given a Key, returns the key size. If there are restrictions on available cryptographic strength specified in jurisdiction policy files, each Cipher initialization method calls engineGetKeySize and then compares the result with the maximum allowable key size for the particular location and circumstances of the applet or application being run. If the key size is too large, the initialization method throws an exception.

Additional optional features that providers may implement are

Step 2: Give your Provider a Name

Decide on a name for your provider. This is the name to be used by client applications to refer to your provider.

Step 3: Write your Master Class, a subclass of Provider

The third step is to create a subclass of the java.security.Provider class.

Your subclass should be a final class, and its constructor should

In each of these, algName, certType, storeType, or attrName is the "standard" name of the algorithm, certificate type, keystore type, or attribute. (See Appendix A of the Java Cryptography Architecture Reference Guide for the standard names that should be used.)

For a property in the above format, the value of the property must be the value for the corresponding attribute. (See Appendix A of the Java Cryptography Architecture API Specification & Reference for the definition of each standard attribute.)

As an example, the default provider named SUN implements the SHA256withDSA Digital Signature Algorithm in software. In the master class for the provider SUN, it sets the Signature.SHA256withDSA ImplementedIn to have the value Software via the following:

    put("Signature.SHA256withDSA ImplementedIn", "Software")

For further master class property setting examples, see the JDK 8 source code for the following classes:

These files show how the SUN and SunJCE providers set properties.

Step 3.1: Additional Steps for Cipher Implementations

As mentioned above, in the case of a Cipher property, algName may actually represent a transformation. A transformation is a string that describes the operation (or set of operations) to be performed by a Cipher object on some given input. A transformation always includes the name of a cryptographic algorithm (e.g., AES), and may be followed by a mode and a padding scheme.

A transformation is of the form:

(In the latter case, provider-specific default values for the mode and padding scheme are used). For example, the following is a valid transformation:

    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); 

When requesting a block cipher in stream cipher mode (for example; AES in CFB or OFB mode), a client may optionally specify the number of bits to be processed at a time, by appending this number to the mode name as shown in the following sample transformations:

    Cipher c1 = Cipher.getInstance("AES/CFB8/NoPadding");
    Cipher c2 = Cipher.getInstance("AES/OFB32/PKCS5Padding");

If a number does not follow a stream cipher mode, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits.)

A provider may supply a separate class for each combination of algorithm/mode/padding. Alternatively, a provider may decide to provide more generic classes representing sub-transformations corresponding to algorithm or algorithm/mode or algorithm//padding (note the double slashes); in this case the requested mode and/or padding are set automatically by the getInstance methods of Cipher, which invoke the engineSetMode and engineSetPadding methods of the provider's subclass of CipherSpi.

That is, a Cipher property in a provider master class may have one of the formats shown in the table below.

Cipher Property Format Description
Cipher.algName A provider's subclass of CipherSpi implements algName with pluggable mode and padding
Cipher.algName/mode A provider's subclass of CipherSpi implements algName in the specified mode, with pluggable padding
Cipher.algName//padding A provider's subclass of CipherSpi implements algName with the specified padding, with pluggable mode
Cipher.algName/mode/padding A provider's subclass of CipherSpi implements algName with the specified mode and padding

(See Appendix A of the Java Cryptography Architecture Reference Guide for the standard algorithm names, modes, and padding schemes that should be used.)

For example, a provider may supply a subclass of CipherSpi that implements AES/ECB/PKCS5Padding, one that implements AES/CBC/PKCS5Padding, one that implements AES/CFB/PKCS5Padding, and yet another one that implements AES/OFB/PKCS5Padding. That provider would have the following Cipher properties in its master class:

Another provider may implement a class for each of the above modes (i.e., one class for ECB, one for CBC, one for CFB, and one for OFB), one class for PKCS5Padding, and a generic AES class that subclasses from CipherSpi. That provider would have the following Cipher properties in its master class:

The getInstance factory method of the Cipher engine class follows these rules in order to instantiate a provider's implementation of CipherSpi for a transformation of the form "algorithm":

  1. Check if the provider has registered a subclass of CipherSpi for the specified "algorithm".

    If the answer is YES, instantiate this class, for whose mode and padding scheme default values (as supplied by the provider) are used.

    If the answer is NO, throw a NoSuchAlgorithmException exception.

The getInstance factory method of the Cipher engine class follows these rules in order to instantiate a provider's implementation of CipherSpi for a transformation of the form "algorithm/mode/padding":

  1. Check if the provider has registered a subclass of CipherSpi for the specified "algorithm/mode/padding" transformation.

    If the answer is YES, instantiate it.

    If the answer is NO, go to the next step.
  2. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm/mode".

    If the answer is YES, instantiate it, and call engineSetPadding(padding) on the new instance.

    If the answer is NO, go to the next step.
  3. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm//padding" (note the double slashes).

    If the answer is YES, instantiate it, and call engineSetMode(mode) on the new instance.

    If the answer is NO, go to the next step.
  4. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm".

    If the answer is YES, instantiate it, and call engineSetMode(mode) and engineSetPadding(padding) on the new instance.

    If the answer is NO, throw a NoSuchAlgorithmException exception.

Step 4: Compile your Code

After you have created your implementation code (Step 1), given your provider a name (Step 2), and created the master class (Step 3), use the Java compiler to compile your files.

Step 5: Place Your Provider in a JAR File

Place your provider code in a JAR file, in preparation for signing it in the next step. For more information on the jar tool, see jar (for Solaris, Linux, or macOS) (for Microsoft Windows).

    jar cvf <JAR file name> <list of classes, separated by spaces>

This command creates a JAR file with the specified name containing the specified classes.

Step 6: Sign your JAR File

If your provider is supplying encryption algorithms through the Cipher KeyAgreement, KeyGenerator, Mac, or SecretKeyFactory classes, you will need to sign your JAR file so that the JCA can authenticate the code at runtime. For details, see Step 1a. If you are NOT providing an implementation of this type you can skip this step.

Step 6.1: Get a Code-Signing Certificate

The next step is to request a code-signing certificate so that you can use it to sign your provider prior to testing. The certificate will be good for both testing and production. It will be valid for 5 years.

Below are the steps you should use to get a code-signing certificate. For more information on the keytool command, see keytool (for Solaris, Linux, or macOS) (for Microsoft Windows).

  1. Use keytool to generate a 2048-bit RSA keypair:

        keytool -genkeypair -alias <alias> \
            -keyalg RSA -keysize 2048 \
            -dname "cn=<Company Name>, \
                ou=Java Software Code Signing, \
                o=Oracle Corporation" \
            -keystore <keystore file name> \
            -storepass <keystore password>

    This generates a 2048-bit RSA key pair (a public key and an associated private key) and stores it in an entry in the specified keystore. The public key is stored in a self-signed certificate. The keystore entry can subsequently be accessed using the specified alias.


    Note: It's recommended that you create a keypair that uses RSA or DSA with 2048 or more bits.


    The option values in angle brackets (< and >) represent the actual values that must be supplied. For example, <alias> must be replaced with whatever alias name you wish to be used to refer to the newly-generated keystore entry in the future, and <keystore file name> must be replaced with the name of the keystore to be used.


    Note:


  2. Use keytool to generate a Certificate Signing Request (CSR):

        keytool -certreq -alias <alias> \
            -file <csr file name> \
            -keystore <keystore file name> \
            -storepass <keystore password>

    Here, <alias> is the alias for the RSA keypair entry created in the previous step. This command generates a Certificate Signing Request (CSR), using the PKCS#10 format. It stores the CSR in the file whose name is specified in <csr file name>.

  3. Request a JCE code signing certificate by sending your CSR, your contact information, and other required documentation to the JCA Code Signing Certification Authority. See Obtain a JCE Code Signing Certificate for more information.

  4. Once the JCE Code Signing Certification Authority receives your request, they will validate it and perform a background check. If this check passes, then they will create and sign a JCE code-signing certificate valid for 5 years. You will receive an email message containing two text certificates: the code-signing certificate and the JCE CA certificate, which authenticates the code-signing certificate's public key.

  5. Import the certificates you received from the JCA Code Signing Certification Authority into your keystore with the keytool command.

    First import the CA's certificate as a "trusted certificate":

        keytool -import -alias <alias for the CA cert> \
            -file <CA cert file name> \
            -keystore <keystore file name> \
            -storepass <keystore password>

    Then import the code-signing certificate:

        keytool -import -alias <alias> \
            -file <code-signing cert file name> \
            -keystore <keystore file name> \
            -storepass <keystore password>

    Here, <alias> is the same alias as that which you created in step 1 where you generated a RSA keypair. This command replaces the self-signed certificate in the keystore entry specified by <alias> with the one signed by the JCA Code Signing Certification Authority.

Now that you have in your keystore a certificate from an entity trusted by JCA (the JCA Code Signing Certification Authority), you can place your provider code in a JAR file (Step 5) and then use that certificate to sign the JAR file (Step 6.2).

Step 6.2: Sign Your Provider

Sign the JAR file created in step five with the code-signing certificate obtained in Step 6. For more information on the jarsigner tool, see jarsigner (for Solaris, Linux, or macOS) (for Microsoft Windows).

    jarsigner -keystore <keystore file name> \
        -storepass <keystore password> \
        <JAR file name> <alias>

Here, <alias> is the alias into the keystore for the entry containing the code-signing certificate received from the JCA Code Signing Certification Authority (the same alias as that specified in the commands in Step 6.1).

You can test verification of the signature via the following:

    jarsigner -verify <JAR file name> 

The text "jar verified" will be displayed if the verification was successful.


Note: If you bundle a signed JCE provider as part of an RIA (applet or webstart application), for the best user experience, you should apply a second signature to the JCE provider JAR with the same certificate/key that you used to sign the applet or webstart application. See the Java Platform, Standard Edition Deployment Guide for more information on deploying RIAs, and the jarsigner (Solaris, Linux, or macOS or Windows) man page for information on applying multiple signatures to a JAR file.


Step 7: Prepare for Testing

The next steps describe how to install and configure your new provider so that it is available via the JCA.

Step 7.1: Install the Provider

In order to prepare for testing your provider, you must install it in the same manner as will be done by clients wishing to use it. The installation enables Java Security to find your algorithm implementations when clients request them.

Installing a provider is done in two steps: installing the provider package classes, and configuring the provider.

Installing the Provider Classes

The first thing you must do is make your classes available so that they can be found when requested. You ship your provider classes as a JAR (Java ARchive) file.

There are a two possible ways to install provider classes:

The provider JAR file will be considered an installed extension if it is placed in the standard place for the JAR files of an installed extension:

Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the Java Runtime Environment (JRE) or the jre directory in the Java SE (JDK) software. For example, if you have the JDK installed on Solaris, Linux, or macOS in a directory named /home/user1/jdk, or on Microsoft Windows in a directory named C:\jdk, then you need to install the JAR file in the following directory:

Similarly, if you have the JRE installed on Solaris, Linux, or macOS in a directory named /home/user1/jre, or on Microsoft Windows in a directory named C:\jre, you need to install the JAR file in the following directory:

For more information on installed extensions, see Installed Extensions.

Configuring the Provider

The next step is to add the provider to your list of approved providers. This is done statically by editing the security properties file

Here <java-home> refers to the directory where the JRE was installed. For example, if you have the JDK installed on Solaris, Linux, or macOS in a directory named /home/user1/jdk, or on Microsoft Windows in a directory named C:\jdk, then you need to edit the following file:

Similarly, if you have the JRE installed on Solaris, Linux, or macOS in a directory named /home/user1/jre, or on Windows in a directory named C:\jre, then you need to edit this file:

For each provider, this file should have a statement of the following form:

    security.provider.n=masterClassName 

This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms when no specific provider is requested. The order is 1-based; 1 is the most preferred, followed by 2, and so on.

masterClassName must specify the fully qualified name of the provider's "master class", which you implemented in Step 3. This class is always a subclass of the Provider class.

Java comes standard with providers named SUN, SunRsaSign, and SunJCE which are automatically configured as a static provider in the java.security properties file, as follows:

    security.provider.2=sun.security.provider.Sun
    security.provider.3=sun.security.rsa.SunRsaSign
    security.provider.4=sun.security.provider.SunJCE

(The SUN provider's master class is the Sun class in the sun.security.provider package.)

The JCA provider SunJCE and other security-related providers shipped with the Java platform are also automatically configured as static providers.

To utilize another JCA provider, add a line registering the alternate provider, giving it a lower preference order than the SUN and SunRsaSign providers.

Suppose that your master class is the CryptoX class in the com.cryptox.provider package, and that you would like to make your provider the fourth preferred provider. To do so, edit the java.security file as seen below:

    security.provider.2=sun.security.provider.Sun
    security.provider.3=sun.security.rsa.SunRsaSign
    security.provider.4=com.cryptox.provider.CryptoX
    security.provider.5=sun.security.provider.SunJCE

Note: Providers may also be registered dynamically. To do so, a program (such as your test program, to be written in Step 8) can call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent and can only be done by code which is granted the following permission:

    java.security.SecurityPermission "insertProvider.{name}"

where {name} is replaced by the actual provider name.

For example, if the provider name is "MyJCE" and if the provider's code is in the myjce_provider.jar file in the /localWork directory, then here is a sample policy file grant statement granting that permission:

    grant codeBase "file:/localWork/myjce_provider.jar" {
        permission java.security.SecurityPermission
            "insertProvider.MyJCE";
    };

Step 7.2: Set Provider Permissions

Whenever providers are not installed extensions, permissions must be granted for when applets or applications are run while a security manager is installed. There is typically a security manager installed whenever an applet is running, and a security manager may be installed for an application either via code in the application itself or via a command-line argument. Permissions do not need to be granted to installed extensions, since the default system policy file grants all permissions to installed extensions.

Whenever a client does not install your provider as an installed extension, your provider may need the following permissions granted to it in the client environment:

To ensure your provider works when a security manager is installed and the provider is not an installed extension, you need to test such an installation and execution environment. In addition, prior to testing you need to grant appropriate permissions to your provider and to any other providers it uses. For example, a sample statement granting permissions to a provider whose name is "MyJCE" and whose code is in myjce_provider.jar appears below. Such a statement could appear in a policy file. In this example, the myjce_provider.jar file is assumed to be in the /localWork directory.

    grant codeBase "file:/localWork/myjce_provider.jar" {
        permission java.lang.RuntimePermission "getProtectionDomain";
        permission java.security.SecurityPermission
            "putProviderProperty.MyJCE";
    };

Step 8: Write and Compile your Test Programs

Write and compile one or more test programs that test your provider's incorporation into the Security API as well as the correctness of its algorithm(s). Create any supporting files needed, such as those for test data to be encrypted.

The first tests your program should perform are ones to ensure that your provider is found, and that its name, version number, and additional information is as expected. To do so, you could write code like the following, substituting your provider name for MyPro:

    import java.security.*;

    Provider p = Security.getProvider("MyPro");

    System.out.println("MyPro provider name is " + p.getName());
    System.out.println("MyPro provider version # is " + p.getVersion());
    System.out.println("MyPro provider info is " + p.getInfo());

Next, you should ensure that your services are found. For instance, if you implemented the AES encryption algorithm, you could check to ensure it's found when requested by using the following code (again substituting your provider name for "MyPro"):

    Cipher c = Cipher.getInstance("AES", "MyPro");

    System.out.println("My Cipher algorithm name is " + c.getAlgorithm());

If you don't specify a provider name in the call to getInstance, all registered providers will be searched, in preference order (see Configuring the Provider), until one implementing the algorithm is found.

If your provider implements an exemption mechanism, you should write a test applet or application that uses the exemption mechanism. Such an applet/application also needs to be signed, and needs to have a "permission policy file" bundled with it. See How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide for complete information on creating and testing such an application.

Step 9: Run your Test Programs

Run your test program(s). Debug your code and continue testing as needed. If the Java Security API cannot seem to find one of your algorithms, review the steps above and ensure they are all completed.

Be sure to include testing of your programs using different installation options (e.g. making the provider an installed extension or placing it on the class path) and execution environments (with or without a security manager running). Installation options are discussed in Step 7.1. In particular, you need to ensure your provider works when a security manager is installed and the provider is not an installed extension -- and thus the provider must have permissions granted to it; therefore, you need to test such an installation and execution environment, after granting required permissions to your provider and to any other providers it uses, as described in Step 7.2.

If you find during testing that your code needs modification, make the changes, recompile (Step 4), place the updated provider code in a JAR file (Step 6), sign the JAR file if necessary (Step 6.2), re-install the provider (Step 7.1), if needed fix or add to the permissions (Step 7.2), and then re-test your programs. Repeat these steps as needed.

Step 10: Apply for U.S. Government Export Approval If Required

All U.S. vendors whose providers may be exported outside the U.S. should apply to the Bureau of Industry and Security in the U.S. Department of Commerce for export approval. Please consult your export counsel for more information.

Note: If your provider calls Cipher.getInstance() and the returned Cipher object needs to perform strong cryptography regardless of what cryptographic strength is allowed by the user's downloaded jurisdiction policy files, you should include a copy of the cryptoPerms permission policy file which you intend to bundle in the JAR file for your provider and which specifies an appropriate permission for the required cryptographic strength. The necessity for this file is just like the requirement that applets and applications "exempt" from cryptographic restrictions must include a cryptoPerms permission policy file in their JAR file. For more information on the creation and inclusion of such a file, see How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide.

Here are two URLs that may be useful:

Step 11: Document your Provider and its Supported Services

The next step is to write documentation for your clients. At the minimum, you need to specify:

In addition, your documentation should specify anything else of interest to clients, such as any default algorithm parameters.

Message Digests and MACs

For each Message Digest and MAC algorithm, indicate whether or not your implementation is cloneable. This is not technically necessary, but it may save clients some time and coding by telling them whether or not intermediate Message Digests or MACs may be possible through cloning. Clients who do not know whether or not a MessageDigest or Mac implementation is cloneable can find out by attempting to clone the object and catching the potential exception, as illustrated by the following example:

    try {
        // try and clone it
        /* compute the MAC for i1 */
        mac.update(i1);
        byte[] i1Mac = mac.clone().doFinal();

        /* compute the MAC for i1 and i2 */
        mac.update(i2);
        byte[] i12Mac = mac.clone().doFinal();

        /* compute the MAC for i1, i2 and i3 */
        mac.update(i3);
        byte[] i123Mac = mac.doFinal();
    } catch (CloneNotSupportedException cnse) {
        // have to use an approach not involving cloning
    } 

where:

Key Pair Generators

For a key pair generator algorithm, in case the client does not explicitly initialize the key pair generator (via a call to an initialize method), each provider must supply and document a default initialization. For example, the Diffie-Hellman key pair generator supplied by the SunJCE provider uses a default prime modulus size (keysize) of 2048 bits.

Key Factories

A provider should document all the key specifications supported by its (secret-)key factory.

Algorithm Parameter Generators

In case the client does not explicitly initialize the algorithm parameter generator (via a call to an init method in the AlgorithmParameterGenerator engine class), each provider must supply and document a default initialization. For example, the SunJCE provider uses a default prime modulus size (keysize) of 2048 bits for the generation of Diffie-Hellman parameters, and the SUN provider uses a default modulus prime size of 2048 bits for the generation of DSA parameters.

Signature Algorithms

If you implement a signature algorithm, you should document the format in which the signature (generated by one of the sign methods) is encoded. For example, the SHA256withDSA signature algorithm supplied by the SUN provider encodes the signature as a standard ASN.1 SEQUENCE of two integers, r and s.

Random Number Generation (SecureRandom) Algorithms

For a random number generation algorithm, provide information regarding how "random" the numbers generated are, and the quality of the seed when the random number generator is self-seeding. Also note what happens when a SecureRandom object (and its encapsulated SecureRandomSpi implementation object) is deserialized: If subsequent calls to the nextBytes method (which invokes the engineNextBytes method of the encapsulated SecureRandomSpi object) of the restored object yield the exact same (random) bytes as the original object would, then let users know that if this behaviour is undesirable, they should seed the restored random object by calling its setSeed method.

Certificate Factories

A provider should document what types of certificates (and their version numbers, if relevant), can be created by the factory.

Keystores

A provider should document any relevant information regarding the keystore implementation, such as its underlying data format.

Step 12: Make your Class Files and Documentation Available to Clients

After writing, configuring, testing, installing and documenting your provider software, make documentation available to your customers.

How a Provider Can Do Self-Integrity Checking

Each provider should do self-integrity checking to ensure that the JAR file containing its code has not been tampered with, for example in an attempt to invoke provider methods directly rather than through JCA. Providers that provide implementations for encryption services (Cipher, KeyAgreement, KeyGenerator, MAC or SecretKey factory) must be digitally signed and should be signed with a certificate issued by "trusted" Certification Authorities. Currently, the following two Certification Authorities are considered "trusted":

Please refer to Step 6.2 for detailed information on how to get a code-signing certificate from Sun Microsystems' JCA Code Signing CA and the certificate of that CA.

After getting the signing certificate from above Certification Authority, provider packages should embed within themselves the bytes for its own signing certificate, for example in an array like the bytesOfProviderCert array referred to in the Identifying Each of the Signers and Determining If One is Trusted section below. At runtime, the embedded certificate will be used in determining whether or not the provider code is authentic.

The basic approach a provider can use to check its own integrity is:

  1. Determine the URL of the JAR file containing the provider code, and
  2. Verify the JAR file's digital signatures to ensure that at least one signer of each entry of the JAR file is trusted.

Each of these steps is described in the following sections:

Notes on the Sample Code

Note: The sample code MyJCE.java is a complete code example that implements these steps. You can download this code for your reference. The Notes on the Sample Code section traces how these concepts are implemented in the sample code.


IMPORTANT NOTE: In the unbundled version of JCE 1.2.x, (used with JDKs 1.2.x and 1.3.x), providers needed to include code to authenticate the JCA framework to assure themselves of the integrity and authenticity of the JCA that they plugged into. In JDK 6 and later, this is no longer necessary.

One implication is that a provider written just for JCE 1.2.2 will not work in JDK 6 because the provider's JCE framework authentication check will not work; the JCE framework code is no longer where the provider expects it to be. If you want your provider to work only with JDK 6, it should not have code to authenticate the JCE framework. On the other hand, if you want your provider to work both with JCE 1.2.2 and with JDK 6, then add a conditional statement. This way the provider code to authenticate the JCE framework is executed only when the provider is run with JCE 1.2.2. The following is sample code:

    Class cipherCls = Class.forName("javax.crypto.Cipher");

    CodeSource cs = cipherCls.getProtectionDomain().getCodeSource();
    if (cs != null) {
        // Authenticate JCE framework
. . . }

Finding the Provider JAR File: Basics

Determining the Provider's JAR File URL

The URL for the provider's JAR file can be obtained by determining the provider's CodeSource and then calling the getLocation method on the CodeSource.

    URL providerURL = (URL) AccessController.doPrivileged(
        new PrivilegedAction) {
            public Object run() {
                CodeSource cs =
                    MyJCE.class.getProtectionDomain().getCodeSource();
                return cs.getLocation();
            }
        }); 

Creating a JarFile Referring to the JAR File

Once you have the URL for the provider's JAR file, you can create a java.util.jar.JarFile referring to the JAR file. This instance is needed in the step for verifying the Provider JAR file.

To create the JAR file, first open a connection to the specified URL by calling its openConnection method. Since the URL is a JAR URL, the type is java.net.JarURLConnection. Here's the basic code:

    // Prep the url with the appropriate protocol.
    jarURL =
        url.getProtocol().equalsIgnoreCase("jar") ? url :
            new URL("jar:" + url.toString() + "!/");

    // Retrieve the jar file using JarURLConnection
    JarFile jf = (JarFile) AccessController.doPrivileged(
        new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                JarURLConnection conn =
                    (JarURLConnection) jarURL.openConnection();
        ...  

Now that you have a JarURLConnection, you can call its getJarFile method to get the JAR file:

    // Always get a fresh copy, so we don't have to
    // worry about the stale file handle when the
    // cached jar is closed by some other application.
    conn.setUseCaches(false);
    jf = conn.getJarFile(); 

Verifying the Provider JAR File: Basics

Once you have determined the URL for your provider JAR file and you have created a JarFile referring to the JAR file, as shown in the steps above, you can then verify the file.

The basic approach is:

  1. Ensure that at least one of each entry's signer's certificates is equal to the provider's own code signing certificate.
  2. Go through all the entries in the JAR file and ensure the signature on each one verifies correctly.
  3. Ensure that at least one of each entry's signer's certificates can be traced back to a trusted Certification Authority.

Sample code for each of these steps is presented and described in the following sections:

Verification Setup

Our approach is to define a class JarVerifier to handle the retrieval of a JAR file from a given URL and verify whether the JAR file is signed with the specified certificate.

The constructor of JarVerifier takes the provider URL as a parameter which will be used to retrieve the JAR file later.

The actual jar verification is implemented in the verify method which takes the provider code signing certificate as a parameter.

    public void verify(X509Certificate targetCert) throws IOException {
        // variable 'jarFile' is a JarFile object created
        // from the provider's Jar URL.
        ...
        Vector entriesVec = new Vector(); 

Basically the verify method will go through the JAR file entries twice: the first time checking the signature on each entry and the second time verifying the signer is trusted.

Note: In our code snippets the jarFile variable is the JarFile object of the provider's jar file.

JAR File Signature Check

An authentic provider JAR file is signed. So the JAR file has been tampered with if it isn't signed:

    // Ensure the jar file is signed.
    Manifest man = jarFile.getManifest();
    if (man == null) {
        throw new SecurityException("The provider is not signed");
    } 

Verifying Signatures

The next step is to go through all the entries in the JAR file and ensure the signature on each one verifies correctly. One possible way to verify the signature on a JAR file entry is to simply read the file. If a JAR file is signed, the read method itself automatically performs the signature verification. Here is sample code:

    // Ensure all the entries' signatures verify correctly
    byte[] buffer = new byte[8192];
    Enumeration entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry je = (JarEntry) entries.nextElement();

        // Skip directories.
        if (je.isDirectory())
            continue;

        entriesVec.addElement(je);
        InputStream is = jarFile.getInputStream(je);

        // Read in each jar entry. A security exception will
        // be thrown if a signature/digest check fails.
        int n;
        while ((n = is.read(buffer, 0, buffer.length)) != -1) {
            // Don't care
        }
        is.close();
    }
    

Ensuring Signers Are Trusted

The code in the previous section verified the signatures of all the provider JAR file entries. The fact that they all verify correctly is a requirement, but it is not sufficient to verify the authenticity of the JAR file. A final requirement is that the signatures were generated by the same entity as the one that developed this provider. To test that the signatures are trusted, we can again go through each entry in the JAR file (this time using the entriesVec built in the previous step), and for each entry that must be signed (that is, each entry that is not a directory and that is not in the META-INF directory):

  1. Get the list of signer certificates for the entry.
  2. Identify each of the certificate chains and determine whether any of the certificate chains are trusted. At least one of the certificate chains must be trusted.

The loop setup is the following:

    Enumeration e = entriesVec.elements();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        ...
    } 

Getting the List of Certificates

The certificates for the signers of a JAR file entry JarEntry can be obtained simply by calling the JarEntry getCertificates method:

    Certificate[] certs = je.getCertificates();

Adding this line of code to the previous loop setup code, and adding code to ignore directories and files in the META-INF directory gives us:

    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();

        // Every file must be signed except files in META-INF.
        Certificate[] certs = je.getCertificates();
        if ((certs == null) || (certs.length == 0)) {
            if (!je.getName().startsWith("META-INF"))
                throw new SecurityException(
                    "The provider has unsigned class files.");
            } else {
                // Check whether the file is signed by the expected
                // signer. The jar may be signed by multiple signers.
                // See if one of the signers is 'targetCert'.
                ...
            }
        ...  

Identifying Each of the Signers and Determining If One is Trusted

The certificate array returned by the JarEntry getCertificates method contains one or more certificate chains. There is one chain per signer of the entry. Each chain contains one or more certificates. Each certificate in a chain authenticates the public key in the previous certificate.

The first certificate in a chain is the signer's certificate which contains the public key corresponding to the private key actually used to sign the entry. Each subsequent certificate is a certificate for the issuer of the previous certificate. Since the self-integrity check is based on whether the JAR file is signed with the provider's signing cert, the trust decision will be made upon only the first certificate, the signer's certificate.

We need to go through the array of certificate chains and check each chain and the associated signers until we find a trusted entity. For each JAR file entry, at least one of the signers must be trusted. A signer is considered "trusted" if and only if its certificate is equals to the embedded provider signing certificate.

The following sample code loops through all the certificate chains, compares the first certificate in a chain to the embedded provider signing certificate, and only returns true if a match is found.

    int startIndex = 0;
    X509Certificate[] certChain;
    boolean signedAsExpected = false;

    while ((certChain = getAChain(certs, startIndex)) != null) {
        if (certChain[0].equals(targetCert)) {
            // Stop since one trusted signer is found.
            signedAsExpected = true;
            break;
        }

        // Proceed to the next chain.
        startIndex += certChain.length;
    }

    if (!signedAsExpected) {
        throw new SecurityException(
            "The provider is not signed by a trusted signer");
    }
    

The getAChain method is defined as follows:

    /**
     * Extracts ONE certificate chain from the specified certificate array
     * which may contain multiple certificate chains, starting from index
     * 'startIndex'.
     */
    private static X509Certificate[] getAChain(
            Certificate[] certs, int startIndex) {

        if (startIndex > certs.length - 1)
            return null;

        int i;
        // Keep going until the next certificate is not the
        // issuer of this certificate.
        for (i = startIndex; i < certs.length - 1; i++) {
            if (!((X509Certificate)certs[i + 1]).getSubjectDN().
                    equals(((X509Certificate)certs[i]).getIssuerDN())) {
                break;
            }
        }

        // Construct and return the found certificate chain.
        int certChainSize = (i-startIndex) + 1;
        X509Certificate[] ret = new X509Certificate[certChainSize];
        for (int j = 0; j < certChainSize; j++ ) {
            ret[j] = (X509Certificate) certs[startIndex + j];
        }
        return ret;
    }
    

Notes on the myJCE Code Sample

The sample code, MyJCE.java, is a sample provider which has a method selfIntegrityChecking which performs self-integrity checking. It first determines the URL of its own provider JAR file and then verifies that the provider JAR file is signed with the embedded code-signing certificate.

Note: The method selfIntegrityChecking should be called by all the constructors of its cryptographic engine classes to ensure that its integrity is not compromised.

Provider MyJCE performs self-integrity checking in the following steps:

  1. Determine the URL to access the provider JAR file using its own class, MyJCE.class.
  2. Instantiate a JarVerifier object with the provider URL in Step 1.
  3. Create a X509Certificate object from the embedded byte array bytesOfProviderCert.
  4. Call the JarVerifier.verify method to verify all entries in the provider JAR file are signed and are signed with the same certificate instantiated in Step 3.

Note: The class JarVerifier will retrieve the JAR file from the given URL, make sure the JAR file is signed, all entries have valid signatures, and that entries are signed with the specified X509Certificate.

A security exception is thrown by JarVerifier.verify in several cases:

The MyJCE.java sample code is comprised of the code snippets shown above. In addition, it includes error handling, sample code signing certificate bytes, and code for instantiating a X509Certificate object from the embedded sample code signing certificate bytes.

Regarding the use of AccessController.doPrivileged, please see API For Privileged Blocks for information on the use of doPrivileged.

Further Implementation Details and Requirements

Alias Names

For many cryptographic algorithms and types, there is a single official "standard name" defined in Appendix A of the Java Cryptography Architecture Reference Guide.

For example, "MD5" is the standard name for the RSA-MD5 Message Digest algorithm defined by RSA DSI in RFC 1321. DiffieHellman is the standard for the Diffie-Hellman key agreement algorithm defined in PKCS3.

In the JDK, there is an aliasing scheme that enables clients to use aliases when referring to algorithms or types, rather than their standard names. For example, the SUN provider's master class (Sun.java) defines the alias "SHA1/DSA" for the algorithm whose standard name is "SHA1withDSA". Thus, the following statements are equivalent:

    Signature sig = Signature.getInstance("SHA1withDSA", "SUN");

    Signature sig = Signature.getInstance("SHA1/DSA", "SUN");

Aliases can be defined in your "master class" (see Step 3). To define an alias, create a property named

    Alg.Alias.engineClassName.aliasName

where engineClassName is the name of an engine class (e.g., Signature), and aliasName is your alias name. The value of the property must be the standard algorithm (or type) name for the algorithm (or type) being aliased.

As an example, the SUN provider defines the alias "SHA1/DSA" for the signature algorithm whose standard name is "SHA1withDSA" by setting a property named Alg.Alias.Signature.SHA1/DSA to have the value SHA1withDSA via the following:

    put("Alg.Alias.Signature.SHA1/DSA", "SHA1withDSA");

Note that aliases defined by one provider are available only to that provider and not to any other providers. Thus, aliases defined by the SunJCE provider are available only to the SunJCE provider.

Service Interdependencies

Some algorithms require the use of other types of algorithms. For example, a PBE algorithm usually needs to use a message digest algorithm in order to transform a password into a key.

If you are implementing one type of algorithm that requires another, you can do one of the following:

  1. Provide your own implementations for both.
  2. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by the default SUN provider that is included with every Java SE Platform installation. For example, if you are implementing a PBE algorithm that requires a message digest algorithm, you can obtain an instance of a class implementing the SHA256 message digest algorithm by calling
        MessageDigest.getInstance("SHA256", "SUN")
  3. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by another specific provider. This is only appropriate if you are sure that all clients who will use your provider will also have the other provider installed.
  4. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by another (unspecified) provider. That is, you can request an algorithm by name, but without specifying any particular provider, as in
        MessageDigest.getInstance("SHA256")
    This is only appropriate if you are sure that there will be at least one implementation of the requested algorithm (in this case, SHA256) installed on each Java platform where your provider will be used.

Here are some common types of algorithm interdependencies:

Signature and Message Digest Algorithms

A signature algorithm often requires use of a message digest algorithm. For example, the SHA256withDSA signature algorithm requires the SHA256 message digest algorithm.

Signature and (Pseudo-)Random Number Generation Algorithms

A signature algorithm often requires use of a (pseudo-)random number generation algorithm. For example, such an algorithm is required in order to generate a DSA signature.

Key Pair Generation and Message Digest Algorithms

A key pair generation algorithm often requires use of a message digest algorithm. For example, DSA keys are generated using the SHA-256 message digest algorithm.

Algorithm Parameter Generation and Message Digest Algorithms

An algorithm parameter generator often requires use of a message digest algorithm. For example, DSA parameters are generated using the SHA-256 message digest algorithm.

KeyStores and Message Digest Algorithms

A keystore implementation will often utilize a message digest algorithm to compute keyed hashes (where the key is a user-provided password) to check the integrity of a keystore and make sure that the keystore has not been tampered with.

Key Pair Generation Algorithms and Algorithm Parameter Generators

A key pair generation algorithm sometimes needs to generate a new set of algorithm parameters. It can either generate the parameters directly, or use an algorithm parameter generator.

Key Pair Generation, Algorithm Parameter Generation, and (Pseudo-)Random Number Generation Algorithms

A key pair generation algorithm may require a source of randomness in order to generate a new key pair and possibly a new set of parameters associated with the keys. That source of randomness is represented by a SecureRandom object. The implementation of the key pair generation algorithm may generate the key parameters itself, or may use an algorithm parameter generator to generate them, in which case it may or may not initialize the algorithm parameter generator with a source of randomness.

Algorithm Parameter Generators and Algorithm Parameters

An algorithm parameter generator's engineGenerateParameters method must return an AlgorithmParameters instance.

Signature and Key Pair Generation Algorithms or Key Factories

If you are implementing a signature algorithm, your implementation's engineInitSign and engineInitVerify methods will require passed-in keys that are valid for the underlying algorithm (e.g., DSA keys for the DSS algorithm). You can do one of the following:

  1. Also create your own classes implementing appropriate interfaces (e.g. classes implementing the DSAPrivateKey and DSAPublicKey interfaces from the package java.security.interfaces), and create your own key pair generator and/or key factory returning keys of those types. Require the keys passed to engineInitSign and engineInitVerify to be the types of keys you have implemented, that is, keys generated from your key pair generator or key factory. Or you can,
  2. Accept keys from other key pair generators or other key factories, as long as they are instances of appropriate interfaces that enable your signature implementation to obtain the information it needs (such as the private and public keys and the key parameters). For example, the engineInitSign method for a DSS Signature class could accept any private keys that are instances of java.security.interfaces.DSAPrivateKey.

KeyStores and Key and Certificate Factories

A keystore implementation will often utilize a key factory to parse the keys stored in the keystore, and a certificate factory to parse the certificates stored in the keystore.

Default Initializations

In case the client does not explicitly initialize a key pair generator or an algorithm parameter generator, each provider of such a service must supply (and document) a default initialization. For example, the SUN provider uses a default key size of 2048 bits for the generation of DSA key pairs and parameters. See Java Cryptography Architecture Oracle Providers Documentation for JDK 8 for information about default key sizes for other providers.

Default Key Pair Generator Parameter Requirements

If you implement a key pair generator, your implementation should supply default parameters that are used when clients don't specify parameters. The documentation you supply (Step 11) should state what the default parameters are.

For example, the DSA key pair generator in the SUN provider supplies a set of precomputed p, q, and g default values for the generation of key pairs in all supported keysizes.

The following example obtains the p, q, and g values for the DSA key pair generator of the preferred provider (as specified in the java.security file) as well as the provider's name and the default keysize:

    static void printDSA() throws Exception {
        KeyPairGenerator kpgen = KeyPairGenerator.getInstance("DSA");
        Provider prov = kpgen.getProvider();
        System.out.println("Current provider: " + prov.getName());
        
        KeyPair kp = kpgen.genKeyPair();
        DSAPublicKey pubKey = (DSAPublicKey) kp.getPublic();

        DSAParams params = pubKey.getParams();
        BigInteger p = params.getP();
        BigInteger q = params.getQ();
        BigInteger g = params.getG();
        
        System.out.println("Bit length of p: " + p.bitLength());
        System.out.printf("p: %x\n", p);
        System.out.printf("q: %x\n", q);
        System.out.printf("g: %x\n", g);
    }

This example prints output similar to the following (line breaks and spaces have been added for clarity):

Current provider: SUN
Bit length of p: 2048
p: 8f7935d9 b9aae9bf abed887a cf4951b6 f32ec59e 3baf3718 e8eac496 1f3efd36
   06e74351 a9c41833 39b809e7 c2ae1c53 9ba7475b 85d011ad b8b47987 75498469
   5cac0e8f 14b33608 28a22ffa 27110a3d 62a99345 3409a0fe 696c4658 f84bdd20
   819c3709 a01057b1 95adcd00 233dba54 84b6291f 9d648ef8 83448677 979cec04
   b434a6ac 2e75e998 5de23db0 292fc111 8c9ffa9d 8181e733 8db792b7 30d7b9e3
   49592f68 09987215 3915ea3d 6b8b4653 c633458f 803b32a4 c2e0f272 90256e4e
   3f8a3b08 38a1c450 e4e18c1a 29a37ddf 5ea143de 4b66ff04 903ed5cf 1623e158
   d487c608 e97f211c d81dca23 cb6e3807 65f822e3 42be484c 05763939 601cd667
q: baf696a6 8578f7df dee7fa67 c977c785 ef32b233 bae580c0 bcd5695d
g: 16a65c58 20485070 4e7502a3 9757040d 34da3a34 78c154d4 e4a5c02d 242ee04f
   96e61e4b d0904abd ac8f37ee b1e09f31 82d23c90 43cb642f 88004160 edf9ca09
   b32076a7 9c32a627 f2473e91 879ba2c4 e744bd20 81544cb5 5b802c36 8d1fa83e
   d489e94e 0fa0688e 32428a5c 78c478c6 8d0527b7 1c9a3abb 0b0be12c 44689639
   e7d3ce74 db101a65 aa2b87f6 4c6826db 3ec72f4b 5599834b b4edb02f 7c90e9a4
   96d3a55d 535bebfc 45d4f619 f63f3ded bb873925 c2f224e0 7731296d a887ec1e
   4748f87e fb5fdeb7 5484316b 2232dee5 53ddaf02 112b0d1f 02da3097 3224fe27
   aeda8b9d 4b2922d9 ba8be39e d9e103a6 3c52810b c688b7e2 ed4316e1 ef17dbde

The Provider.Service Class

Since its introduction, security providers have published their service information via appropriately formatted key-value String pairs they put in their Hashtable entries. While this mechanism is simple and convenient, it limits the amount customization possible. As a result, JDK 5.0 introduced a second option, the Provider.Service class. It offers an alternative way for providers to advertise their services and supports additional features as described below. Note that this addition is fully compatible with the older method of using String valued Hashtable entries. A provider on JDK 5.0 can choose either method as it prefers, or even use both at the same time.

A Provider.Service object encapsulates all information about a service. This is the provider that offers the service, its type (e.g. MessageDigest or Signature), the algorithm name, and the name of the class that implements the service. Optionally, it also includes a list of alternate algorithm names for this service (aliases) and attributes, which are a map of (name, value) String pairs. In addition, it defines the methods newInstance() and supportsParameter(). They have default implementations, but can be overridden by providers if needed, as may be the case with providers that interface with hardware security tokens.

The newInstance() method is used by the security framework when it needs to construct new implementation instances. The default implementation uses reflection to invoke the standard constructor for the respective type of service. For all standard services except CertStore, this is the no-args constructor. The constructorParameter to newInstance() must be null in theses cases. For services of type CertStore, the constructor that takes a CertStoreParameters object is invoked, and constructorParameter must be a non-null instance of CertStoreParameters. A security provider can override the newInstance() method to implement instantiation as appropriate for that implementation. It could use direct invocation or call a constructor that passes additional information specific to the Provider instance or token. For example, if multiple Smartcard readers are present on the system, it might pass information about which reader the newly created service is to be associated with. However, despite customization all implementations must follow the conventions about constructorParameter described above.

The supportsParameter() tests whether the Service can use the specified parameter. It returns false if this service cannot use the parameter. It returns true if this service can use the parameter, if a fast test is infeasible, or if the status is unknown. It is used by the security framework with some types of services to quickly exclude non-matching implementations from consideration. It is currently only defined for the following standard services: Signature, Cipher, Mac, and KeyAgreement. The parameter must be an instance of Key in these cases. For example, for Signature services, the framework tests whether the service can use the supplied Key before instantiating the service. The default implementation examines the attributes SupportedKeyFormats and SupportedKeyClasses as described below. Again, a provider may override this methods to implement additional tests.

The SupportedKeyFormats attribute is a list of the supported formats for encoded keys (as returned by key.getFormat()) separated by the "|" (pipe) character. For example, X.509|PKCS#8. The SupportedKeyClasses attribute is a list of the names of classes of interfaces separated by the "|" character. A key object is considered to be acceptable if it is assignable to at least one of those classes or interfaces named. In other words, if the class of the key object is a subclass of one of the listed classes (or the class itself) or if it implements the listed interface. An example value is "java.security.interfaces.RSAPrivateKey|java.security.interfaces.RSAPublicKey" .

Four methods have been added to the Provider class for adding and looking up Services. As mentioned earlier, the implementation of those methods and also of the existing Properties methods have been specifically designed to ensure compatibility with existing Provider subclasses. This is achieved as follows:

If legacy Properties methods are used to add entries, the Provider class makes sure that the property strings are parsed into equivalent Service objects prior to lookup via getService(). Similarly, if the putService() method is used, equivalent property strings are placed into the provider's hashtable at the same time. If a provider implementation overrides any of the methods in the Provider class, it has to ensure that its implementation does not interfere with this conversion. To avoid problems, we recommend that implementations do not override any of the methods in the Provider class.

Signature Formats

If you implement a signature algorithm, the documentation you supply (Step 11) should specify the format in which the signature (generated by one of the sign methods) is encoded.

For example, the SHA256withDSA signature algorithm supplied by the SUN provider encodes the signature as a standard ASN.1 sequence of two ASN.1 INTEGER values: r and s, in that order:

SEQUENCE ::= {
        r INTEGER,
        s INTEGER }

DSA Interfaces and their Required Implementations

The Java Security API contains the following interfaces (in the java.security.interfaces package) for the convenience of programmers implementing DSA services:

The following sections discuss requirements for implementations of these interfaces.

DSAKeyPairGenerator

The interface DSAKeyPairGenerator is obsolete. It used to be needed to enable clients to provide DSA-specific parameters to be used rather than the default parameters your implementation supplies. However, in Java it is no longer necessary; a new KeyPairGenerator initialize method that takes an AlgorithmParameterSpec parameter enables clients to indicate algorithm-specific parameters.

DSAParams Implementation

If you are implementing a DSA key pair generator, you need a class implementing DSAParams for holding and returning the p, q, and g parameters.

A DSAParams implementation is also required if you implement the DSAPrivateKey and DSAPublicKey interfaces. DSAPublicKey and DSAPrivateKey both extend the DSAKey interface, which contains a getParams method that must return a DSAParams object. See DSAPrivateKey and DSAPublicKey Implementations for more information.

Note: there is a DSAParams implementation built into the JDK: the java.security.spec.DSAParameterSpec class.

DSAPrivateKey and DSAPublicKey Implementations

If you implement a DSA key pair generator or key factory, you need to create classes implementing the DSAPrivateKey and DSAPublicKey interfaces.

If you implement a DSA key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement a DSA key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your DSAPrivateKey implementation, and your engineGeneratePublic method will return an instance of your DSAPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of a DSAPrivateKey or DSAPublicKey implementation. The getParams method provided by the interface implementations is useful for obtaining and extracting the parameters from the keys and then using the parameters, for example as parameters to the DSAParameterSpec constructor called to create a parameter specification from parameter values that could be used to initialize a KeyPairGenerator object for DSA.

If you implement a DSA signature algorithm, your engineInitSign method (in your SignatureSpi subclass) will expect to be passed a DSAPrivateKey and your engineInitVerify method will expect to be passed a DSAPublicKey.

Please note: The DSAPublicKey and DSAPrivateKey interfaces define a very generic, provider-independent interface to DSA public and private keys, respectively. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of DSAPrivateKey or DSAPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the DSA signature algorithm engineInitSign and engineInitVerify methods (in your SignatureSpi subclass).

To see what methods need to be implemented by classes that implement the DSAPublicKey and DSAPrivateKey interfaces, first note the following interface signatures:

In the java.security.interfaces package:

   public interface DSAPrivateKey extends DSAKey,
                java.security.PrivateKey

   public interface DSAPublicKey extends DSAKey,
                java.security.PublicKey

   public interface DSAKey 

In the java.security package:

   public interface PrivateKey extends Key

   public interface PublicKey extends Key

   public interface Key extends java.io.Serializable 

In order to implement the DSAPrivateKey and DSAPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for private keys, you need to supply a class that implements

RSA Interfaces and their Required Implementations

The Java Security API contains the following interfaces (in the java.security.interfaces package) for the convenience of programmers implementing RSA services:

The following sections discuss requirements for implementations of these interfaces.

RSAPrivateKey, RSAPrivateCrtKey, and RSAPublicKey Implementations

If you implement an RSA key pair generator or key factory, you need to create classes implementing the RSAPrivateKey (and/or RSAPrivateCrtKey) and RSAPublicKey interfaces. (RSAPrivateCrtKey is the interface to an RSA private key, using the Chinese Remainder Theorem (CRT) representation.)

If you implement an RSA key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement an RSA key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your RSAPrivateKey (or RSAPrivateCrtKey) implementation, and your engineGeneratePublic method will return an instance of your RSAPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of an RSAPrivateKey, RSAPrivateCrtKey, or RSAPublicKey implementation.

If you implement an RSA signature algorithm, your engineInitSign method (in your SignatureSpi subclass) will expect to be passed either an RSAPrivateKey or an RSAPrivateCrtKey, and your engineInitVerify method will expect to be passed an RSAPublicKey.

Please note: The RSAPublicKey, RSAPrivateKey, and RSAPrivateCrtKey interfaces define a very generic, provider-independent interface to RSA public and private keys. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of RSAPrivateKey, RSAPrivateCrtKey, or RSAPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the RSA signature algorithm engineInitSign and engineInitVerify methods (in your SignatureSpi subclass).

To see what methods need to be implemented by classes that implement the RSAPublicKey, RSAPrivateKey, and RSAPrivateCrtKey interfaces, first note the following interface signatures:

In the java.security.interfaces package:

    public interface RSAPrivateKey extends java.security.PrivateKey

    public interface RSAPrivateCrtKey extends RSAPrivateKey

    public interface RSAPublicKey extends java.security.PublicKey

In the java.security package:

    public interface PrivateKey extends Key

    public interface PublicKey extends Key

    public interface Key extends java.io.Serializable

In order to implement the RSAPrivateKey, RSAPrivateCrtKey, and RSAPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for RSA private keys, you need to supply a class that implements:

Similarly, for RSA private keys using the Chinese Remainder Theorem (CRT) representation, you need to supply a class that implements:

For public RSA keys, you need to supply a class that implements:

JCA contains a number of AlgorithmParameterSpec implementations for the most frequently used cipher and key agreement algorithm parameters. If you are operating on algorithm parameters that should be for a different type of algorithm not provided by JCA, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

Diffie-Hellman Interfaces and their Required Implementations

JCA contains the following interfaces (in the javax.crypto.interfaces package) for the convenience of programmers implementing Diffie-Hellman services:

The following sections discuss requirements for implementations of these interfaces.

DHPrivateKey and DHPublicKey Implementations

If you implement a Diffie-Hellman key pair generator or key factory, you need to create classes implementing the DHPrivateKey and DHPublicKey interfaces.

If you implement a Diffie-Hellman key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement a Diffie-Hellman key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your DHPrivateKey implementation, and your engineGeneratePublic method will return an instance of your DHPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of a DHPrivateKey or DHPublicKey implementation. The getParams method provided by the interface implementations is useful for obtaining and extracting the parameters from the keys. You can then use the parameters, for example, as parameters to the DHParameterSpec constructor called to create a parameter specification from parameter values used to initialize a KeyPairGenerator object for Diffie-Hellman.

If you implement the Diffie-Hellman key agreement algorithm, your engineInit method (in your KeyAgreementSpi subclass) will expect to be passed a DHPrivateKey and your engineDoPhase method will expect to be passed a DHPublicKey.

Note: The DHPublicKey and DHPrivateKey interfaces define a very generic, provider-independent interface to Diffie-Hellman public and private keys, respectively. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of DHPrivateKey or DHPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the Diffie-Hellman algorithm engineInit and engineDoPhase methods (in your KeyAgreementSpi subclass).

To see what methods need to be implemented by classes that implement the DHPublicKey and DHPrivateKey interfaces, first note the following interface signatures:

In the javax.crypto.interfaces package:

    public interface DHPrivateKey extends DHKey, java.security.PrivateKey

    public interface DHPublicKey extends DHKey, java.security.PublicKey

    public interface DHKey 

In the java.security package:

    public interface PrivateKey extends Key

    public interface PublicKey extends Key

    public interface Key extends java.io.Serializable 

To implement the DHPrivateKey and DHPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for private keys, you need to supply a class that implements:

Similarly, for public Diffie-Hellman keys, you need to supply a class that implements:

Interfaces for Other Algorithm Types

As noted above, the Java Security API contains interfaces for the convenience of programmers implementing services like DSA, RSA and ECC. If there are services without API support, you need to define your own APIs.

If you are implementing a key pair generator for a different algorithm, you should create an interface with one or more initialize methods that clients can call when they want to provide algorithm-specific parameters to be used rather than the default parameters your implementation supplies. Your subclass of KeyPairGeneratorSpi should implement this interface.

For algorithms without direct API support, it is recommended that you create similar interfaces and provide implementation classes. Your public key interface should extend the PublicKey interface. Similarly, your private key interface should extend the PrivateKey interface.

Algorithm Parameter Specification Interfaces and Classes

An algorithm parameter specification is a transparent representation of the sets of parameters used with an algorithm.

A transparent representation of parameters means that you can access each value individually, through one of the get methods defined in the corresponding specification class (e.g., DSAParameterSpec defines getP, getQ, and getG methods, to access the p, q, and g parameters, respectively).

This is contrasted with an opaque representation, as supplied by the AlgorithmParameters engine class, in which you have no direct access to the key material values; you can only get the name of the algorithm associated with the parameter set (via getAlgorithm) and some kind of encoding for the parameter set (via getEncoded).

If you supply an AlgorithmParametersSpi, AlgorithmParameterGeneratorSpi, or KeyPairGeneratorSpi implementation, you must utilize the AlgorithmParameterSpec interface, since each of those classes contain methods that take an AlgorithmParameterSpec parameter. Such methods need to determine which actual implementation of that interface has been passed in, and act accordingly.

JCA contains a number of AlgorithmParameterSpec implementations for the most frequently used signature, cipher and key agreement algorithm parameters. If you are operating on algorithm parameters that should be for a different type of algorithm not provided by JCA, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

Java defines the following algorithm parameter specification interfaces and classes in the java.security.spec and javax.crypto.spec packages:

The AlgorithmParameterSpec Interface

AlgorithmParameterSpec is an interface to a transparent specification of cryptographic parameters.

This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all parameter specifications. All parameter specifications must implement this interface.

The DSAParameterSpec Class

This class (which implements the AlgorithmParameterSpec and DSAParams interfaces) specifies the set of parameters used with the DSA algorithm. It has the following methods:

    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()

These methods return the DSA algorithm parameters: the prime p, the sub-prime q, and the base g.

Many types of DSA services will find this class useful - for example, it is utilized by the DSA signature, key pair generator, algorithm parameter generator, and algorithm parameters classes implemented by the SUN provider. As a specific example, an algorithm parameters implementation must include an implementation for the getParameterSpec method, which returns an AlgorithmParameterSpec. The DSA algorithm parameters implementation supplied by SUN returns an instance of the DSAParameterSpec class.

The IvParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the initialization vector (IV) used with a cipher in feedback mode.

Method in IvParameterSpec
Method Description
byte[] getIV() Returns the initialization vector (IV).

The OAEPParameterSpec Class

This class specifies the set of parameters used with OAEP Padding, as defined in the PKCS #1 standard.

Methods in OAEPParameterSpec
Method Description
String getDigestAlgorithm() Returns the message digest algorithm name.
String getMGFAlgorithm() Returns the mask generation function algorithm name.
AlgorithmParameterSpec getMGFParameters() Returns the parameters for the mask generation function.
PSource getPSource() Returns the source of encoding input P.

The PBEParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with a password-based encryption (PBE) algorithm.

Methods in PBEParameterSpec
Method Description
int getIterationCount() Returns the iteration count.
byte[] getSalt() Returns the salt.

The RC2ParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the RC2 algorithm.

Methods in RC2ParameterSpec
Method Description
boolean equals(Object obj) Tests for equality between the specified object and this object.
int getEffectiveKeyBits() Returns the effective key size in bits.
byte[] getIV() Returns the IV or null if this parameter set does not contain an IV.
int hashCode() Calculates a hash code value for the object.

The RC5ParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the RC5 algorithm.

Methods in RC5ParameterSpec
Method Description
boolean equals(Object obj) Tests for equality between the specified object and this object.
byte[] getIV() Returns the IV or null if this parameter set does not contain an IV.
int getRounds() Returns the number of rounds.
int getVersion() Returns the version.
int getWordSize() Returns the word size in bits.
int hashCode() Calculates a hash code value for the object.

The DHParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the Diffie-Hellman algorithm.

Methods in DHParameterSpec
Method Description
BigInteger getG() Returns the base generator g.
int getL() Returns the size in bits, l, of the random exponent (private value).
BigInteger getP() Returns the prime modulus p.

Many types of Diffie-Hellman services will find this class useful; for example, it is used by the Diffie-Hellman key agreement, key pair generator, algorithm parameter generator, and algorithm parameters classes implemented by the SunJCE provider. As a specific example, an algorithm parameters implementation must include an implementation for the getParameterSpec method, which returns an AlgorithmParameterSpec. The Diffie-Hellman algorithm parameters implementation supplied by SunJCE returns an instance of the DHParameterSpec class.

Key Specification Interfaces and Classes Required by Key Factories

A key factory provides bi-directional conversions between opaque keys (of type Key) and key specifications. If you implement a key factory, you thus need to understand and utilize key specifications. In some cases, you also need to implement your own key specifications.

Further information about key specifications, the interfaces and classes supplied in Java, and key factory requirements with respect to specifications, is provided below.

Key specifications are transparent representations of the key material that constitutes a key. If the key is stored on a hardware device, its specification may contain information that helps identify the key on the device.

A transparent representation of keys means that you can access each key material value individually, through one of the get methods defined in the corresponding specification class. For example, java.security.spec.DSAPrivateKeySpec defines getX, getP, getQ, and getG methods, to access the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

This is contrasted with an opaque representation, as defined by the Key interface, in which you have no direct access to the parameter fields. In other words, an "opaque" representation gives you limited access to the key - just the three methods defined by the Key interface: getAlgorithm, getFormat, and getEncoded.

A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components x, p, q, and g (see DSAPrivateKeySpec), or it may be specified using its DER encoding (see PKCS8EncodedKeySpec).

Java defines the following key specification interfaces and classes in the java.security.spec and javax.crypto.spec packages:

The KeySpec Interface

This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all key specifications. All key specifications must implement this interface.

Java supplies several classes implementing the KeySpec interface: DSAPrivateKeySpec, DSAPublicKeySpec, RSAPrivateKeySpec, RSAPublicKeySpec, EncodedKeySpec, PKCS8EncodedKeySpec, and X509EncodedKeySpec.

If your provider uses key types (e.g., Your_PublicKey_type and Your_PrivateKey_type) for which the JDK does not already provide corresponding KeySpec classes, there are two possible scenarios, one of which requires that you implement your own key specifications:

  1. If your users will never have to access specific key material values of your key type, you will not have to provide any KeySpec classes for your key type.

    In this scenario, your users will always create Your_PublicKey_type and Your_PrivateKey_type keys through the appropriate KeyPairGenerator supplied by your provider for that key type. If they want to store the generated keys for later usage, they retrieve the keys' encodings (using the getEncoded method of the Key interface). When they want to create an Your_PublicKey_type or Your_PrivateKey_type key from the encoding (e.g., in order to initialize a Signature object for signing or verification), they create an instance of X509EncodedKeySpec or PKCS8EncodedKeySpec from the encoding, and feed it to the appropriate KeyFactory supplied by your provider for that algorithm, whose generatePublic and generatePrivate methods will return the requested PublicKey (an instance of Your_PublicKey_type) or PrivateKey (an instance of Your_PrivateKey_type) object, respectively.
  2. If you anticipate a need for users to access specific key material values of your key type, or to construct a key of your key type from key material and associated parameter values, rather than from its encoding (as in the above case), you have to specify new KeySpec classes (classes that implement the KeySpec interface) with the appropriate constructor methods and get methods for returning key material fields and associated parameter values for your key type. You will specify those classes in a similar manner as is done by the DSAPrivateKeySpec and DSAPublicKeySpec classes. You need to ship those classes along with your provider classes, for example, as part of your provider JAR file.

The DSAPrivateKeySpec Class

This class (which implements the KeySpec Interface) specifies a DSA private key with its associated parameters. It has the following methods:

Method in DSAPrivateKeySpec Description
public BigInteger getX() Returns the private key x.
public BigInteger getP() Returns the prime p.
public BigInteger getQ() Returns the sub-prime q.
public BigInteger getG() Returns the base g.

These methods return the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

The DSAPublicKeySpec Class

This class (which implements the KeySpec Interface) specifies a DSA public key with its associated parameters. It has the following methods:

Method in DSAPublicKeySpec Description
public BigInteger getY() returns the public key y.
public BigInteger getP() Returns the prime p.
public BigInteger getQ() Returns the sub-prime q.
public BigInteger getG() Returns the base g.

These methods return the public key y, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

The RSAPrivateKeySpec Class

This class (which implements the KeySpec Interface) specifies an RSA private key. It has the following methods:

Method in RSAPrivateKeySpec Description
public BigInteger getModulus() Returns the modulus.
public BigInteger getPrivateExponent() Returns the private exponent.

These methods return the RSA modulus n and private exponent d values that constitute the RSA private key.

The RSAPrivateCrtKeySpec Class

This class (which extends the RSAPrivateKeySpec class) specifies an RSA private key, as defined in the PKCS#1 standard, using the Chinese Remainder Theorem (CRT) information values. It has the following methods (in addition to the methods inherited from its superclass RSAPrivateKeySpec ):

Method in RSAPrivateCrtKeySpec Description
public BigInteger getPublicExponent() Returns the public exponent.
public BigInteger getPrimeP() Returns the prime P.
public BigInteger getPrimeQ() Returns the prime Q.
public BigInteger getPrimeExponentP() Returns the primeExponentP.
public BigInteger getPrimeExponentQ() Returns the primeExponentQ.
public BigInteger getCrtCoefficient() Returns the crtCoefficient.

These methods return the public exponent e and the CRT information integers: the prime factor p of the modulus n, the prime factor q of n, the exponent d mod (p-1), the exponent d mod (q-1), and the Chinese Remainder Theorem coefficient (inverse of q) mod p.

An RSA private key logically consists of only the modulus and the private exponent. The presence of the CRT values is intended for efficiency.

The RSAPublicKeySpec Class

This class (which implements the KeySpec Interface) specifies an RSA public key. It has the following methods:

Method in RSAPublicKeySpec Description
public BigInteger getModulus() Returns the modulus.
public BigInteger getPublicExponent() Returns the public exponent.

These methods return the RSA modulus n and public exponent e values that constitute the RSA public key.

The EncodedKeySpec Class

This abstract class (which implements the KeySpec Interface) represents a public or private key in encoded format.

Method in EncodedKeySpec Description
public abstract byte[] getEncoded() Returns the encoded key.
public abstract String getFormat() Returns the name of the encoding format.

The JDK supplies two classes implementing the EncodedKeySpec interface: PKCS8EncodedKeySpec and X509EncodedKeySpec. If desired, you can supply your own EncodedKeySpec implementations for those or other types of key encodings.

The PKCS8EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a private key, according to the format specified in the PKCS #8 standard.

Its getEncoded method returns the key bytes, encoded according to the PKCS #8 standard. Its getFormat method returns the string "PKCS#8".

The X509EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a public or private key, according to the format specified in the X.509 standard.

Its getEncoded method returns the key bytes, encoded according to the X.509 standard. Its getFormat method returns the string "X.509". DHPrivateKeySpec, DHPublicKeySpec, DESKeySpec, DESedeKeySpec, PBEKeySpec, and SecretKeySpec.

The DHPrivateKeySpec Class

This class (which implements the KeySpec interface) specifies a Diffie-Hellman private key with its associated parameters.

Method in DHPrivateKeySpec Description
BigInteger getG() Returns the base generator g.
BigInteger getP() Returns the prime modulus p.
BigInteger getX() Returns the private value x.

The DHPublicKeySpec Class

This class (which implements the KeySpec interface) specifies a Diffie-Hellman public key with its associated parameters.

Method in DHPublicKeySpec Description
BigInteger getG() Returns the base generator g.
BigInteger getP() Returns the prime modulus p.
BigInteger getY() Returns the public value y.

The DESKeySpec Class

This class (which implements the KeySpec interface) specifies a DES key.

Method in DESKeySpec Description
byte[] getKey() Returns the DES key bytes.
static boolean isParityAdjusted(byte[] key, int offset) Checks if the given DES key material is parity-adjusted.
static boolean isWeak(byte[] key, int offset) Checks if the given DES key material is weak or semi-weak.

The DESedeKeySpec Class

This class (which implements the KeySpec interface) specifies a DES-EDE (Triple DES) key.

Method in DESedeKeySpec Description
byte[] getKey() Returns the DES-EDE key.
static boolean isParityAdjusted(byte[] key, int offset) Checks if the given DES-EDE key is parity-adjusted.

The PBEKeySpec Class

This class implements the KeySpec interface. A user-chosen password can be used with password-based encryption (PBE); the password can be viewed as a type of raw key material. An encryption mechanism that uses this class can derive a cryptographic key from the raw key material.

Method in PBEKeySpec Description
void clearPassword Clears the internal copy of the password.
int getIterationCount Returns the iteration count or 0 if not specified.
int getKeyLength Returns the to-be-derived key length or 0 if not specified.
char[] getPassword Returns a copy of the password.
byte[] getSalt Returns a copy of the salt or null if not specified.

The SecretKeySpec Class

This class implements the KeySpec interface. Since it also implements the SecretKey interface, it can be used to construct a SecretKey object in a provider-independent fashion, i.e., without having to go through a provider-based SecretKeyFactory.

Method in SecretKeySpec Description
boolean equals (Object obj) Indicates whether some other object is "equal to" this one.
String getAlgorithm() Returns the name of the algorithm associated with this secret key.
byte[] getEncoded() Returns the key material of this secret key.
String getFormat() Returns the name of the encoding format for this secret key.
int hashCode() Calculates a hash code value for the object.

Secret-Key Generation

If you provide a secret-key generator (subclass of javax.crypto.KeyGeneratorSpi) for a particular secret-key algorithm, you may return the generated secret-key object (which must be an instance of javax.crypto.SecretKey, see engineGenerateKey) in one of the following ways:

Adding New Object Identifiers

The following information applies to providers who supply an algorithm that is not listed as one of the standard algorithms in Appendix A of the Java Cryptography Architecture Reference Guide.

Mapping from OID to Name

Sometimes the JCA needs to instantiate a cryptographic algorithm implementation from an algorithm identifier (for example, as encoded in a certificate), which by definition includes the object identifier (OID) of the algorithm. For example, in order to verify the signature on an X.509 certificate, the JCA determines the signature algorithm from the signature algorithm identifier that is encoded in the certificate, instantiates a Signature object for that algorithm, and initializes the Signature object for verification.

For the JCA to find your algorithm, you must provide the object identifier of your algorithm as an alias entry for your algorithm in the provider master file.

    put("Alg.Alias.<engine_type>.1.2.3.4.5.6.7.8",
        "<algorithm_alias_name>");

Note that if your algorithm is known under more than one object identifier, you need to create an alias entry for each object identifier under which it is known.

An example of where the JCA needs to perform this type of mapping is when your algorithm ("Foo") is a signature algorithm and users run the keytool command and specify your (signature) algorithm alias.

    % keytool -genkeypair -sigalg 1.2.3.4.5.6.7.8

In this case, your provider master file should contain the following entries:

    put("Signature.Foo", "com.xyz.MyFooSignatureImpl");
    put("Alg.Alias.Signature.1.2.3.4.5.6.7.8", "Foo");

Other examples of where this type of mapping is performed are (1) when your algorithm is a keytype algorithm and your program parses a certificate (using the X.509 implementation of the SUN provider) and extracts the public key from the certificate in order to initialize a Signature object for verification, and (2) when keytool users try to access a private key of your keytype (for example, to perform a digital signature) after having generated the corresponding keypair. In these cases, your provider master file should contain the following entries:

    put("KeyFactory.Foo", "com.xyz.MyFooKeyFactoryImpl");
    put("Alg.Alias.KeyFactory.1.2.3.4.5.6.7.8", "Foo");

Mapping from Name to OID

If the JCA needs to perform the inverse mapping (that is, from your algorithm name to its associated OID), you need to provide an alias entry of the following form for one of the OIDs under which your algorithm should be known:

    put("Alg.Alias.Signature.OID.1.2.3.4.5.6.7.8", "MySigAlg");

If your algorithm is known under more than one object identifier, prefix the preferred one with "OID."

An example of where the JCA needs to perform this kind of mapping is when users run keytool in any mode that takes a -sigalg option. For example, when the -genkeypair and -certreq commands are invoked, the user can specify your (signature) algorithm with the -sigalg option.

Ensuring Exportability

A key feature of JCA is the exportability of the JCA framework and of the provider cryptography implementations if certain conditions are met.

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files shipped with the JDK specify that "strong" but limited cryptography may be used. An "unlimited" version of these files indicating no restrictions on cryptographic strengths is available for those living in eligible countries (which is most countries). But only the "strong" version can be imported into those countries whose governments mandate restrictions. The JCA framework will enforce the restrictions specified in the installed jurisdiction policy files.

As noted elsewhere, you can write just one version of your provider software, implementing cryptography of maximum strength. It is up to JCA, not your provider, to enforce any jurisdiction policy file-mandated restrictions regarding the cryptographic algorithms and maximum cryptographic strengths available to applets/applications in different locations.

The conditions that must be met by your provider in order to enable it to be plugged into JCA are the following:

Appendix A: The java.security.properties File

Below is part of the java.security file that shows the default list of installed providers. It appears in every JRE installation. The file also contains other entries, but for brevity, we show only part of the file here. See the complete file at:

Here <java-home> refers to the directory where the JRE was installed.

See Step 5 for an example of adding information about your provider to this file.

#
# This is the "master security properties file".
#
# In this file, various security properties are set for use by
# java.security classes. This is where users can statically register
# Cryptography Package Providers ("providers" for short). The term
# "provider" refers to a package or set of packages that supply a
# concrete implementation of a subset of the cryptography aspects of
# the Java Security API. A provider may, for example, implement one or
# more digital signature algorithms or message digest algorithms.
#
# Each provider must implement a subclass of the Provider class.
# To register a provider in this master security properties file,
# specify the Provider subclass name and priority in the format
#
#    security.provider.<n>=<className>
#
# This declares a provider, and specifies its preference
# order n. The preference order is the order in which providers are
# searched for requested algorithms (when no specific provider is
# requested). The order is 1-based; 1 is the most preferred, followed
# by 2, and so on.
#
# <className> must specify the subclass of the Provider class whose
# constructor sets the values of various properties that are required
# for the Java Security API to look up the algorithms or other
# facilities implemented by the provider.
#
# There must be at least one provider specification in java.security.
# There is a default provider that comes standard with the JDK. It
# is called the "SUN" provider, and its Provider subclass
# named Sun appears in the sun.security.provider package. Thus, the
# "SUN" provider is registered via the following:
#
#    security.provider.1=sun.security.provider.Sun
#
# (The number 1 is used for the default provider.)
#
# Note: Providers can be dynamically registered instead by calls to
# either the addProvider or insertProviderAt method in the Security
# class.

#
# List of providers and their preference orders (see above):
#

security.provider.1=sun.security.pkcs11.SunPKCS11 \
    ${java.home}/lib/security/sunpkcs11-solaris.cfg
security.provider.2=sun.security.provider.Sun
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=com.sun.net.ssl.internal.ssl.Provider
security.provider.5=com.sun.crypto.provider.SunJCE
security.provider.6=sun.security.jgss.SunProvider
security.provider.7=com.sun.security.sasl.Provider
security.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.9=sun.security.smartcardio.SunPCSC

# Rest of file deleted


Oracle and/or its affiliates Copyright © 1993, 2022, Oracle and/or its affiliates. All rights reserved.
Contact Us