How to Implement a Provider in the Java Cryptography Architecture (original) (raw)

This document describes what you need to do in order to integrate your provider into Java SE so that algorithms and other services can be found when Java Security API clients request them.

Who Should Read This Document

Programmers who only need to use the Java Security APIs (see Core Classes and Interfaces in [Java Cryptography Architecture (JCA) Reference Guide](java-cryptography-architecture-jca-reference-guide.html#GUID-2BCFDD85-D533-4E6C-8CE9-29990DEB0190 "The Java Cryptography Architecture (JCA) is a major piece of the platform, and contains a "provider" architecture and a set of APIs for digital signatures, message digests (hashes), certificates and certificate validation, encryption (symmetric/asymmetric block/stream ciphers), key generation and management, and secure random number generation, to name a few.")) to access existing cryptography algorithms and other services donot 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.

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.

Introduction to Implementing Providers

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:

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. See Security Providers, which illustrates how a provider selects a requested security service.

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.

A cryptographic service 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.

The Java Cryptography Architecture encompasses the classes comprising the Security package that relate to cryptography, including 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 aSignatureSpi 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.

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, inMessageDigestSpi subclasses, may be those of various message digest algorithms such as SHA-256 or SHA-384.

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. The actual implementation supplied in a KeyFactorySpi subclass would be that for a specific type of keys, such as DSA public and private keys.

Steps to Implement and Integrate a Provider

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. 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), see Engine Classes and Algorithms.

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

To know more about the JCA and other cryptographic classes, see Engine Classes and Corresponding Service Provider Interface Classes.

In the subclass, you need to:

  1. Supply implementations for the abstract methods, whose names usually begin with engine. See Further Implementation Details and Requirements.
  2. Depending on how you write your provider and register its algorithms (using either String objects or the Provider.Service class), the provider either:
    • Ensure that 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: Write Your Master Class, a Subclass of Provider). 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. (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.)
    • Override the newInstance() method in the registered Provider.Service. This is the preferred mechanism in JDK 9 and later.
Step 1.1: Consider 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 the JCA. Thus, one requirement for encryption providers is that they must be signed, as described in later steps.

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 theengineGetKeySize 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 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 unique name for your provider. This is the name to be used by client applications to refer to your provider, and it must not conflict with any other provider names.

Step 3: Write Your Master Class, a Subclass of Provider

Create a subclass of the java.security.Provider class. This is essentially a lookup table that advertises the algorithms that your provider implements.

You can use the following coding styles to subclass the Provider class:

A provider can use either style, or even use both styles at the same time. Regardless of which style you choose, your subclass should be final.

Step 3.1: Create a Provider That Uses String Objects to Register Its Services

The following is an example of a provider that uses String objects to store implemented algorithm names:

package p;
public final class MyProvider extends Provider {
    public MyProvider() {
        super("MyProvider", "1.0",
            "Some info about my provider and which algorithms it supports");
        // com.my.crypto.provider.MyCipher extends CipherSPI
        put("Cipher.MyCipher", "com.my.crypto.provider.MyCipher");
    }
}

To create a provider with this coding style, do the following:

    super("MyProvider", "1.0",  
        "Some info about my provider and which algorithms it supports");  
    put("Cipher.MyCipher", "com.my.crypto.provider.MyCipher");  

The following list shows the various types of JCA services, where the actual algorithm name is substituted for algName:

    put("Signature.SHA256withDSA", "sun.security.provider.DSA");  

The following list shows more properties that can be defined for the various types of services, where the actual algorithm name is substituted for algName, certificate type for certType, keystore type for storeType, and attribute name for attrName:

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

Note:
For examples of this coding style, see the source code for sun.security.provider.Sun and sun.security.provider.SunEntries classes.

Step 3.2: Create a Provider That Uses Provider.Service

The following is an example of a provider that uses a Provider.Service class:

package p;
 
public final class MyProvider extends Provider {
     
    public MyProvider() {
        super("MyProvider", "1.0",
            "Some info about my provider and which algorithms it supports");
        putService(new ProviderService(this, "Cipher", "MyCipher", "p.MyCipher"));
    }
     
    private static final class ProviderService extends Provider.Service {
        ProviderService(Provider p, String type, String algo, String cn) {
            super(p, type, algo, cn, null, null);
        }
         
