How to Implement a Provider in the Java Cryptography Architecture
- Introduction
- Engine Classes and Corresponding SPI Classes
- Steps to Implement and Integrate a Provider
- Step 1: Write your Service Implementation Code
- Step 2: Give your Provider a Name
- Step 3: Write your Master Class, a subclass of Provider
- Step 4: Compile your Code
- Step 5: Place your Provider in a Jar File
- Step 6: Sign your JAR File
- Step 7: Prepare for Testing
- Step 8: Write and Compile your Test Programs
- Step 9: Run your Test Programs
- Step 10: Apply for U.S. Government Export Approval if Required
- Step 11: Document your Provider and its Supported Services
- Step 12: Make your Class Files and Documentation Available to Clients
- How a Provider Can Do Self-Integrity Checking
- Further Implementation Details and Requirements
- Alias Names
- Service Interdependencies
- Default Initializations
- Default Key Pair Generator Parameter Requirements
- The
Provider.Service
Class - Signature Formats
- DSA Interfaces and their Required Implementations
- RSA Interfaces and their Required Implementations
- Diffie-Hellman Interfaces and their Required Implementations
- Interfaces for Other Algorithm Types
- Algorithm Parameter Specification Interfaces and Classes
- Key Specification Interfaces and Classes Required by Key Factories
- Secret-Key Generation
- Ensuring Exportability
- Appendix A: The Sun Provider Master Class
- Appendix B: The SunJCE Provider Master Class
- Appendix C: The
java.security
Properties File
Introduction
The Java platform defines a set of APIs spanning major security areas, including cryptography, public key infrastructure, authentication, secure communication, and access control. These APIs allow developers to easily integrate security into their application code. They were designed around the following principles:
Implementation independence
Applications do not need to implement security themselves. Rather, they can request security services from the Java platform. Security services are implemented in providers (see below), which are plugged into the Java platform via a standard interface. An application may rely on multiple independent providers for security functionality.
Implementation interoperability
Providers are interoperable across applications. Specifically, an application is not bound to a specific provider, and a provider is not bound to a specific application.
Algorithm extensibility
The Java platform includes a number of built-in providers that implement a basic set of security services that are widely used today. However, some applications may rely on emerging standards not yet implemented, or on proprietary services. The Java platform supports the installation of custom providers that implement such services.
A Cryptographic Service Provider (provider) refers to a package (or a set of packages) that supply a concrete implementation of a subset of the cryptography aspects of the JDK Security API.
The java.security.Provider
class encapsulates the notion of a security provider in the Java platform. It specifies the provider's name and lists the security services it implements. Multiple providers may be configured at the same time, and are listed in order of preference. When a security service is requested, the highest priority provider that implements that service is selected.
The following figure illustrate these options for requesting an MD5 message digest implementation. The figure consists of two diagrams, both of which show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In the diagram to the left, an application requests an MD5 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In the diagram to the right, the application requests the MD5 algorithm implementation from a specific provider, ProviderC. This time the implementation from that provider is returned, even though a provider with a higher preference order, ProviderB, also supplies an MD5 implementation.
Description of Figure Options for Requesting an MD5 Message Digest Implementation
Each installation has one or more provider packages installed. Clients may configure their runtimes with different providers, and specify a preference order for each of them. The preference order is the order in which providers are searched for requested algorithms when no particular provider is requested.
The Oracle version of the Java runtime environment (JRE) comes standard with a default provider, named "SUN". Other Java runtime environments may not necessarily supply the "SUN" provider.
Who Should Read This Document
Programmers that only need to use the Java Security API to access existing cryptography algorithms and other services do not need to read this document.
This document is intended for experienced programmers wishing to create their own provider packages supplying cryptographic service implementations. It documents what you need to do in order to integrate your provider into Java so that your algorithms and other services can be found when Java Security API clients request them.
Related Documentation
This document assumes you have already read the Java Cryptography Architecture Reference Guide.
It documents the packages which contain the various classes and interfaces in the Security API.
java.security
java.security.spec
java.security.interfaces
javax.crypto
javax.crypto.spec
javax.crypto.interfaces
Notes on Terminology
- Prior to JDK 1.4, the JCE was an unbundled product, and as such, the JCA and JCE were regularly referred to as separate, distinct components. As JCE is now bundled in JDK, the distinction is becoming less apparent. Since the JCE uses the same architecture as the JCA, the JCE should be more properly thought of as a subset of the JCA.
- The JCA within the JDK includes two software components:
- the framework that defines and supports cryptographic services for which providers supply implementations. This framework includes packages such as
java.security
,javax.crypto
,javax.crypto.spec
, andjavax.crypto.interfaces
. - the actual providers such as Sun, SunRsaSign, SunJCE, which contain the actual cryptographic implementations.
- the framework that defines and supports cryptographic services for which providers supply implementations. This framework includes packages such as
Throughout this document, the terms JCA by itself refers to the JCA framework. Whenever this document notes a specific JCA provider, it will be referred to explicitly by the provider name.
Engine Classes and Corresponding Service Provider Interface Classes
An engine class defines a cryptographic service in an abstract fashion (without a concrete implementation).
A cryptographic service is always associated with a particular algorithm or type. It either provides cryptographic operations (like those for digital signatures or message digests, ciphers or key agreement protocols); generates or supplies the cryptographic material (keys or parameters) required for cryptographic operations; or generates data objects (keystores or certificates) that encapsulate cryptographic keys (which can be used in a cryptographic operation) in a secure fashion.
For example, here are four engine classes:
- The
Signature
class provides access to the functionality of a digital signature algorithm. - A DSA
KeyFactory
class supplies a DSA private or public key (from its encoding or transparent specification) in a format usable by the initSign or initVerify methods, respectively, of a DSA Signature object. - The
Cipher
class provides access to the functionality of an encryption algorithm (such as DES) - the
KeyAgreement
class provides access to the functionality of a key agreement protocol (such as Diffie-Hellman)
The Java Cryptography Architecture encompasses the classes comprising the Security package that relate to cryptography, including the engine classes. Users of the API request and utilize instances of the engine classes to carry out corresponding operations. The JDK defines the following engine classes:
MessageDigest
- used to calculate the message digest (hash) of specified data.Signature
- used to sign data and verify digital signatures.KeyPairGenerator
- used to generate a pair of public and private keys suitable for a specified algorithm.KeyFactory
- used to convert opaque cryptographic keys of typeKey
into key specifications (transparent representations of the underlying key material), and vice versa.KeyStore
- used to create and manage a keystore. A keystore is a database of keys. Private keys in a keystore have a certificate chain associated with them, which authenticates the corresponding public key. A keystore also contains certificates from trusted entities.CertificateFactory
- used to create public key certificates and Certificate Revocation Lists (CRLs).AlgorithmParameters
- used to manage the parameters for a particular algorithm, including parameter encoding and decoding.AlgorithmParameterGenerator
- used to generate a set of parameters suitable for a specified algorithm.SecureRandom
- used to generate random or pseudo-random numbers.Cipher
: used to encrypt or decrypt some specified data.KeyAgreement
: used to execute a key agreement (key exchange) protocol between 2 or more parties.KeyGenerator
: used to generate a secret (symmetric) key suitable for a specified algorithm.Mac
: used to compute the message authentication code of some specified data.SecretKeyFactory
: used to convert opaque cryptographic keys of typeSecretKey
into key specifications (transparent representations of the underlying key material), and vice versa.ExemptionMechanism
: used to provide the functionality of an exemption mechanism such as key recovery, key weakening, key escrow, or any other (custom) exemption mechanism. Applications or applets that use an exemption mechanism may be granted stronger encryption capabilities than those which don't. However, please note that cryptographic restrictions are no longer required for most countries, and thus exemption mechanisms may only be useful in those few countries whose governments mandate restrictions.
Note: A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).
An engine class provides the interface to the functionality of a specific type of cryptographic service (independent of a particular cryptographic algorithm). It defines Application Programming Interface (API) methods that allow applications to access the specific type of cryptographic service it provides. The actual implementations (from one or more providers) are those for specific algorithms. For example, the Signature engine class provides access to the functionality of a digital signature algorithm. The actual implementation supplied in a SignatureSpi
subclass (see next paragraph) would be that for a specific kind of signature algorithm, such as SHA1 with DSA, SHA1 with RSA, or MD5 with RSA.
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.
Description of Architecture of Service Provider Interface
An instance of an engine class, the "API object", encapsulates (as a private field) an instance of the corresponding SPI class, the "SPI object". All API methods of an API object are declared "final", and their implementations invoke the corresponding SPI methods of the encapsulated SPI object. An instance of an engine class (and of its corresponding SPI class) is created by a call to the getInstance
factory method of the engine class.
The name of each SPI class is the same as that of the corresponding engine class, followed by "Spi". For example, the SPI class corresponding to the Signature engine class is the SignatureSpi class.
Each SPI class is abstract. To supply the implementation of a particular type of service and for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.
Another example of an engine class is the MessageDigest class, which provides access to a message digest algorithm. Its implementations, in MessageDigestSpi subclasses, may be those of various message digest algorithms such as SHA-1, MD5, or MD2.
As a final example, the KeyFactory engine class supports the conversion from opaque keys to transparent key specifications, and vice versa. See Key Specification Interfaces and Classes Required by Key Factories for details. The actual implementation supplied in a KeyFactorySpi subclass would be that for a specific type of keys, e.g., DSA public and private keys.
Steps to Implement and Integrate a Provider
Follow the steps below to implement a provider and integrate it into the JCA framework:
- Step 1: Write your Service Implementation Code
- Step 2: Give your Provider a Name
- Step 3: Write your Master Class, a subclass of Provider
- Step 4: Compile your Code
- Step 5: Place your Provider in a Jar File
- Step 6: Sign your JAR File
- Step 7: Prepare for Testing
- Step 8: Write and Compile your Test Programs
- Step 9: Run your Test Programs
- Step 10: Apply for U.S. Government Export Approval if Required
- Step 11: Document your Provider and its Supported Services
- Step 12: Make your Class Files and Documentation Available to Clients
Step 1: Write your Service Implementation Code
The first thing you need to do is to write the code that provides algorithm-specific implementations of the cryptographic services you want to support.
Note that your provider may supply implementations of cryptographic services already available in one or more of the security components of the JDK.
For cryptographic services not defined in JCA (For example; signatures and message digests), please refer to Java Cryptography Architecture Reference Guide.
For each cryptographic service you wish to implement, create a subclass of the appropriate SPI class. JCA defines the following engine classes:
SignatureSpi
MessageDigestSpi
KeyPairGeneratorSpi
SecureRandomSpi
AlgorithmParameterGeneratorSpi
AlgorithmParametersSpi
KeyFactorySpi
CertificateFactorySpi
KeyStoreSpi
CipherSpi
KeyAgreementSpi
KeyGeneratorSpi
MacSpi
SecretKeyFactorySpi
ExemptionMechanismSpi
(See Engine Classes and Corresponding SPI Classes in this document for information on the JCA and other cryptographic classes.)
In your subclass, you need to:
- Supply implementations for the abstract methods, whose names usually begin with
engine
. See Further Implementation Details and Requirements for additional information. - Ensure there is a public constructor without any arguments. Here's why: When one of your services is requested, Java Security looks up the subclass implementing that service, as specified by a property in your "master class" (see Step 3). Java Security then creates the
Class
object associated with your subclass, and creates an instance of your subclass by calling thenewInstance
method on thatClass
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.
Step 1.1: Additional JCA Provider Requirements and Recommendations for Encryption Implementations
When instantiating a provider's implementation (class) of a Cipher, KeyAgreement, KeyGenerator, MAC
or SecretKey
factory, the framework will determine the provider's codebase (JAR file) and verify its signature. In this way, JCA authenticates the provider and ensures that only providers signed by a trusted entity can be plugged into JCA. Thus, one requirement for encryption providers is that they must be signed, as described in later steps.
In addition, each provider should perform self-integrity checking to ensure that the JAR file containing its code has not been manipulated in an attempt to invoke provider methods directly rather than through JCA. For further information, see How a Provider Can Do Self-Integrity Checking.
In order for provider classes to become unusable if instantiated by an application directly, bypassing JCA, providers should implement the following:
- All SPI implementation classes in a provider package should be declared final (so that they cannot be subclassed), and their (SPI) implementation methods should be declared protected.
- All crypto-related helper classes in a provider package should have package-private scope, so that they cannot be accessed from outside the provider package.
For providers that may be exported outside the U.S., CipherSpi
implementations must include an implementation of the engineGetKeySize
method which, given a Key
, returns the key size. If there are restrictions on available cryptographic strength specified in jurisdiction policy files, each Cipher
initialization method calls engineGetKeySize
and then compares the result with the maximum allowable key size for the particular location and circumstances of the applet or application being run. If the key size is too large, the initialization method throws an exception.
Additional optional features that providers may implement are
- the
engineWrap
andengineUnwrap
methods ofCipherSpi
. Wrapping a key enables secure transfer of the key from one place to another. Information about wrapping and unwrapping keys is provided in the Wrapping and Unwrapping Keys section of the Java Cryptography Architecture Reference Guide. - one or more exemption mechanisms. An exemption mechanism is something such as key recovery, key escrow, or key weakening which, if implemented and enforced, may enable reduced cryptographic restrictions for an application (or applet) that uses it. For information on the requirements for apps that utilize exemption mechanisms, see How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide.
Step 2: Give your Provider a Name
Decide on a name for your provider. This is the name to be used by client applications to refer to your provider.
Step 3: Write your Master Class, a subclass of Provider
The third step is to create a subclass of the java.security.Provider
class.
Your subclass should be a final
class, and its constructor should
- call
super
, specifying the provider name (see Step 2), version number, and a string of information about the provider and algorithms it supports. For example:super("CryptoX", 1.0, "CryptoX provider v1.0, implementing " + "RSA encryption and key pair generation, and DES encryption.");
- set the values of various properties that are required for the Java Security API to look up the cryptographic services implemented by the provider. For each service implemented by the provider, there must be a property whose name is the type of service (for example; Signature, MessageDigest, Cipher, KeyAgreement) Signature, MessageDigest, KeyPairGenerator, SecureRandom, KeyFactory, KeyStore, CertificateFactory, AlgorithmParameterGenerator, AlgorithmParameters, Cipher, KeyAgreement, KeyGenerator, Mac, SecretKeyFactory, or ExemptionMechanism) followed by a period and the name of the algorithm to which the service applies. The property value must specify the fully qualified name of the class implementing the service.
The list below shows the various types of JCA services, where the actual algorithm name is substitued for algName:
Signature.algName
MessageDigest.algName
KeyPairGenerator.algName
SecureRandom.algName
AlgorithmParameterGenerator.algName
AlgorithmParameters.algName
KeyFactory.algName
CertificateFactory.algName
KeyStore.algName
Cipher.algName
KeyAgreement.algName
KeyGenerator.algName
Mac.algName
SecretKeyFactory.algName
ExemptionMechanism.algName
In all of these except
ExemptionMechanism
andCipher
,algName, certType
, orstoreType
is the "standard" name of the algorithm, certificate type, or keystore type. See Appendix A of the Java Cryptography Architecture Reference Guide for the standard names that should be used.)In the case of
ExemptionMechanism
, algName refers to the name of the exemption mechanism, which can be one of the following:KeyRecovery
,KeyEscrow
, orKeyWeakening
. Case does not matter.In the case of
Cipher
, algName may actually represent a transformation, and may be composed of an algorithm name, a particular mode, and a padding scheme. See Appendix A of the Java Cryptography Architecture Reference Guide for details.The value of each property must be the fully qualified name of the class implementing the specified algorithm, certificate type, or keystore type. That is, it must be the package name followed by the class name, where the two are separated by a period.
As an example, the default provider named SUN implements the Digital Signature Algorithm (whose standard name is
SHA1withDSA
) in a class namedDSA
in thesun.security.provider
package. Its subclass ofProvider
(which is the Sun class in thesun.security.provider package
) sets theSignature.SHA1withDSA
property to have the valuesun.security.provider.DSA
via the following:put("Signature.SHA1withDSA", "sun.security.provider.DSA")
The list below shows more properties that can be defined for the various types of services, where the actual algorithm name is substitued for algName, certificate type for certType, keystore type for storeType, and attribute name for attrName:
Signature.algName [one or more spaces] attrName
MessageDigest.algName [one or more spaces] attrName
KeyPairGenerator.algName [one or more spaces] attrName
SecureRandom.algName [one or more spaces] attrName
KeyFactory.algName [one or more spaces] attrName
CertificateFactory.certType [one or more spaces] attrName
KeyStore.storeType [one or more spaces] attrName
AlgorithmParameterGenerator.algName [one or more spaces] attrName
AlgorithmParameters.algName [one or more spaces] attrName
Cipher.algName [one or more spaces] attrName
KeyAgreement.algName [one or more spaces] attrName
KeyGenerator.algName [one or more spaces] attrName
Mac.algName [one or more spaces] attrName
SecretKeyFactory.algName [one or more spaces] attrName
ExemptionMechanism.algName [one or more spaces] attrName
In each of these, algName, certType, storeType,
or attrName
is the "standard" name of the algorithm, certificate type, keystore type, or attribute. (See Appendix A of the Java Cryptography Architecture Reference Guide for the standard names that should be used.)
For a property in the above format, the value of the property must be the value for the corresponding attribute. (See Appendix A of the Java Cryptography Architecture API Specification & Reference for the definition of each standard attribute.)
As an example, the default provider named "SUN" implements the SHA1withDSA Digital
Signature Algorithm in software. In the master class for the provider "SUN", it sets the Signature.SHA1withDSA ImplementedIn
to have the value Software
via the following:
put("Signature.SHA1withDSA ImplementedIn", "Software")
For further master class property setting examples, see Appendix A to view the current Sun.java source file or Appendix B to see the SunJCE provider. These files show how the Sun and SunJCE providers set properties.
Step 3.1: Additional Steps for Cipher Implementations
As mentioned above, in the case of a Cipher
property, algName may actually represent a transformation. A transformation is a string that describes the operation (or set of operations) to be performed by a Cipher
object on some given input. A transformation always includes the name of a cryptographic algorithm (e.g., DES), and may be followed by a mode and a padding scheme.
A transformation is of the form:
- algorithm/mode/padding, or
- algorithm
(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("DES/CBC/PKCS5Padding");
When requesting a block cipher in stream cipher mode (for example; DES
in CFB
or OFB
mode), a client may optionally specify the number of bits to be processed at a time, by appending this number to the mode name as shown in the following sample transformations:
Cipher c1 = Cipher.getInstance("DES/CFB8/NoPadding"); Cipher c2 = Cipher.getInstance("DES/OFB32/PKCS5Padding");
If a number does not follow a stream cipher mode, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits.)
A provider may supply a separate class for each combination of algorithm/mode/padding. Alternatively, a provider may decide to provide more generic classes representing sub-transformations corresponding to algorithm or algorithm/mode or algorithm//padding (note the double slashes); in this case the requested mode and/or padding are set automatically by the getInstance
methods of Cipher
, which invoke the engineSetMode
and engineSetPadding
methods of the provider's subclass of CipherSpi
.
That is, a Cipher
property in a provider master class may have one of the formats shown in the table below.
Cipher Property Format |
Description |
---|---|
Cipher. algName |
A provider's subclass of CipherSpi implements algName with pluggable mode and padding |
Cipher. algName/mode |
A provider's subclass of CipherSpi implements algName in the specified mode, with pluggable padding |
Cipher. algName//padding |
A provider's subclass of CipherSpi implements algName with the specified padding, with pluggable mode |
Cipher. algName/mode/padding |
A provider's subclass of CipherSpi implements algName with the specified mode and padding |
(See Appendix A of the Java Cryptography Architecture Reference Guide for the standard algorithm names, modes, and padding schemes that should be used.)
For example, a provider may supply a subclass of CipherSpi
that implements DES/ECB/PKCS5Padding, one that implements DES/CBC/PKCS5Padding, one that implements DES/CFB/PKCS5Padding, and yet another one that implements DES/OFB/PKCS5Padding. That provider would have the following Cipher
properties in its master class:
Cipher.DES/ECB/PKCS5Padding
Cipher.DES/CBC/PKCS5Padding
Cipher.DES/CFB/PKCS5Padding
Cipher.DES/OFB/PKCS5Padding
Another provider may implement a class for each of the above modes (i.e., one class for ECB, one for CBC, one for CFB, and one for OFB), one class for PKCS5Padding, and a generic DES class that subclasses from CipherSpi
. That provider would have the following Cipher
properties in its master class:
Cipher.DES
Cipher.DES SupportedModes
Example: "ECB|CBC|CFB|OFB"Cipher.DES SupportedPaddings
Example: "NOPADDING|PKCS5Padding"
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":
- 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 aNoSuchAlgorithmException
exception.
The getInstance
factory method of the Cipher
engine class follows these rules in order to instantiate a provider's implementation of CipherSpi
for a transformation of the form "algorithm/mode/padding":
- 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. - Check if the provider has registered a subclass of
CipherSpi
for the sub-transformation "algorithm/mode".
If the answer is YES, instantiate it, and callengineSetPadding(padding)
on the new instance.
If the answer is NO, go to the next step. - 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 callengineSetMode(mode)
on the new instance.
If the answer is NO, go to the next step. - Check if the provider has registered a subclass of
CipherSpi
for the sub-transformation "algorithm".
If the answer is YES, instantiate it, and callengineSetMode(mode)
andengineSetPadding(padding)
on the new instance.
If the answer is NO, throw aNoSuchAlgorithmException
exception.
Step 4: Compile your Code
After you have created your implementation code (Step 1), given your provider a name (Step 2), and created the master class (Step 3), use the Java compiler to compile your files.
Step 5: Place Your Provider in a JAR File
Place your provider code in a JAR file, in preparation for signing it in the next step. For more information on the jar tool, see jar (for Solaris, Linux, or Mac OS X) (for Microsoft Windows).
jar cvf <JAR file name> <list of classes, separated by spaces>
This command creates a JAR file with the specified name containing the specified classes.
Step 6: Sign your JAR File
If your provider is supplying encryption algorithms through the Cipher KeyAgreement, KeyGenerator, Mac,
or SecretKeyFactory
classes, you will need to sign your JAR file so that the JCA can authenticate the code at runtime. For details, see Step 1a. If you are NOT providing an implementation of this type you can skip this step.
Step 6.1: Get a Code-Signing Certificate
The next step is to request a code-signing certificate so that you can use it to sign your provider prior to testing. The certificate will be good for both testing and production. It will be valid for 5 years.
Below are the steps you should use to get a code-signing certificate. For more information on the keytool tool, see keytool (for Solaris, Linux, or Mac OS X) (for Microsoft Windows).
- Use keytool to generate a DSA keypair, using DSA algorithm as an example:
keytool -genkeypair -alias <alias> \ -keyalg DSA -keysize 1024 \ -dname "cn=<Company Name>, \ ou=Java Software Code Signing,\ o=Sun Microsystems Inc" \ -keystore <keystore file name>\ -storepass <keystore password>
This will generate a DSA keypair (a public key and an associated private key) and store 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.
The option values in angle brackets ("<" and ">") represent the actual values that must be supplied. For example,
<alias>
must be replaced with whatever alias name you wish to be used to refer to the newly-generated keystore entry in the future, and<keystore file name>
must be replaced with the name of the keystore to be used. Note: 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 fullkeytool -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.
- Use keytool to generate a certificate signing request.
keytool -certreq -alias <alias> \ -file <csr file name> \ -keystore <keystore file name> \ -storepass <keystore password>
Here,<alias>
is the alias for the DSA keypair entry created in the previous step. This command generates a Certificate Signing Request (CSR), using the PKCS#10 format. It stores the CSR in the file whose name is specified in<csr file name>
. - Send the CSR, contact information, and other required documentation to the JCA Code Signing Certification Authority. See JCA Code Signing Certification Authority for contact info.
- After the JCA Code Signing Certification Authority has received your email message, they will send you a request number via email. Once you receive this request number, you should print, fill out and send the Certification Form for CSPs. See Sending Certification Form for CSPs for contact information.
- Use keytool to import the certificates received from the CA.
Once you have received the two certificates from the JCA Code Signing Certification Authority, you can use keytool to import them into your keystore.
First import the CA's certificate as a "trusted certificate":keytool -import -alias <alias for the CA cert> \ -file <CA cert file name> \ -keystore <keystore file name> \ -storepass <keystore password>
Then import the code-signing certificate:keytool -import -alias <alias> \ -file <code-signing cert file name> \ -keystore <keystore file name> \ -storepass <keystore password>
Here,<alias>
is the same alias as that which you created in step 1 where you generated a DSA keypair. This command replaces the self-signed certificate in the keystore entry specified by<alias>
with the one signed by the JCA Code Signing Certification Authority.
Now that you have in your keystore a certificate from an entity trusted by JCA (the JCA Code Signing Certification Authority), you can place your provider code in a JAR file (Step 5) and then use that certificate to sign the JAR file (Step 6.2).
Step 6.2: Sign Your Provider
Sign the JAR file created in step five with the code-signing certificate obtained in Step 6. For more information on the jarsigner tool, see jarsigner (for Solaris, Linux, or Mac OS X) (for Microsoft Windows).
jarsigner -keystore <keystore file name> \ -storepass <keystore password> \ <JAR file name> <alias>
Here, <alias>
is the alias into the keystore for the entry containing the code-signing certificate received from the JCA Code Signing Certification Authority (the same alias as that specified in the commands in Step 6.1).
You can test verification of the signature via the following:
jarsigner -verify <JAR file name>
The text "jar verified" will be displayed if the verification was successful.
Note: If you bundle a signed JCE provider as part of an RIA (applet or webstart application), for the best user experience, you should apply a second signature to the JCE provider JAR with the same certificate/key that you used to sign the applet or webstart application. See the Java Platform, Standard Edition Deployment Guide for more information on deploying RIAs, and the jarsigner (Solaris, Linux, or Mac OS X or Windows) man page for information on applying multiple signatures to a JAR file.
Step 7: Prepare for Testing
The next steps describe how to install and configure your new provider so that it is available via the JCA.
Step 7.1: Install the Provider
In order to prepare for testing your provider, you must install it in the same manner as will be done by clients wishing to use it. The installation enables Java Security to find your algorithm implementations when clients request them.
Installing a provider is done in two steps: installing the provider package classes, and configuring the provider.
Installing the Provider Classes
The first thing you must do is make your classes available so that they can be found when requested. You ship your provider classes as a JAR (Java ARchive) file.
There are a two possible ways to install provider classes:
- Install the JAR file containing the provider classes as an installed or bundled extension.
- Place the JAR file containing the provider classes in your CLASSPATH.
The provider JAR file will be considered an installed extension if it is placed in the standard place for the JAR files of an installed extension:
- Solaris, Linux, or Mac OS X:
<java-home>/lib/ext
- Windows:
<java-home>\lib\ext
Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the Java Runtime Environment (JRE) or the jre directory in the Java SE (JDK) software. For example, if you have the JDK installed on Solaris, Linux, or Mac OS X in a directory named /home/user1/jdk
, or on Microsoft Windows in a directory named C:\jdk
, then you need to install the JAR file in the following directory:
- Solaris, Linux, or Mac OS X:
/home/user1/jdk/jre/lib/ext
- Windows:
C:\jdk\jre\lib\ext
Similarly, if you have the JRE installed on Solaris, Linux, or Mac OS X in a directory named /home/user1/jre
, or on Microsoft Windows in a directory named C:\jre
, you need to install the JAR file in the following directory:
- Solaris, Linux, or Mac OS X:
/home/user1/jre/lib/ext
- Windows:
C:\jre\lib\ext
For more information on installed extensions, see Installed Extensions.
For more information on bundled extensions, see Bundled Extensions.
Configuring the Provider
The next step is to add the provider to your list of approved providers. This is done statically by editing the security properties file
- Solaris, Linux, or Mac OS X:
<java-home>/lib/security/java.security
- Windows:
<java-home>\lib\security\java.security
Here <java-home> refers to the directory where the JRE was installed. For example, if you have the JDK installed on Solaris, Linux, or Mac OS X in a directory named /home/user1/jdk
, or on Microsoft Windows in a directory named C:\jdk
, then you need to edit the following file:
- Solaris, Linux, or Mac OS X:
/home/user1/jdk/jre/lib/security/java.security
- Windows:
C:\jdk\jre\lib\security\java.security
Similarly, if you have the JRE installed on Solaris, Linux, or Mac OS X in a directory named /home/user1/jre
, or on Windows in a directory named C:\jre
, then you need to edit this file:
- Solaris, Linux, or Mac OS X:
/home/user1/jre/lib/security/java.security
- Windows:
C:\jre\lib\security\java.security
For each provider, this file should have a statement of the following form:
security.provider.n=masterClassName
This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms when no specific provider is requested. The order is 1-based; 1 is the most preferred, followed by 2, and so on.
masterClassName must specify the fully qualified name of the provider's "master class", which you implemented in Step 3. This class is always a subclass of the Provider class.
security.provider.2=sun.security.provider.Sun security.provider.3=sun.security.rsa.SunRsaSign security.provider.4=sun.security.provider.SunJCE
(The Sun provider's master class is the Sun
class in the sun.security.provider
package.)
The JCA provider SunJCE and other security-related providers shipped with the Java platform are also automatically configured as static providers.
To utilize another JCA provider, add a line registering the alternate provider, giving it a lower preference order than the SUN and SunRsaSign providers.
Suppose that your master class is the CryptoX
class in the com.cryptox.provider
package, and that you would like to make your provider the fourth preferred provider. To do so, edit the java.security
file as seen below:
security.provider.2=sun.security.provider.Sun security.provider.3=sun.security.rsa.SunRsaSign security.provider.4=com.cryptox.provider.CryptoX security.provider.5=sun.security.provider.SunJCE
Note: Providers may also be registered dynamically. To do so, a program (such as your test program, to be written in Step 8) can call either the addProvider
or insertProviderAt
method in the Security
class. This type of registration is not persistent and can only be done by code which is granted the following permission:
java.security.SecurityPermission "insertProvider.{name}"
where {name}
is replaced by the actual provider name.
For example, if the provider name is "MyJCE" and if the provider's code is in the myjce_provider.jar
file in the /localWork
directory, then here is a sample policy file grant
statement granting that permission:
grant codeBase "file:/localWork/myjce_provider.jar" { permission java.security.SecurityPermission "insertProvider.MyJCE"; };
Step 7.2: Set Provider Permissions
Whenever providers are not installed extensions, permissions must be granted for when applets or applications are run while a security manager is installed. There is typically a security manager installed whenever an applet is running, and a security manager may be installed for an application either via code in the application itself or via a command-line argument. Permissions do not need to be granted to installed extensions, since the default system policy file grants all permissions to installed extensions.
Whenever a client does not install your provider as an installed extension, your provider may need the following permissions granted to it in the client environment:
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.
To ensure your provider works when a security manager is installed and the provider is not an installed extension, you need to test such an installation and execution environment. In addition, prior to testing you need to grant appropriate permissions to your provider and to any other providers it uses. For example, a sample statement granting permissions to a provider whose name is "MyJCE" and whose code is in myjce_provider.jar
appears below. Such a statement could appear in a policy file. In this example, the myjce_provider.jar
file is assumed to be in the /localWork
directory.
grant codeBase "file:/localWork/myjce_provider.jar" { permission java.lang.RuntimePermission "getProtectionDomain"; permission java.security.SecurityPermission "putProviderProperty.MyJCE"; };
Step 8: Write and Compile your Test Programs
Write and compile one or more test programs that test your provider's incorporation into the Security API as well as the correctness of its algorithm(s). Create any supporting files needed, such as those for test data to be encrypted.
The first tests your program should perform are ones to ensure that your provider is found, and that its name, version number, and additional information is as expected. To do so, you could write code like the following, substituting your provider name for MyPro
:
import java.security.*; Provider p = Security.getProvider("MyPro"); System.out.println("MyPro provider name is " + p.getName()); System.out.println("MyPro provider version # is " + p.getVersion()); System.out.println("MyPro provider info is " + p.getInfo());
Next, you should ensure that your services are found. For instance, if you implemented the DES 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("DES", "MyPro"); System.out.println("My Cipher algorithm name is " + c.getAlgorithm());
If you don't specify a provider name in the call to getInstance
, all registered providers will be searched, in preference order (see Configuring the Provider), until one implementing the algorithm is found.
If your provider implements an exemption mechanism, you should write a test applet or application that uses the exemption mechanism. Such an applet/application also needs to be signed, and needs to have a "permission policy file" bundled with it. See How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide for complete information on creating and testing such an application.
Step 9: Run your Test Programs
Run your test program(s). Debug your code and continue testing as needed. If the Java Security API cannot seem to find one of your algorithms, review the steps above and ensure they are all completed.
Be sure to include testing of your programs using different installation options (e.g. making the provider an installed extension or placing it on the class path) and execution environments (with or without a security manager running). Installation options are discussed in Step 7.1. In particular, you need to ensure your provider works when a security manager is installed and the provider is not an installed extension -- and thus the provider must have permissions granted to it; therefore, you need to test such an installation and execution environment, after granting required permissions to your provider and to any other providers it uses, as described in Step 7.2.
If you find during testing that your code needs modification, make the changes, recompile (Step 4), place the updated provider code in a JAR file (Step 6), sign the JAR file if necessary (Step 6.2), re-install the provider (Step 7.1), if needed fix or add to the permissions (Step 7.2), and then re-test your programs. Repeat these steps as needed.
Step 10: Apply for U.S. Government Export Approval If Required
All U.S. vendors whose providers may be exported outside the U.S. should apply to the Bureau of Industry and Security in the U.S. Department of Commerce for export approval. Please consult your export counsel for more information.
Note: If your provider calls Cipher.getInstance()
and the returned Cipher
object needs to perform strong cryptography regardless of what cryptographic strength is allowed by the user's downloaded jurisdiction policy files, you should include a copy of the cryptoPerms
permission policy file which you intend to bundle in the JAR file for your provider and which specifies an appropriate permission for the required cryptographic strength. The necessity for this file is just like the requirement that applets and applications "exempt" from cryptographic restrictions must include a cryptoPerms
permission policy file in their JAR file. For more information on the creation and inclusion of such a file, see How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide.
Here are two URLs that may be useful:
- U.S. Department of Commerce: http://www.commerce.gov
- Bureau of Industry and Security: http://www.bis.doc.gov
Step 11: Document your Provider and its Supported Services
The next step is to write documentation for your clients. At the minimum, you need to specify:
- the name programs should use to refer to your provider. Note: As of this writing, provider name searches are case-sensitive. That is, if your master class specifies your provider name as "CryptoX" but a user requests "CRYPTOx", your provider will not be found. This behavior may change in the future, but for now be sure to warn your clients to use the exact case you specify.
- the types of algorithms and other services implemented by your provider.
- instructions for installing the provider, similar to those provided in Step 7.1, except that the information and examples should be specific to your provider.
- the permissions your provider will require if it is not installed as an installed extension and if a security manager is run, as described in Step 7.2.
In addition, your documentation should specify anything else of interest to clients, such as any default algorithm parameters.
Message Digests and MACs
For each Message Digest and MAC algorithm, indicate whether or not your implementation is cloneable. This is not technically necessary, but it may save clients some time and coding by telling them whether or not intermediate Message Digests or MACs may be possible through cloning. Clients who do not know whether or not a MessageDigest
or Mac
implementation is cloneable can find out by attempting to clone the object and catching the potential exception, as illustrated by the following example:
try { // try and clone it /* compute the MAC for i1 */ mac.update(i1); byte[] i1Mac = mac.clone().doFinal(); /* compute the MAC for i1 and i2 */ mac.update(i2); byte[] i12Mac = mac.clone().doFinal(); /* compute the MAC for i1, i2 and i3 */ mac.update(i3); byte[] i123Mac = mac.doFinal(); } catch (CloneNotSupportedException cnse) { // have to use an approach not involving cloning }
where:
mac
is the MAC object they received when they requested one via a call toMac.getInstance
,i1
,i2
andi3
are input byte arrays, and- they want to calculate separate hashes for:
i1
i1 and i2
i1, i2, and i3
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 1024 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 1024 bits for the generation of Diffie-Hellman parameters, the Sun provider a default modulus prime size of 1024 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 SHA1withDSA signature algorithm supplied by the "SUN" provider encodes the signature as a standard ASN.1 SEQUENCE
of two integers, r
and s
.
Random Number Generation (SecureRandom) Algorithms
For a random number generation algorithm, provide information regarding how "random" the numbers generated are, and the quality of the seed when the random number generator is self-seeding. Also note what happens when a SecureRandom object (and its encapsulated SecureRandomSpi implementation object) is deserialized: If subsequent calls to the nextBytes
method (which invokes the engineNextBytes
method of the encapsulated SecureRandomSpi object) of the restored object yield the exact same (random) bytes as the original object would, then let users know that if this behaviour is undesirable, they should seed the restored random object by calling its setSeed
method.
Certificate Factories
A provider should document what types of certificates (and their version numbers, if relevant), can be created by the factory.
Keystores
A provider should document any relevant information regarding the keystore implementation, such as its underlying data format.
Step 12: Make your Class Files and Documentation Available to Clients
After writing, configuring, testing, installing and documenting your provider software, make documentation available to your customers.
How a Provider Can Do Self-Integrity Checking
Each provider should do self-integrity checking to ensure that the JAR file containing its code has not been tampered with, for example in an attempt to invoke provider methods directly rather than through JCA. Providers that provide implementations for encryption services (Cipher, KeyAgreement, KeyGenerator, MAC
or SecretKey
factory) must be digitally signed and should be signed with a certificate issued by "trusted" Certification Authorities. Currently, the following two Certification Authorities are considered "trusted":
- Sun Microsystems' JCA Code Signing CA, and
- IBM JCA Code Signing CA.
Please refer to Step 6.2 for detailed information on how to get a code-signing certificate from Sun Microsystems' JCA Code Signing CA and the certificate of that CA.
After getting the signing certificate from above Certification Authority, provider packages should embed within themselves the bytes for its own signing certificate, for example in an array like the bytesOfProviderCert
array referred to in the Identifying Each of the Signers and Determining If One is Trusted section below. At runtime, the embedded certificate will be used in determining whether or not the provider code is authentic.
The basic approach a provider can use to check its own integrity is:
- Determine the URL of the JAR file containing the provider code, and
- Verify the JAR file's digital signatures to ensure that at least one signer of each entry of the JAR file is trusted.
Each of these steps is described in the following sections:
- Notes on the Sample Code
- Finding the Provider JAR File: Basics
- Verifying the Provider JAR File: Basics
- Verifying Signatures
- Ensuring Signers Are Trusted
Note: The sample code MyJCE.java
is a complete code example that implements these steps. You can download this code for your reference. The Notes on the Sample Code section traces how these concepts are implemented in the sample code.
IMPORTANT NOTE: In the unbundled version of JCE 1.2.x, (used with JDKs 1.2.x and 1.3.x), providers needed to include code to authenticate the JCA framework to assure themselves of the integrity and authenticity of the JCA that they plugged into. In JDK 6 and later, this is no longer necessary.
One implication is that a provider written just for JCE 1.2.2 will not work in JDK 6 because the provider's JCE framework authentication check will not work; the JCE framework code is no longer where the provider expects it to be. If you want your provider to work only with JDK 6, it should not have code to authenticate the JCE framework. On the other hand, if you want your provider to work both with JCE 1.2.2 and with JDK 6, then add a conditional statement. This way the provider code to authenticate the JCE framework is executed only when the provider is run with JCE 1.2.2. The following is sample code:
Class cipherCls = Class.forName("javax.crypto.Cipher"); CodeSource cs = cipherCls.getProtectionDomain().getCodeSource(); if (cs != null) { // Authenticate JCE framework
. . . }