Provider.Service Classjava.security Properties
FileThe 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.
Figures 1 and 2 illustrate these options for requesting an MD5 message digest implementation. Both figures show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In Figure 1, 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 Figure 2, 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.
Figure 1: Provider searching Figure 2: Specific provider requested
Figures 1 and 2 illustrate these options for requesting an MD5 message digest implementation. Both figures show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In Figure 1, 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 Figure 2, 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.
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.
Sun's version of the Java runtime environment comes standard with a default provider, named "SUN". Other Java runtime environments may not necessarily supply the "SUN" provider.
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.
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
java.security, javax.crypto,
javax.crypto.spec, and
javax.crypto.interfaces.
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.
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:
Signature class provides access to the
functionality of a digital signature algorithm.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.Cipher class provides access to the functionality
of an encryption algorithm (such as DES)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 type Key
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.CipherKeyAgreementKeyGeneratorMacSecretKeyFactorySecretKey into key
specifications (transparent representations of the underlying
key material), and vice versa.
ExemptionMechanismNote: 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.
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.
Follow the steps below to implement a provider and integrate it into the JCA framework:
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 KeyGeneratorSpiMacSpi 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:
engine. See Further Implementation Details and
Requirements for additional information.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. When instantiating a provider's implementation (class) of a
Cipher, KeyAgreement, KeyGenerator, MAC or
SecretKey factory, the framework will determine the
provider's codebase (JAR file) and verify its signature. In this way,
JCA authenticates the provider and ensures that only providers signed
by a trusted entity can be plugged into JCA. Thus, one requirement for
encryption providers is that they must be signed, as described in later
steps.
In addition, each provider should perform self-integrity checking to ensure that the JAR file containing its code has not been manipulated in an attempt to invoke provider methods directly rather than through JCA. For further information, see How a Provider Can Do Self-Integrity Checking.
In order for provider classes to become unusable if instantiated by an application directly, bypassing JCA, providers should implement the following:
For providers that may be exported outside the U.S.,
CipherSpi implementations must include an implementation
of the engineGetKeySize method which, given a
Key, returns the key size. If there are restrictions on
available cryptographic strength specified in jurisdiction policy
files, each Cipher initialization method calls
engineGetKeySize and then compares the result with the
maximum allowable key size for the particular location and
circumstances of the applet or application being run. If the key size
is too large, the initialization method throws an exception.
Additional optional features that providers may implement are
engineWrap and engineUnwrap
methods of CipherSpi.
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.
Decide on a name for your provider. This is the name to be used by client applications to refer to your 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
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.");
The list below shows the various types of JCA services, where the actual algorithm name is substitued for algName:
Signature.algNameMessageDigest.algNameKeyPairGenerator.algName SecureRandom.algNameAlgorithmParameterGenerator.algName AlgorithmParameters.algName KeyFactory.algNameCertificateFactory.algNameKeyStore.algName Cipher.algName KeyAgreement.algName KeyGenerator.algName Mac.algName SecretKeyFactory.algName ExemptionMechanism.algName In all of these except ExemptionMechanism and
Cipher, algName, certType , or
storeType 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, or
KeyWeakening. 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 named DSA in the
sun.security.provider package. Its subclass of
Provider (which is the Sun class in the
sun.security.provider package) sets the
Signature.SHA1withDSA property to have the value
sun.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] attrNameMessageDigest.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] attrNameCertificateFactory.certType [one or more spaces]
attrName KeyStore.storeType [one or more spaces] attrNameAlgorithmParameterGenerator.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.
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:
(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":
CipherSpi
for the specified "algorithm".NoSuchAlgorithmException
exception.
The getInstance factory method of the Cipher
engine class follows these rules in order to instantiate a provider's
implementation of CipherSpi for a
transformation of the form "algorithm/mode/padding":
CipherSpi
for the specified "algorithm/mode/padding" transformation.
CipherSpi for the sub-transformation
"algorithm/mode".
engineSetPadding(padding) on the new instance.
CipherSpi for the sub-transformation
"algorithm//padding" (note the double slashes).
engineSetMode(mode) on the new instance.
CipherSpi for the sub-transformation "algorithm".
engineSetMode(mode) and
engineSetPadding(padding) on the new
instance.
NoSuchAlgorithmException exception.
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.
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) (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.
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.
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) (for Microsoft Windows).
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>
<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 be
myTestAlias, specify the -alias
option as follows:
-alias myTestAliasIf you specify a keystore that doesn't yet exist, it will be created.
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.
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>.
Request a Certificate for Signing a JCA Provider
Put the contact information in the body of the message and send the CSR
file as a plain text attachment to the message. If your mail tool has
an option for specifying the encoding format to be used for
attachments, select the "MIME" option.All of the above information is required.
You can also fax paperwork as follows:
Fax #: 408-668-0918
Subject Line: CSR #___
Attention: Encryption Export
Sun Microsystems, Inc.
International Trade Services/Export Compliance
After the JCA Code Signing Certification Authority has received both
your email message and the required form, they will authenticate you,
the requester. Then they will create and sign a code-signing
certificate valid for 5 years. You will receive an email message
containing two plain-text file attachments: one file containing this
code-signing certificate and another file containing its own CA
certificate, which authenticates its public key. Please also allow
five business days from receipt of your request for
processing.
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).
Sign the JAR file created step five with the code-signing certificate obtained in Step 6. For more information on the jarsigner tool, see jarsigner (for Solaris) (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.
The next steps describe how to install and configure your new provider so that it is available via the JCA.
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.
The first thing you must do is make your classes available so that they can be found when requested. You ship your provider classes as a JAR (Java ARchive) file.
There are a two possible ways to install provider classes:
The provider JAR file will be considered an installed extension if it is placed in the standard place for the JAR files of an installed extension:
<java-home>/lib/ext [Solaris]
<java-home>\lib\ext [Windows]
Here <java-home> refers to the directory
where the runtime software is installed, which is the top-level
directory of the JavaTM 2 Runtime
Environment (JRE) or the jre directory in the JavaTM SE (JDK) software. For example, if you have
JDK 6 installed on Solaris in a directory named
/home/user1/jdk1.6.0, or on Microsoft Windows in a
directory named C:\jdk1.6.0, then you need to install the
JAR file in the following directory:
/home/user1/jdk1.6.0/jre/lib/ext [Solaris]
C:\jdk1.6.0\jre\lib\ext [Windows]
Similarly, if you have JRE 6 installed on Solaris
in a directory named /home/user1/jre1.6.0,
or on Microsoft Windows in a directory named C:\jre1.6.0,
you need to install the JAR file in the following directory:
/home/user1/jre1.6.0/lib/ext [Solaris]
C:\jre1.6.0\lib\ext [Windows]
For more information on installed extensions, see Installed Extensions.
For more information on bundled extensions, see Bundled Extensions.
The next step is to add the provider to your list of approved providers. This is done statically by editing the security properties file
<java-home>/lib/security/java.security [Solaris]
<java-home>\lib\security\java.security [Windows]
Here <java-home> refers to the directory
where the JRE
was installed. For example, if you have JDK 6 installed
on Solaris in a directory named /home/user1/jdk1.6.0,
or on Microsoft indows in a directory named C:\jdk1.6.0,
then you
need to edit the following file:
/home/user1/jdk1.6.0/jre/lib/security/java.security [Solaris]
C:\jdk1.6.0\jre\lib\security\java.security [Windows]
Similarly, if you have the JRE 6 installed on Solaris in a directory
named /home/user1/jre1.6.0, or on Windows in a directory
named C:\jre1.6.0, then you need to edit this file:
/home/user1/jre1.6.0/lib/security/java.security [Solaris]
C:\jre1.6.0\lib\security\java.security [Windows]
For each provider, this file should have a statement of the following form:
security.provider.n=masterClassName
This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms when no specific provider is requested. The order is 1-based; 1 is the most preferred, followed by 2, and so on.
masterClassName must specify the fully qualified name of the provider's "master class", which you implemented in Step 3. This class is always a subclass of the Provider class.
Java comes standard with providers named
SUN, SunRsaSign, and SunJCE which are
automatically configured as a static provider in the
java.security properties file, as follows:
security.provider.2=sun.security.provider.Sun
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=sun.security.provider.SunJCE
(The Sun provider's master class is the Sun
class in the sun.security.provider
package.)
The JCA provider SunJCE and other security-related providers shipped with the Java platform are also automatically configured as static providers.
To utilize another JCA provider, add a line registering the alternate provider, giving it a lower preference order than the SUN and SunRsaSign providers.
Suppose that your master class is the CryptoX
class in the
com.cryptox.provider package,
and that you would like to make your provider the fourth
preferred provider. To do so, edit the java.security
file as seen below:
security.provider.2=sun.security.provider.Sun
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=com.cryptox.provider.CryptoX
security.provider.5=sun.security.provider.SunJCE
Note: Providers may also be registered dynamically. To
do so, a program (such as your test program, to be written in Step 8) can call either the addProvider
or
insertProviderAt method in the Security
class.
This type of registration is not persistent and can only be
done by code which is granted the following permission:
java.security.SecurityPermission "insertProvider.{name}"
where {name} is replaced by the actual provider
name.
For example, if the provider name is "MyJCE" and if the
provider's code is in the myjce_provider.jar file in the
/localWork directory, then here is a sample policy
file grant statement granting that permission:
grant codeBase "file:/localWork/myjce_provider.jar" {
permission java.security.SecurityPermission
"insertProvider.MyJCE";
};
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";
};
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.
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.
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:
The next step is to write documentation for your clients. At the minimum, you need to specify:
In addition, your documentation should specify anything else of
interest to clients, such as any default algorithm parameters.
Message Digests and MACs
For each Message Digest and MAC algorithm, indicate whether or
not your implementation is cloneable. This is not technically
necessary, but it may save clients some time and coding by telling them
whether or not intermediate Message Digests or MACs may be possible
through cloning. Clients who do not know whether or not a
MessageDigest or Mac implementation is
cloneable can find out by attempting to clone the object and catching
the potential exception, as illustrated by the following example:
try {
// try and clone it
/* compute the MAC for i1 */
mac.update(i1);
byte[] i1Mac = mac.clone().doFinal();
/* compute the MAC for i1 and i2 */
mac.update(i2);
byte[] i12Mac = mac.clone().doFinal();
/* compute the MAC for i1, i2 and i3 */
mac.update(i3);
byte[] i123Mac = mac.doFinal();
} catch (CloneNotSupportedException cnse) {
// have to use an approach not involving cloning
}
where:
mac is the MAC object they
received when they requested one via a call to Mac.getInstance,
i1,
i2 and i3 are input byte arrays, and
i1
i1 and i2
i1, i2, and i3
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.
A provider should document all the key specifications supported by its (secret-)key factory.
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.
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.
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.
A provider should document what types of certificates (and their version numbers, if relevant), can be created by the factory.
A provider should document any relevant information regarding the keystore implementation, such as its underlying data format.
After writing, configuring, testing, installing and documenting your provider software, make documentation available to your customers.
Each provider should do self-integrity checking to ensure that the
JAR file containing its code has not been tampered with, for example in
an attempt to invoke provider methods directly rather than through
JCA. Providers that provide implementations for encryption services
(Cipher, KeyAgreement, KeyGenerator, MAC or
SecretKey factory) must be digitally signed and should be
signed with a certificate issued by "trusted" Certification
Authorities. Currently, the following two Certification Authorities are
considered "trusted":
Please refer to Step 6.2 for detailed information on how to get a code-signing certificate from Sun Microsystems' JCA Code Signing CA and the certificate of that CA.
After getting the signing certificate from above Certification
Authority, provider packages should embed within themselves the bytes
for its own signing certificate, for example in an array like the
bytesOfProviderCert array referred to in the Identifying Each of the Signers and Determining If
One is Trusted section below. At runtime, the embedded certificate
will be used in determining whether or not the provider code is
authentic.
The basic approach a provider can use to check its own integrity is:
Each of these steps is described in the following sections:
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, 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 the 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 the 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
. . .
}
The URL for the provider's JAR file can be
obtained by determining the provider's CodeSource and
then
calling the getLocation method on the CodeSource.
URL providerURL = (URL) AccessController.doPrivileged(
new PrivilegedAction) {
public Object run() {
CodeSource cs =
MyJCE.class.getProtectionDomain().getCodeSource();
return cs.getLocation();
}
});
Once you have the URL for the provider's JAR file, you can
create a java.util.jar.JarFile
referring to the JAR file. This instance is needed in the step for verifying the Provider JAR file.
To create the JAR file, first open a connection to the
specified URL by calling its openConnection method. Since
the URL is a JAR URL, the type is
java.net.JarURLConnection. Here's the basic code:
// Prep the url with the appropriate protocol.
jarURL =
url.getProtocol().equalsIgnoreCase("jar") ? url :
new URL("jar:" + url.toString() + "!/");
// Retrieve the jar file using JarURLConnection
JarFile jf = (JarFile) AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public Object run() throws Exception {
JarURLConnection conn =
(JarURLConnection) jarURL.openConnection();
...
Now that you have a JarURLConnection, you can call its
getJarFile method to get the JAR file:
// Always get a fresh copy, so we don't have to
// worry about the stale file handle when the
// cached jar is closed by some other application.
conn.setUseCaches(false);
jf = conn.getJarFile();
Once you have determined the URL for your provider JAR file and
you have created a JarFile referring to the JAR file, as
shown in the steps above,
you can then verify the file.
The basic approach is:
Sample code for each of these steps is presented and described in the following sections:
Our approach is to define a class JarVerifier to
handle the retrieval of a JAR file from a given URL and verify whether
the JAR file is signed with the specified certificate.
The constructor of JarVerifier takes the provider
URL as a parameter which will be used to retrieve the JAR file later.
The actual jar verification is implemented in the verify
method which takes the provider code signing certificate as a
parameter.
public void verify(X509Certificate targetCert) throws IOException {
// variable 'jarFile' is a JarFile object created
// from the provider's Jar URL.
...
Vector entriesVec = new Vector();
Basically the verify method will go through the JAR file
entries twice: the first time checking the signature on each entry and
the second time verifying the signer is trusted.
Note: In our code snippets the jarFile
variable is the JarFile object of the provider's jar
file.
An authentic provider JAR file is signed. So the JAR file has been tampered with if it isn't signed:
// Ensure the jar file is signed.
Manifest man = jarFile.getManifest();
if (man == null) {
throw new SecurityException("The provider is not signed");
}
The next step is to go through all the entries in the JAR file
and ensure the signature on each one verifies correctly.
One possible way to verify the signature on a JAR file entry
is to simply read the file. If a JAR file is signed,
the read method itself automatically
performs the signature verification. Here is sample code:
// Ensure all the entries' signatures verify correctly
byte[] buffer = new byte[8192];
Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry je = (JarEntry) entries.nextElement();
// Skip directories.
if (je.isDirectory())
continue;
entriesVec.addElement(je);
InputStream is = jarFile.getInputStream(je);
// Read in each jar entry. A security exception will
// be thrown if a signature/digest check fails.
int n;
while ((n = is.read(buffer, 0, buffer.length)) != -1) {
// Don't care
}
is.close();
}
The code in the previous section verified the signatures of all
the provider JAR file entries. The fact that they all verify correctly
is a requirement, but it is not sufficient to verify the authenticity
of the JAR file. A final requirement is that the signatures were
generated by the same entity as the one that developed this provider.
To test that the signatures are trusted, we can again go through each
entry
in the JAR file (this time using the entriesVec
built in the previous step), and for each entry that
must be signed (that is, each entry that is not a directory
and that is not in the META-INF directory):
The loop setup is the following:
Enumeration e = entriesVec.elements();
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
...
}
The certificates for the signers of a JAR file entry
JarEntry can be obtained simply by calling the
JarEntry getCertificates method:
Certificate[] certs = je.getCertificates();
Adding this line of code to the previous loop setup code, and adding code to ignore directories and files in the META-INF directory gives us:
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
// Every file must be signed except files in META-INF.
Certificate[] certs = je.getCertificates();
if ((certs == null) || (certs.length == 0)) {
if (!je.getName().startsWith("META-INF"))
throw new SecurityException(
"The provider has unsigned class files.");
} else {
// Check whether the file is signed by the expected
// signer. The jar may be signed by multiple signers.
// See if one of the signers is 'targetCert'.
...
}
...
The certificate array returned by the JarEntry
getCertificates method contains one or more
certificate chains. There is one chain per signer of the entry.
Each chain contains one or more certificates. Each certificate in a
chain authenticates the public key in the previous certificate.
The first certificate in a chain is the signer's certificate which contains the public key corresponding to the private key actually used to sign the entry. Each subsequent certificate is a certificate for the issuer of the previous certificate. Since the self-integrity check is based on whether the JAR file is signed with the provider's signing cert, the trust decision will be made upon only the first certificate, the signer's certificate.
We need to go through the array of certificate chains and check each chain and the associated signers until we find a trusted entity. For each JAR file entry, at least one of the signers must be trusted. A signer is considered "trusted" if and only if its certificate is equals to the embedded provider signing certificate.
The following sample code loops through all the certificate
chains, compares the first certificate in a chain to the embedded
provider signing certificate, and only returns true if a
match is found.
int startIndex = 0;
X509Certificate[] certChain;
boolean signedAsExpected = false;
while ((certChain = getAChain(certs, startIndex)) != null) {
if (certChain[0].equals(targetCert)) {
// Stop since one trusted signer is found.
signedAsExpected = true;
break;
}
// Proceed to the next chain.
startIndex += certChain.length;
}
if (!signedAsExpected) {
throw new SecurityException(
"The provider is not signed by a trusted signer");
}
The getAChain method is defined as follows:
/**
* Extracts ONE certificate chain from the specified certificate array
* which may contain multiple certificate chains, starting from index
* 'startIndex'.
*/
private static X509Certificate[] getAChain(
Certificate[] certs, int startIndex) {
if (startIndex > certs.length - 1)
return null;
int i;
// Keep going until the next certificate is not the
// issuer of this certificate.
for (i = startIndex; i < certs.length - 1; i++) {
if (!((X509Certificate)certs[i + 1]).getSubjectDN().
equals(((X509Certificate)certs[i]).getIssuerDN())) {
break;
}
}
// Construct and return the found certificate chain.
int certChainSize = (i-startIndex) + 1;
X509Certificate[] ret = new X509Certificate[certChainSize];
for (int j = 0; j < certChainSize; j++ ) {
ret[j] = (X509Certificate) certs[startIndex + j];
}
return ret;
}
The sample code, MyJCE.java, is a sample
provider which has a method selfIntegrityChecking which
performs self-integrity checking. It first determines the URL of its
own provider JAR file and then verifies that the provider JAR file is
signed with the embedded code-signing certificate.
Note: The method selfIntegrityChecking
should be called by all the constructors of its cryptographic engine
classes to ensure that its integrity is not compromised.
Provider MyJCE performs self-integrity checking in
the following steps:
MyJCE.class.
JarVerifier object with the
provider URL in Step 1.
X509Certificate object from the
embedded byte array bytesOfProviderCert.
JarVerifier.verify method to verify
all entries in the provider JAR file are signed and are signed with the
same certificate instantiated in Step 3.
Note: The class JarVerifier will retrieve the
JAR file from the given URL, make sure the JAR file is signed, all
entries have valid signatures, and that entries are signed with the
specified X509Certificate.
A security exception is thrown by JarVerifier.verify
in several cases:
verify is null
(invalid).
The MyJCE.java sample code is
comprised of the code snippets shown above. In addition, it includes
error handling, sample code signing certificate bytes, and code for
instantiating a X509Certificate object from the embedded
sample code signing certificate bytes.
Regarding the use of AccessController.doPrivileged,
please see API For Privileged Blocks
for information on the use of doPrivileged.
For many cryptographic algorithms and types, there is a single official "standard name" defined in Appendix A of the Java Cryptography Architecture Reference Guide.
For example, "MD5" is the standard name for the RSA-MD5 Message
Digest algorithm defined by RSA DSI in RFC 1321.
DiffieHellman is the standard for the Diffie-Hellman key
agreement algorithm defined in PKCS3.
In the JDK, there is an aliasing scheme that enables clients
to use aliases when referring to algorithms or types, rather than their
standard names. For example, the "SUN" provider's master class
(Sun.java) defines the alias "SHA1/DSA" for the algorithm
whose standard name is "SHA1withDSA". Thus, the following statements
are equivalent:
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
Signature sig = Signature.getInstance("SHA1/DSA", "SUN");
Aliases can be defined in your "master class" (see Step 3). To define an alias, create a property named
Alg.Alias.engineClassName.aliasName
where engineClassName is the name of an engine
class (e.g., Signature), and
aliasName is your alias name. The value of the property
must be the standard algorithm (or type) name for the algorithm
(or type) being aliased.
As an example, the "SUN" provider
defines the alias "SHA1/DSA" for the signature
algorithm whose standard name is "SHA1withDSA" by setting a property
named Alg.Alias.Signature.SHA1/DSA to have the value
SHA1withDSA via the following:
put("Alg.Alias.Signature.SHA1/DSA", "SHA1withDSA");
Note that aliases defined by one provider are available only to
that provider and not to any other providers. Thus, aliases defined by
the SunJCE provider are available only to the SunJCE
provider.
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("MD5", "SUN")
MessageDigest.getInstance("MD5")
This is only appropriate if you are sure that there will be at
least one implementation of the requested algorithm (in this case,
MD5) installed on each Java platform where
your provider will be used.
Here are some common types of algorithm interdependencies:
A signature algorithm often requires use of a message digest algorithm. For example, the SHA1withDSA signature algorithm requires the SHA-1 message digest algorithm.
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.
A key pair generation algorithm often requires use of a message digest algorithm. For example, DSA keys are generated using the SHA-1 message digest algorithm.
An algorithm parameter generator often requires use of a message digest algorithm. For example, DSA parameters are generated using the SHA-1 message digest algorithm.
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.
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.
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.
An algorithm parameter generator's
engineGenerateParameters method must return an
AlgorithmParameters instance.
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:
DSAPrivateKey and
DSAPublicKey interfaces from the package
java.security.interfaces), and create your own key pair
generator and/or key factory returning keys of those types. Require
the keys passed to engineInitSign and
engineInitVerify to be the types of keys you have
implemented, that is, keys generated from your key pair generator or
key factory. Or you can,
engineInitSign method for a DSS Signature class could
accept any private keys that are instances of
java.security.interfaces.DSAPrivateKey.
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.
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 modulus size (strength) of 1024 bits for the generation of DSA parameters, and the "SunJCE" provider uses a default modulus size (keysize) of 1024 bits for the generation of Diffie-Hellman parameters.
If you implement a key pair generator, your implementation should supply default parameters that are used when clients don't specify parameters. The documentation you supply (Step 11) should state what the default parameters are.
For example, the DSA key pair generator in the Sun provider
supplies a set of pre-computed p, q, and
g default values for the
generation of 512, 768, and 1024-bit key pairs.
The following p, q, and
g values are used as the default values
for the generation of 1024-bit DSA key pairs:
p = fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80
b6512669 455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b
801d346f f26660b7 6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6
1bf83b57 e7c6a8a6 150f04fb 83f6d3c5 1ec30235 54135a16 9132f675
f3ae2b61 d72aeff2 2203199d d14801c7
q = 9760508f 15230bcc b292b982 a2eb840b f0581cf5
g = f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b
3d078267 5159578e bad4594f e6710710 8180b449 167123e8 4c281613
b7cf0932 8cc8a6e1 3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f
0bfa2135 62f1fb62 7a01243b cca4f1be a8519089 a883dfe1 5ae59f06
928b665e 807b5525 64014c3b fecf492a
(The p and q values given here were
generated by the prime
generation standard, using the 160-bit
SEED: 8d515589 4229d5e6 89ee01e6 018a237e 2cae64cd
With this seed, the algorithm found p and
q when the counter
was at 92.)
Provider.Service Class Since its introduction,
security providers have published their service information
via appropriately formatted key-value String pairs they put
in their Hashtable entries. While this mechanism is simple
and convenient, it limits the amount customization possible.
As a result, JDK 5.0 introduced a second option, the
Provider.Service class. It offers an alternative way for
providers to advertise their services and supports additional
features as described below. Note that this addition is fully
compatible with the older method of using String valued
Hashtable entries. A provider on JDK 5.0 can choose either
method as it prefers, or even use both at the same time.
A Provider.Service object encapsulates all information
about a service. This is the provider that offers the service, its type
(e.g. MessageDigest or Signature), the
algorithm name, and the name of the class that implements the service.
Optionally, it also includes a list of alternate algorithm names for
this service (aliases) and attributes, which are a map of (name, value)
String pairs. In addition, it defines the methods
newInstance() and supportsParameter(). They
have default implementations, but can be overridden by providers if
needed, as may be the case with providers that interface with hardware
security tokens.
The newInstance() method is used by the security
framework when it needs to construct new implementation instances. The
default implementation uses reflection to invoke the standard
constructor for the respective type of service. For all standard
services except CertStore, this is the no-args
constructor. The constructorParameter to
newInstance() must be null in theses cases. For services
of type CertStore, the constructor that takes a
CertStoreParameters object is invoked, and
constructorParameter must be a non-null instance of
CertStoreParameters. A security provider can override the
newInstance() method to implement instantiation as
appropriate for that implementation. It could use direct invocation or
call a constructor that passes additional information specific to the
Provider instance or token. For example, if multiple Smartcard readers
are present on the system, it might pass information about which reader
the newly
created service is to be associated with. However, despite
customization all implementations must follow the conventions about
constructorParameter described above.
The supportsParameter() tests whether the Service can
use the specified parameter. It returns false if this service cannot
use the parameter. It returns true if this service can use the
parameter, if a fast test is infeasible, or if the status is unknown.
It is used by the security framework with some types of services to
quickly exclude non-matching implementations from consideration. It is
currently only defined for the following standard services:
Signature, Cipher, Mac, and
KeyAgreement. The parameter must be an instance
of Key in these cases. For example, for Signature
services, the framework tests whether the service can use the supplied
Key before instantiating the service. The default implementation
examines the attributes SupportedKeyFormats and
SupportedKeyClasses as described below. Again, a provider
may override this methods to implement additional tests.
The SupportedKeyFormats attribute is a list of the
supported formats for encoded keys (as returned by
key.getFormat()) separated by the "|" (pipe) character. For
example, X.509|PKCS#8. The
SupportedKeyClasses attribute is a list of the names of
classes of interfaces separated by the "|" character. A key object is
considered to be acceptable if it is assignable to at least one of
those classes or interfaces named. In other words, if the class of the
key object is a subclass of one of the listed classes (or the class
itself) or if it implements the listed interface. An example value is
"java.security.interfaces.RSAPrivateKey|java.security.interfaces.RSAPublicKey"
.
Four methods have been added to the Provider class for adding and looking up Services. As mentioned earlier, the implementation of those methods and also of the existing Properties methods have been specifically designed to ensure compatibility with existing Provider subclasses. This is achieved as follows:
If legacy Properties methods are used to add entries, the Provider
class makes sure that the property strings are parsed into equivalent
Service objects prior to lookup via getService(). Similarly,
if the putService() method is used, equivalent property
strings are placed into the provider's hashtable at the same time. If a
provider implementation overrides any of the methods in the Provider
class, it has to ensure that its implementation does not interfere with
this conversion. To avoid problems, we recommend that implementations
do not override any of the methods in the Provider class.
If you implement a signature algorithm, the documentation you supply
(Step 11) should specify the format
in which the signature (generated by one of the sign methods)
is encoded.
For example, the 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 }
The Java Security API contains the following interfaces
(in the java.security.interfaces package)
for the convenience of programmers implementing DSA services:
The following sections discuss requirements for implementations of these interfaces.
DSAKeyPairGenerator ImplementationThis interface is obsolete. It used to be needed to enable clients
to provide DSA-specific parameters to be used rather than the default
parameters your implementation supplies. However, in Java it is no
longer necessary; a new KeyPairGenerator
initialize method that takes an
AlgorithmParameterSpec parameter enables clients to
indicate algorithm-specific parameters.
DSAParams ImplementationIf you are implementing a DSA key pair generator,
you need a class implementing DSAParams for holding and
returning the p, q, and g
parameters.
A DSAParams implementation is also required if you
implement the DSAPrivateKey and DSAPublicKey
interfaces. DSAPublicKey and DSAPrivateKey
both extend the DSAKey interface, which contains a
getParams method that must return a DSAParams
object. See DSAPrivateKey and
DSAPublicKey Implementations for more information.
Note: there is a DSAParams implementation built
into the JDK: the java.security.spec.DSAParameterSpec
class.
DSAPrivateKey and
DSAPublicKey ImplementationsIf you implement a DSA key pair generator or key factory, you
need to create classes implementing the DSAPrivateKey and
DSAPublicKey interfaces.
If you implement a DSA key pair generator, your
generateKeyPair method (in your
KeyPairGeneratorSpi subclass) will return instances
of your implementations of those interfaces.
If you implement a DSA key factory, your
engineGeneratePrivate method (in your
KeyFactorySpi subclass) will return an instance
of your DSAPrivateKey implementation, and your
engineGeneratePublic method will return an instance
of your DSAPublicKey implementation.
Also, your engineGetKeySpec and
engineTranslateKey methods will expect the passed-in key
to be an instance of a DSAPrivateKey or
DSAPublicKey implementation. The getParams
method provided by the interface implementations is useful for
obtaining and extracting the parameters from the keys and then using
the parameters, for example as parameters to the
DSAParameterSpec constructor called to create a parameter
specification from parameter values that could be used to initialize a
KeyPairGenerator object for DSA.
If you implement a DSA signature algorithm, your
engineInitSign method (in your
SignatureSpi subclass) will expect to be passed a
DSAPrivateKey and your engineInitVerify method
will expect to be passed a DSAPublicKey.
Please note: The DSAPublicKey and
DSAPrivateKey interfaces define a very generic,
provider-independent interface to DSA public and private keys,
respectively. The engineGetKeySpec and
engineTranslateKey methods (in your
KeyFactorySpi subclass) could additionally check if the
passed-in key is actually an instance of their provider's own
implementation of DSAPrivateKey or
DSAPublicKey, e.g., to take advantage of provider-specific
implementation details. The same is true for the DSA signature
algorithm engineInitSign and engineInitVerify
methods (in your SignatureSpi subclass).
To see what methods need to be implemented by classes that implement
the DSAPublicKey and DSAPrivateKey
interfaces, first note the following interface signatures:
In the java.security.interfaces package:
public interface DSAPrivateKey extends DSAKey, java.security.PrivateKey public interface DSAPublicKey extends DSAKey, java.security.PublicKey public interface DSAKey
In the java.security package:
public interface PrivateKey extends Key public interface PublicKey extends Key public interface Key extends java.io.Serializable
In order to implement the DSAPrivateKey and
DSAPublicKey interfaces, you must implement the methods
they define as well as those defined by interfaces they
extend, directly or indirectly.
Thus, for private keys, you need to supply a class that implements
getX method from the
DSAPrivateKey interface.
getParams method from the
java.security.interfaces.DSAKey interface, since
DSAPrivateKey extends DSAKey. Note: The
getParams method returns a DSAParams object,
so you must also have a DSAParams
implementation.
getAlgorithm, getEncoded, and
getFormat methods from the
java.security.Key interface, since
DSAPrivateKey extends
java.security.PrivateKey, and PrivateKey
extends Key.
Similarly, for public DSA keys, you need to supply a class that implements:
getY method from the
DSAPublicKey interface.
getParams method from the
java.security.interfaces.DSAKey interface, since
DSAPublicKey extends DSAKey. Note: The getParams
method returns a DSAParams object, so you must also
have a DSAParams implementation.
getAlgorithm, getEncoded, and
getFormat methods from the
java.security.Key interface, since DSAPublicKey
extends java.security.PublicKey, and PublicKey
extends Key.
The Java Security API contains the following interfaces
(in the java.security.interfaces package)
for the convenience of programmers implementing RSA services:
The following sections discuss requirements for implementations of these interfaces.
RSAPrivateKey ,
RSAPrivateCrtKey , and
RSAPublicKey ImplementationsIf you implement an RSA key pair generator or key factory, you need
to create classes implementing the RSAPrivateKey (and/or
RSAPrivateCrtKey) and RSAPublicKey
interfaces. (RSAPrivateCrtKey is the interface to an RSA
private key, using the Chinese Remainder Theorem (CRT)
representation.)
If you implement an RSA key pair generator, your
generateKeyPair method (in your
KeyPairGeneratorSpi subclass) will return instances
of your implementations of those
interfaces.
If you implement an RSA key factory, your
engineGeneratePrivate method (in your
KeyFactorySpi subclass) will return an instance of your
RSAPrivateKey (or RSAPrivateCrtKey)
implementation, and your engineGeneratePublic method will
return an instance of your RSAPublicKey implementation.
Also, your engineGetKeySpec and
engineTranslateKey methods will expect the passed-in key
to be an instance of an RSAPrivateKey,
RSAPrivateCrtKey, or RSAPublicKey
implementation.
If you implement an RSA signature algorithm, your
engineInitSign method (in your
SignatureSpi subclass) will expect to be passed either an
RSAPrivateKey or an RSAPrivateCrtKey,
and your engineInitVerify method
will expect to be passed an RSAPublicKey.
Please note: The RSAPublicKey,
RSAPrivateKey, and RSAPrivateCrtKey
interfaces define a very generic, provider-independent interface to RSA
public and private keys. The engineGetKeySpec and
engineTranslateKey methods (in your
KeyFactorySpi subclass) could additionally check if the
passed-in key is actually an instance of their provider's own
implementation of RSAPrivateKey,
RSAPrivateCrtKey, or RSAPublicKey, e.g., to
take advantage of provider-specific implementation details. The same is
true for the RSA signature algorithm engineInitSign and
engineInitVerify methods (in your
SignatureSpi subclass).
To see what methods need to be implemented by classes that implement
the RSAPublicKey, RSAPrivateKey, and
RSAPrivateCrtKey interfaces, first note the following
interface signatures:
In the java.security.interfaces package:
public interface RSAPrivateKey extends java.security.PrivateKey
public interface RSAPrivateCrtKey extends RSAPrivateKey
public interface RSAPublicKey extends java.security.PublicKey
In the java.security package:
public interface PrivateKey extends Key
public interface PublicKey extends Key
public interface Key extends java.io.Serializable
In order to implement the RSAPrivateKey,
RSAPrivateCrtKey, and RSAPublicKey
interfaces, you must implement the methods they define as well as those
defined by interfaces they extend, directly or indirectly.
Thus, for RSA private keys, you need to supply a class that implements:
getModulus and getPrivateExponent
methods from the
RSAPrivateKey interface.
getAlgorithm, getEncoded, and
getFormat methods from the
java.security.Key interface, since RSAPrivateKey
extends java.security.PrivateKey, and PrivateKey
extends Key.
Similarly, for RSA private keys using the Chinese Remainder Theorem (CRT) representation, yo