        @Override
        public Object newInstance(Object ctrParamObj)
            throws NoSuchAlgorithmException {
            String type = getType();
            String algo = getAlgorithm();
            try {
                if (type.equals("Cipher")) {
                    if (algo.equals("MyCipher")) {
                        return new MyCipher();
                    }
                }
            } catch (Exception ex) {
                throw new NoSuchAlgorithmException(
                    "Error constructing " + type + " for "
                    + algo + " using MyProvider", ex);
            }
            throw new ProviderException("No impl for " + algo + " " + type);
        }
    }
}

To create a provider with this coding style, do the following:

        putService(new ProviderService(this, "Cipher", "MyCipher", "p.MyCipher"));  

This example uses a subclass of Provider.Service named ProviderService (rather than Provider.Service itself) as it customizes how the JCA framework instantiates services. If you don't need to customize the behavior of Provider.Service, then you can call theProvider.Service constructor directly:

public final class MyProvider extends Provider {  
    public MyProvider() {  
        super("MyProvider", "1.0",  
            "Some info about my provider and which algorithms it supports");  
        putService(new Provider.Service(  
            this, "Cipher", "MyCipher", "p.MyCipher", null, null));  
    }  
}  

Note that this example is essentially the same as the example described in Step 3.1: Create a Provider That Uses String Objects to Register Its Services.

Step 3.3: Specify Additional Information for Cipher Implementations

As mentioned previously, 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 aCipher 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 inCFB 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 128 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 ofCipher, which invoke the engineSetMode andengineSetPadding methods of the provider's subclass ofCipherSpi.

That is, aCipher property in a provider master class may have one of the formats shown in the following table:

Table 3-1 Cipher Property Format

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

(See Java Security Standard Algorithm Names for the standard algorithm names, modes, and padding schemes that should be used.)

For example, a provider may supply a subclass ofCipherSpi 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 these modes (for example, 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 ofCipherSpi 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.
  2. 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: Create a Module Declaration for Your Provider

This step is optional but recommended; it enables you to package your provider in a named module. A modular JDK can then locate your provider in the module path as opposed to the class path. The module system can more thoroughly check for dependencies in modules in the module path. Note that you can use named modules in a non-modular JDK; the module declaration will be ignored. Also, you can still package your providers in unnamed or automatic modules.

Create a module declaration for your provider and save it in a file named module-info.java. This module declaration includes the following:

The following example module declaration defines a module named com.foo.MyProvider. p.MyProvider is the fully qualified class name of a service implementation. Suppose that, in this example, p.MyProvider uses API in the package javax.security.auth.kerberos, which is in the module java.security.jgss. Thus, the directive requires java.security.jgss appears in the module declaration.

module com.foo.MyProvider {
    provides java.security.Provider with p.MyProvider;
    requires java.security.jgss;
    }

You can package a provider in three different kinds of modules:

It is recommended that you package your providers in named modules as they provide better performance, stronger encapsulation, simpler configuration and greater flexibility.

You have a lot of flexibility when it comes to packaging and configuring your providers. However, this impacts how you start applications that use them. For example, you might have to specify additional --add-exports or --add-modules options. Named modules, in general, require fewer of these additional options. In addition named modules offer more flexibility. You can use them with non-modular JDKs or even as unnamed modules by specifying them in a modular JDK's class path. For more information about modules, see The State of the Module System and JEP 261: Module System.

Step 5: Compile Your Code

Step 6: Place Your Provider in a JAR File

Add the File java.security.Provider to Use the ServiceLoader Class to Search for Providers

If your provider is packaged in an automatic or unnamed module (you did not create a module declaration as described in Step 4: Create a Module Declaration for Your Provider) and you want the use the java.util.ServiceLoader to search for your providers, then add the file META-INF/services/java.security.Provider to the JAR file and ensure that the file contains the fully qualified class name of your provider implementation.

The security provider loading mechanism uses the ServiceLoader class to search for providers before consulting the class path.

For example, if the fully qualified class name of your provider is p.Provider and all the compiled code of your provider is in the directory classes, then create a file named classes/META-INF/services/java.security.Provider that contains the following line:

p.MyProvider

Run the jar Command to Create a JAR File

The following command creates a JAR file named MyProvider.jar. All the compiled code for the module JAR file is in the directory classes. In addition, the module descriptor, module-info.class, is in the directory classes:

jar --create --file MyProvider.jar --module-version 1.0 -C classes

Note:

The module-info.class file and the --module-version option are optional. However, the module-info.class file is required if you want to create a modular JAR file. (A modular JAR file is a regular JAR file that has a module-info.class file in its top-level directory.)

See jar in Java Development Kit Tool Specifications.

Step 7: Sign Your JAR File, If Necessary

Step 7.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.

The following are the steps you should use to get a code-signing certificate. Seekeytool in the Java Development Kit Tool Specifications.

  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 keypair (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.
Tip:
Do not surround actual values with angle brackets. For example, if you want your alias to bemyTestAlias, specify the -alias option as follows:

    -alias myTestAlias  

If you specify a keystore that doesn't yet exist, it will be created.
Note:
If command lines you type are not allowed to be as long as the keytool -genkeypair command you want to execute (for example, if you are typing to a Microsoft Windows DOS prompt), you can create and execute a plain-text batch file containing the command. That is, create a new text file that contains nothing but the full keytool -genkeypair command. (Remember to type it all on one line.) Save the file with a .bat extension. Then in your DOS window, type the file name (with its path, if necessary). This will cause the command in the batch file to be executed. 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 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. SeeJCA Code Signing Certification Authority 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>  

<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 6: Place Your Provider in a JAR File) and then use that certificate to sign the JAR file (Step 7.2: Sign Your Provider).

Step 7.2: Sign Your Provider

Sign the JAR file created in Step 6: Place Your Provider in a JAR File with the code-signing certificate obtained in Step 7.1: Get a Code-Signing Certificate. See jarsigner in Java Development Kit Tool Specifications.

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 7.1: Get a Code-Signing Certificate).

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:

Step 8: Prepare for Testing

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

Step 8.1: Configure the Provider

Register your provider so that the JCA framework can find your provider, either with the ServiceLoader class or in the class path or module path.

  1. Open the java.security file in an editor:
    • Linux or macOS:<java-home>/conf/security/java.security
    • Windows: <java-home>\conf\security\java.security
  2. In the java.security file, find the section where standard providers such as SUN, SunRsaSign, and SunJCE are configured as static providers; it looks like the following:
security.provider.1=SUN  
security.provider.2=SunRsaSign  
security.provider.3=SunEC  
security.provider.4=SunJSSE  
security.provider.5=SunJCE  
security.provider.6=SunJGSS  
security.provider.7=SunSASL  
security.provider.8=XMLDSig  
security.provider.9=SunPCSC  
security.provider.10=JdkLDAP  
security.provider.11=JdkSASL  
security.provider.12=SunMSCAPI  
security.provider.13=SunPKCS11  

Each line in this section has the following form:

security.provider.n=provName|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.
provName is the provider's name and className is the fully qualified class name of the provider. You can use either of these two names. 3. Register your provider by adding to the java.security file a line with the form security.provider.n=provName|className.
If you configured your provider so that the ServiceLoader class can search for it (because you packaged the provider in a named module as described in Step 4: Create a Module Declaration for Your Provider or added a java.security.Provider file as described in Add the File java.security.Provider to Use the ServiceLoader Class to Search for Providers), then specify just the provider's name.
If you have not configured your provider so that ServiceLoader class can search for it, which means that the JCA framework will search for it in the class path or module path, then specify the fully qualified class name of your provider.
For example, the highlighted line registers the provider MyProvider (whose fully qualified class name is p.MyProvider and has been configured so that the ServiceLoader class can search for it) as the 14th preferred provider:

# ...  
security.provider.11=JdkSASL  
security.provider.12=SunMSCAPI  
security.provider.13=SunPKCS11  
security.provider.14=MyProvider  

If you are not sure if the ServiceLoader mechanism will be used, or if you'll be deploying on a non-modular system, then you can also register the provider again, this time using the full class name:

security.provider.15=p.MyProvider  

Note:
Properties in thejava.security file are typically parsed only once. If you have modified any property in this file, restart your applications to ensure that the changes are properly reflected.

Alternatively, you can register providers dynamically. To do so, a program (such as your test program, to be written in Step 9: Write and Compile Your Test Programs) call either the addProvider or insertProviderAt method in the Security class:

ServiceLoader<Provider> sl = ServiceLoader.load(java.security.Provider.class);
for (Provider p : sl) {
    System.out.println(p);
    if (p.getName().equals("MyProvider")) {
        Security.addProvider(p);
    }
}

Grant the program, which calls the addProvider orinsertProviderAt method, one of the following permissions:

java.security.SecurityPermission "addProvider.<provider name>"
java.security.SecurityPermission "insertProvider.<provider name>"

For example, if the provider name is MyJCE, your program is in themyapplication.jar file in the /localWork directory, and your program calls the addProvider method, then the following is a sample policy file that contains a grant statement that grants that permission:

    grant codeBase "file:/localWork/myapplicaton.jar" {
        permission java.security.SecurityPermission
            "insertProvider.MyJCE";
    };
Step 8.2: Set Provider Permissions

Permissions must be granted for when applications are run while a security manager is installed. A security manager may be installed for an application either through code in the application itself or through a command-line argument.

WARNING:

The Security Manager and APIs related to it have been deprecated and are subject to removal in a future release. There is no replacement for the Security Manager. See JEP 411 for discussion and alternatives.

  1. Your provider may need the following permissions granted to it in the client environment:
    • java.lang.RuntimePermission to get class protection domains. The provider may need to get its own protection domain in the process of doing self-integrity checking.
    • java.security.SecurityPermission to set provider properties.
  2. To ensure your provider works when a security manager is installed, you need to test such an installation and execution environment. In addition, prior to testing your need to grant appropriate permissions to your provider and to any other providers it uses.
    For example, the following is a sample statement granting permissions to a provider whose name is MyJCE and whose code is inmyjce_provider.jar. 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 9: 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.

  1. 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 forMyPro:
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());  
  1. 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());  
  1. Optional: If you don't specify a provider name in the call to getInstance, all registered providers will be searched, in preference order (see Step 8.1: Configure the Provider), until one implementing the algorithm is found.
  2. Optional: If your provider implements an exemption mechanism, you should write a test application that uses the exemption mechanism. Such an application also needs to be signed and have a "permission policy file" bundled with it.

Step 10: Run Your Test Programs

When you run your test applications, the required java command options will vary depending on factors such as whether you packaged your provider as a named, automatic, or unnamed module and if you configured it so that the ServiceLoader class can search for it.

If you packaged your provider as a named module and have configured it so that the ServiceLoader class can search for it (by registering it with its name in the java.security as described in Step 8.1: Configure the Provider), then run your test program with the following command:

java --module-path "jars" <other java options>

The directory jars contains your provider.

You may require more options depending on your provider code style (see Step 3.1: Create a Provider That Uses String Objects to Register Its Services and Step 3.2: Create a Provider That Uses Provider.Service), if you packaged your provider in a different kind of module, or if you have not configured it for the ServiceLoader class. The following table describes these options.

For the java commands, the name of the provider is MyProvider, its fully qualified class name is p.MyProvider, and it is packaged in the file com.foo.MyProvider.jar, which is in the directory jars.

Table 3-2 Expected Java Runtime Options for Various Provider Implementation Styles

Module Type Provider Code Style Configured for ServiceLoader Class? Provider Name Used in java.security File java Command
Unnamed String objects or Provider.Service No Fully qualified class name java -cp "jars/com.foo.MyProvider.jar"
Unnamed String objects or Provider.Service Yes Fully qualified class name or provider name java -cp "jars/com.foo.MyProvider.jar"
Automatic String objects or Provider.Service No Fully qualified class name java --module–path "jars/com.foo.MyProvider.jar" --add–modules=com.foo.MyProvider
Automatic String objects or Provider.Service Yes Fully qualified class name or provider name java --module–path "jars/com.foo.MyProvider.jar"
Named String objects or Provider.Service No Fully qualified class name java --module–path "jars" --add–modules=com.foo.MyProvider --add–exports=com.foo.MyProvider/p=java.base You can remove the --add-exports option if you add exports p in the module declaration.
Named String objects Yes Fully qualified class name java --module–path "jars" --add–exports=com.foo.MyProvider/p=java.base You can remove the --add-exports option if you add exports p in the module declaration.
Named String objects Yes Provider name java --module–path "jars" --add–exports=com.foo.MyProvider/p=java.base You can remove the --add-exports option if you add exports p in the module declaration.
Named Provider.Service Yes Fully qualified class name java --module–path "jars" --add–exports=com.foo.MyProvider/p=java.baseYou can remove the --add-exports option if you add exports p in the module declaration.
Named Provider.Service Yes Provider name java --module–path "jars"

Once you have determined the proper java options for your test programs, run them. Debug your code and continue testing as needed. If the Java runtime cannot seem to find one of your algorithms, review the previous steps and ensure that they are all completed.

Be sure to include testing of your programs using different installation options (for example, configured to use the ServiceLoader class or to be found in the class path or module path) and execution environments (with or without a security manager running).

WARNING:

The Security Manager and APIs related to it have been deprecated and are subject to removal in a future release. There is no replacement for the Security Manager. See JEP 411 for discussion and alternatives.

  1. Optional: If you find during testing that your code needs modification, make the changes and recompile Step 5: Compile Your Code.
  2. Place the updated provider code in a JAR file (Step 6: Place Your Provider in a JAR File).
  3. Sign the JAR file (Step 7: Sign Your JAR File, If Necessary).
  4. Re-configure the provider (Step 8.1: Configure the Provider).
  5. Optional: If needed, fix or add to the permissions (Step 8.2: Set Provider Permissions).
  6. Run your programs.
  7. Optional: If required, repeat steps 1 to 6.

Step 11: 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 callsCipher.getInstance() and the returnedCipher 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 thecryptoPerms 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 applications "exempt" from cryptographic restrictions must include a cryptoPerms permission policy file in their JAR file. See How to Make Applications Exempt from Cryptographic Restrictions.

Here are two URLs that may be useful:

Step 12: 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.

Step 12.1: Indicate Whether Your Implementation is Cloneable for 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,

mac

Indicates the MAC object they received when they requested one via a call to Mac.getInstance

i1, i2 and i3

Indicates input byte arrays, and they want to calculate separate hashes for:

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 behavior 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 13: 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.

Further Implementation Details and Requirements

This section provides additional information about alias names, service interdependencies, algorithm parameter generators and algorithm parameters.

Alias Names

In the JDK, the aliasing scheme enables clients to use aliases when referring to algorithms or types, rather than the standard names.

For many cryptographic algorithms and types, there is a single official "standard name" defined in the Java Security Standard Algorithm Names.

For example, "SHA-256" is the standard name for the SHA-256 Message Digest algorithm defined in FIPS PUB 180-4: Secure Hash Standard (SHS).DiffieHellman is the standard for the Diffie-Hellman key agreement algorithm defined in PKCS#3.

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: Write Your Master Class, a Subclass of Provider). 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:

The 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:

MessageDigest.getInstance("SHA-256", "SUN")  
MessageDigest.getInstance("SHA-256")  

This is only appropriate if you are sure that there will be at least one implementation of the requested algorithm (in this case, SHA-256) 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 SHA-256 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:

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 Initialization

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 JDK Providers Documentation 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 12: Document Your Provider and Its Supported Services) 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

Provider.Service class offers an alternative way for providers to advertise their services and supports additional features.

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, theProvider.Service class. It offers an alternative way for providers to advertise their services and supports additional features. 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 typeCertStore, the constructor that takes aCertStoreParameters object is invoked, andconstructorParameter must be a non-null instance ofCertStoreParameters. A security provider can override thenewInstance() 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 previously.

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, andKeyAgreement. The parameter must be an instance of Key in these cases. For example, forSignature services, the framework tests whether the service can use the supplied Key before instantiating the service. The default implementation examines the attributes SupportedKeyFormats andSupportedKeyClasses. 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

The signature algorithm should specify the format in which the signature is encoded.

If you implement a signature algorithm, the documentation you supply (Step 12: Document Your Provider and Its Supported Services) should specify the format in which the signature (generated by one of the sign methods) is encoded.

For example, the SHA1withDSA 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 interfaces (in thejava.security.interfaces package) for the convenience of programmers implementing DSA services.

The Java Security API contains the following interfaces:

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, it's no longer necessary. The 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 implementingDSAParams for holding and returning the p,q, and g parameters.

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

Note:

There is a DSAParams implementation built into the JDK: thejava.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 andDSAPublicKey interfaces.

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

If you implement a DSA key factory, yourengineGeneratePrivate method (in yourKeyFactorySpi subclass) will return an instance of yourDSAPrivateKey implementation, and yourengineGeneratePublic method will return an instance of yourDSAPublicKey implementation.

Also, your engineGetKeySpec andengineTranslateKey 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 theDSAParameterSpec constructor called to create a parameter specification from parameter values that could be used to initialize aKeyPairGenerator object for DSA.

If you implement a DSA signature algorithm, yourengineInitSign method (in your SignatureSpi subclass) will expect to be passed a DSAPrivateKey and yourengineInitVerify method will expect to be passed aDSAPublicKey.

Please note: The DSAPublicKey andDSAPrivateKey interfaces define a very generic, provider-independent interface to DSA public and private keys, respectively. TheengineGetKeySpec 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 ofDSAPrivateKey or DSAPublicKey, for example, to take advantage of provider-specific implementation details. The same is true for the DSA signature algorithm engineInitSign andengineInitVerify methods (in your SignatureSpi subclass).

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

In the java.security.interfaces package:

public interface DSAPrivateKey extends DSAKey, PrivateKey
public interface DSAPublicKey extends DSAKey, PublicKey
public interface DSAKey

In the java.security package:

public interface PrivateKey extends Key
public interface PublicKey extends Key
public interface Key extends Serializable

To implement the DSAPrivateKey andDSAPublicKey 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 DSA keys, you need to supply a class that implements:

RSA Interfaces and their Required Implementations

The Java Security API contains the 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 RSAPublicKey (and/orRSAPrivateCrtKey) 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, andRSAPrivateCrtKey interfaces define a very generic, provider-independent interface to RSA public and private keys. TheengineGetKeySpec 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, orRSAPublicKey, for example, 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 PrivateKey
public interface RSAPrivateCrtKey extends RSAPrivateKey
public interface RSAPublicKey extends PublicKey

In the java.security package:

public interface PrivateKey extends Key
public interface PublicKey extends Key
public interface Key extends Serializable

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 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 andDHPublicKey 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 andDHPrivateKey interfaces define a very generic, provider-independent interface to Diffie-Hellman public and private keys, respectively. The engineGetKeySpec andengineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation ofDHPrivateKey or DHPublicKey, for example, to take advantage of provider-specific implementation details. The same is true for the Diffie-Hellman algorithm engineInit andengineDoPhase methods (in yourKeyAgreementSpi 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, PrivateKey
public interface DHPublicKey extends DHKey, jPublicKey
public interface DHKey

In the java.security package:

public interface PrivateKey extends Key
public interface PublicKey extends Key
public interface Key extends 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 previously, 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 thePrivateKey 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.

Table 3-3 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.

Table 3-4 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.

Table 3-5 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.

Table 3-6 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.

Table 3-7 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.

Table 3-8 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.

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:

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 previous 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 theDSAPrivateKeySpec 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:

Table 3-9 Methods in DSAPrivateKeySpec

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:

Table 3-10 Methods in DSAPublicKeySpec

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.

The RSAPrivateKeySpec Class

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

Table 3-11 Methods in RSAPrivateKeySpec

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 ):

Table 3-12 Methods in RSAPrivateCrtKeySpec

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:

Table 3-13 Methods in RSAPublicKeySpec

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

The EncodedKeySpec Class

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

Table 3-14 Methods in EncodedKeySpec

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.

Table 3-15 Methods in DHPrviateKeySpec

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

Table 3-16 Methods in DHPublicKeySpec

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.

Table 3-17 Methods in DESKeySpec

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.

Table 3-18 Methods in DESedeKeySpec

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.

Table 3-19 Methods in PBEKeySpec

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.

Table 3-20 Methods in SecretKeySpec

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.

The generated secret-key object (which must be an instance of javax.crypto.SecretKey, see engineGenerateKey) can be returned 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 Java Security Standard Algorithm Names.

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 should 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 -keyalg foo 

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");
    put("KeyPairGenerator.Foo", "com.xyz.MyFooKeyPairGeneratorImpl");

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.

By default, an application can use cryptographic algorithms of any strength. However, due to import regulations in some countries, you may have to limit those algorithms' strength. You do this with jurisdiction policy files; see Cryptographic Strength Configuration. 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:

Sample Code for MyProvider

The following is the complete source code for an example provider, MyProvider. It's a portable provider; you can specify it in a class or module path. It consists of two modules:

This example consists of the following files:

src/com.example.MyProvider/module-info.java

See Step 4: Create a Module Declaration for Your Provider for information about the module declaration, which is specified in module-info.java.

module com.example.MyProvider {
    provides java.security.Provider with com.example.MyProvider.MyProvider;
}

src/com.example.MyProvider/com/example/MyProvider/MyProvider.java

The MyProvider class is an example of a provider that uses the Provider.Service class. See Step 3.2: Create a Provider That Uses Provider.Service.

package com.example.MyProvider;

import java.security.*;
import java.util.*;

/**
 * Test JCE provider.
 *
 * Registers services using Provider.Service and overrides newInstance().
 */
public final class MyProvider extends Provider {

    public MyProvider() {
        super("MyProvider", "1.0", "My JCE provider");

        final Provider p = this;

        AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
            putService(new ProviderService(p, "Cipher",
                    "MyCipher", "com.example.MyProvider.MyCipher"));
            return null;
        });
    }

    private static final class ProviderService extends Provider.Service {

        ProviderService(Provider p, String type, String algo, String cn) {
            super(p, type, algo, cn, null, null);
        }

        ProviderService(Provider p, String type, String algo, String cn,
                String[] aliases, HashMap<String, String> attrs) {
            super(p, type, algo, cn,
                    (aliases == null ? null : Arrays.asList(aliases)), attrs);
        }

        @Override
        public Object newInstance(Object ctrParamObj)
                throws NoSuchAlgorithmException {

            String type = getType();
            if (ctrParamObj != null) {
                throw new InvalidParameterException(
                        "constructorParameter not used with " + type
                        + " engines");
            }
            String algo = getAlgorithm();
            try {
                if (type.equals("Cipher")) {
                    if (algo.equals("MyCipher")) {
                        return new MyCipher();
                    }
                }
            } catch (Exception ex) {
                throw new NoSuchAlgorithmException(
                        "Error constructing " + type + " for "
                        + algo + " using SunMSCAPI", ex);
            }
            throw new ProviderException("No impl for " + algo
                    + " " + type);
        }
    }

    @Override
    public String toString() {
        return "MyProvider [getName()=" + getName()
                + ", getVersionStr()=" + getVersionStr() + ", getInfo()="
                + getInfo() + "]";
    }
}

src/com.example.MyProvider/com/example/MyProvider/MyCipher.java

The MyCipher class extends the CipherSPI, which is a Server Provider Interface (SPI). Each cryptographic service that a provider implements has a subclass of the appropriate SPI. See Step 1: Write your Service Implementation Code.

Note:

This code is only a stub provider that demonstrates how to write a provider; it's missing the actual cryptographic algorithm implementation. The MyCipher class would contain an actual cryptographic algorithm implementation if MyProvider were a real security provider.

package com.example.MyProvider;

import java.security.*;
import java.security.spec.*;
import javax.crypto.*;

/**
 * Implementation represents a test Cipher.
 *
 * All are stubs.
 */
public class MyCipher extends CipherSpi {

    @Override
    protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
            throws IllegalBlockSizeException, BadPaddingException {
        return null;
    }

    @Override
    protected int engineDoFinal(byte[] input, int inputOffset, int inputLen,
            byte[] output, int outputOffset) throws ShortBufferException,
            IllegalBlockSizeException, BadPaddingException {
        return 0;
    }

    @Override
    protected int engineGetBlockSize() {
        return 0;
    }

    @Override
    protected byte[] engineGetIV() {
        return null;
    }

    @Override
    protected int engineGetOutputSize(int inputLen) {
        return 0;
    }

    @Override
    protected AlgorithmParameters engineGetParameters() {
        return null;
    }

    @Override
    protected void engineInit(int opmode, Key key, SecureRandom random)
            throws InvalidKeyException {
    }

    @Override
    protected void engineInit(int opmode, Key key,
            AlgorithmParameterSpec params, SecureRandom random)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
    }

    @Override
    protected void engineInit(int opmode, Key key, AlgorithmParameters params,
            SecureRandom random) throws InvalidKeyException,
            InvalidAlgorithmParameterException {
    }

    @Override
    protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
    }

    @Override
    protected void engineSetPadding(String padding)
            throws NoSuchPaddingException {
    }

    @Override
    protected int engineGetKeySize(Key key)
            throws InvalidKeyException {
        return 0;
    }

    @Override
    protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
        return null;
    }

    @Override
    protected int engineUpdate(byte[] input, int inputOffset, int inputLen,
            byte[] output, int outputOffset) throws ShortBufferException {
        return 0;
    }
}

src/com.example.MyProvider/META-INF/services/java.security.Provider

The java.security.Provider file enables automatic or unnamed modules to use the ServiceLoader class to search for your providers. See Step 6: Place Your Provider in a JAR File.

com.example.MyProvider.MyProvider

src/com.example.MyApp/module-info.java

This file contains a uses directive, which specifies a service that the module requires. This directive helps the module system locate providers and ensure that they run reliably. This is the complement to the provides directive in the MyProvider module definition.

module com.example.MyApp {
    uses java.security.Provider;
}

src/com.example.MyApp/com/example/MyApp/MyApp.java

package com.example.MyApp;

import java.util.*;
import java.security.*;
import javax.crypto.*;

/**
 * A simple JCE test client to access a simple test Provider/Cipher
 * implementation in a signed modular jar.
 */
public class MyApp {

    private static final String PROVIDER = "MyProvider";
    private static final String CIPHER = "MyCipher";

    public static void main(String[] args) throws Exception {

        /*
         * Registers MyProvider dynamically.
         *
         * Could do statically by editing the java.security file.
         * Use the first form if using ServiceLoader ("uses" or
         * META-INF/service), the second if using the traditional class
         * lookup method.  Both if provider could be deployed to either.
         *
         * security.provider.14=MyProvider
         * security.provider.15=com.example.MyProvider.MyProvider
         */
        ServiceLoader<Provider> sl =
            ServiceLoader.load(java.security.Provider.class);
        for (Provider p : sl) {
            if (p.getName().equals(PROVIDER)) {
                System.out.println("Registering the Provider");
                Security.addProvider(p);
            }
        }

        /*
         * Get a MyCipher from MyProvider and initialize it.
         */
        Cipher cipher = Cipher.getInstance(CIPHER, PROVIDER);
        cipher.init(Cipher.ENCRYPT_MODE, (Key) null);

        /*
         * What Provider did we get?
         */
        Provider p = cipher.getProvider();
        Class c = p.getClass();
        Module m = c.getModule();
        System.out.println(p.getName() + ": version "
            + p.getVersionStr() + "\n"
            + p.getInfo() + "\n    "
            + ((m.getName() == null) ? "<UNNAMED>" : m.getName())
            + "/" + c.getName());
    }
}

RunTest.sh

#!/bin/sh

#
# A simple example to show how a JCE provider could be developed in a
# modular JDK, for deployment as either Named/Unnamed modules.
#

#
# Edit as appropriate
#
JDK_DIR=d:/java/jdk9
KEYSTORE=YourKeyStore
STOREPASS=YourStorePass
SIGNER=YourAlias

echo "-----------"
echo "Clean/Init"
echo "-----------"
rm -rf mods jars
mkdir mods jars

echo "--------------------"
echo "Compiling MyProvider"
echo "--------------------"
${JDK_DIR}/bin/javac.exe \
    --module-source-path src \
    -d mods \
    $(find src/com.example.MyProvider -name '*.java' -print)

echo "------------------------------------"
echo "Packaging com.example.MyProvider.jar"
echo "------------------------------------"
${JDK_DIR}/bin/jar.exe --create \
    --file jars/com.example.MyProvider.jar \
    --verbose \
    --module-version=1.0 \
    -C mods/com.example.MyProvider . \
    -C src/com.example.MyProvider META-INF/services

echo "----------------------------------"
echo "Signing com.example.MyProvider.jar"
echo "----------------------------------"
${JDK_DIR}/bin/jarsigner.exe \
    -keystore ${KEYSTORE} \
    -storepass ${STOREPASS} \
    jars/com.example.MyProvider.jar ${SIGNER}

echo "---------------"
echo "Compiling MyApp"
echo "---------------"
${JDK_DIR}/bin/javac.exe \
    --module-source-path src \
    -d mods \
    $(find src/com.example.MyApp -name '*.java' -print)

echo "-------------------------------"
echo "Packaging com.example.MyApp.jar"
echo "-------------------------------"
${JDK_DIR}/bin/jar.exe --create \
    --file jars/com.example.MyApp.jar \
    --verbose \
    --module-version=1.0 \
    -C mods/com.example.MyApp .

echo "------------------------"
echo "Test1                   "
echo "Named Provider/Named App"
echo "------------------------"
${JDK_DIR}/bin/java.exe \
    --module-path 'jars' \
    -m com.example.MyApp/com.example.MyApp.MyApp

echo "--------------------------"
echo "Test2                     "
echo "Named Provider/Unnamed App"
echo "--------------------------"
${JDK_DIR}/bin/java.exe \
    --module-path 'jars/com.example.MyProvider.jar' \
    --class-path 'jars/com.example.MyApp.jar' \
    com.example.MyApp.MyApp

echo "--------------------------"
echo "Test3                     "
echo "Unnamed Provider/Named App"
echo "--------------------------"
${JDK_DIR}/bin/java.exe \
    --module-path 'jars/com.example.MyApp.jar' \
    --class-path 'jars/com.example.MyProvider.jar' \
    -m com.example.MyApp/com.example.MyApp.MyApp

echo "----------------------------"
echo "Test4                       "
echo "Unnamed Provider/Unnamed App"
echo "----------------------------"
${JDK_DIR}/bin/java.exe \
    --class-path \
        'jars/com.example.MyProvider.jar;jars/com.example.MyApp.jar' \
    com.example.MyApp.MyApp