Movatterモバイル変換


[0]ホーム

URL:


Skip toContent

How to Implement a Provider in the Java CryptographyArchitecture


Introduction

The Java platform defines a set of APIs spanning major securityareas, including cryptography, public key infrastructure,authentication, secure communication, and access control. TheseAPIs allow developers to easily integrate security into theirapplication code. They were designed around the followingprinciples:

  1. Implementation independence

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

  2. Implementation interoperability

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

  3. Algorithm extensibility

    The Java platform includes a number of built-in providers thatimplement a basic set of security services that are widely usedtoday. However, some applications may rely on emerging standardsnot yet implemented, or on proprietary services. The Java platformsupports the installation of custom providers that implement suchservices.

ACryptographic Service Provider (provider) refers to apackage (or a set of packages) that supply a concreteimplementation of a subset of the cryptography aspects of the JDKSecurity API.

Thejava.security.Provider class encapsulates thenotion of a security provider in the Java platform. It specifiesthe provider's name and lists the security services it implements.Multiple providers may be configured at the same time, and arelisted in order of preference. When a security service isrequested, the highest priority provider that implements thatservice is selected.

Figures 1 and 2 illustrate these options for requesting a SHA-256message digest implementation. Both figures show three providersthat implement message digest algorithms. The providers are orderedby preference from left to right (1-3). In Figure 1, an applicationrequests an SHA-256 algorithm implementation without specifying aprovider name. The providers are searched in preference order andthe implementation from the first provider supplying thatparticular algorithm, ProviderB, is returned. In Figure 2, theapplication requests the SHA-256 algorithm implementation from aspecific provider, ProviderC. This time the implementation fromthat provider is returned, even though a provider with a higherpreference order, ProviderB, also supplies a SHA-256implementation.

diagram showing an application requesting an SHA-256 algorithem without specifying a provider namediagram showing an application requesting an SHA-256 algorithem from a specific provider
Figure 1: Provider searchingFigure 2: Specific providerrequested

Each installation has one or more provider packages installed.Clients may configure their runtimes with different providers, andspecify apreference order for each of them. The preferenceorder is the order in which providers are searched for requestedalgorithms when no particular provider is requested.

Sun's version of the Java runtime environment comes standardwith a default provider, named "SUN". Other Java runtimeenvironments may not necessarily supply the "SUN" provider.

Who Should Read This Document

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

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

Related Documentation

This document assumes you have already read theJava Cryptography Architecture ReferenceGuide.

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

Notes onTerminology

Throughout this document, the termsJCA by itself refersto the JCA framework. Whenever this document notes a specific JCAprovider, it will be referred to explicitly by the providername.

Engine Classes and CorrespondingService Provider Interface Classes

Anengine class defines a cryptographic service in anabstract fashion (without a concrete implementation).

Acryptographic service is always associated with aparticular algorithm or type. It either provides cryptographicoperations (like those for digital signatures or message digests,ciphers or key agreement protocols); generates or supplies thecryptographic material (keys or parameters) required forcryptographic operations; or generates data objects (keystores orcertificates) that encapsulate cryptographic keys (which can beused in a cryptographic operation) in a secure fashion.

For example, here are four engine classes:

The Java Cryptography Architecture encompasses the classescomprising the Security package that relate to cryptography,including the engine classes. Users of the API request and utilizeinstances of the engine classes to carry out correspondingoperations. The JDK defines the following engine classes:


Note: Agenerator creates objects with brand-newcontents, whereas afactory creates objects from existingmaterial (for example, an encoding).


Anengine class provides the interface to thefunctionality of a specific type of cryptographic service(independent of a particular cryptographic algorithm). It definesApplication Programming Interface (API) methods that allowapplications to access the specific type of cryptographic serviceit provides. The actual implementations (from one or moreproviders) are those for specific algorithms. For example, theSignature engine class provides access to the functionality of adigital signature algorithm. The actual implementation supplied inaSignatureSpi subclass (see next paragraph) would bethat for a specific kind of signature algorithm, such as SHA256withDSAor SHA512withRSA.

The application interfaces supplied by an engine class areimplemented in terms of aService Provider Interface (SPI).That is, for each engine class, there is a corresponding abstractSPI class, which defines the Service Provider Interface methodsthat cryptographic service providers must implement.

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 SPImethods of the encapsulated SPI object. An instance of an engineclass (and of its corresponding SPI class) is created by a call tothegetInstance factory method of the engineclass.

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

Each SPI class is abstract. To supply the implementation of aparticular type of service and for a specific algorithm, a providermust subclass the corresponding SPI class and provideimplementations for all the abstract methods.

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

As a final example, the KeyFactory engine class supports theconversion from opaque keys to transparent key specifications, andvice versa. SeeKey Specification Interfacesand Classes Required by Key Factories for details. The actualimplementation supplied in a KeyFactorySpi subclass would be thatfor a specific type of keys, e.g., DSA public and private keys.

Steps to Implement and Integrate aProvider

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

Step 1: Write your ServiceImplementation Code

The first thing you need to do is to write the code thatprovides algorithm-specific implementations of the cryptographicservices you want to support.

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

For cryptographic services not defined in JCA (For example;signatures and message digests), please refer toJava Cryptography Architecture ReferenceGuide.

For each cryptographic service you wish to implement, create asubclass of the appropriate SPI class. JCA defines the followingengine classes:

(SeeEngine Classes and Corresponding SPIClasses in this document for information on the JCA and othercryptographic classes.)

In your subclass, you need to:

  1. Supply implementations for the abstract methods, whose namesusually begin withengine. SeeFurther Implementation Details andRequirements for additional information.
  2. Ensure there is a public constructor without any arguments.Here's why: When one of your services is requested, Java Securitylooks up the subclass implementing that service, as specified by aproperty in your "master class" (seeStep 3).Java Security then creates theClass object associatedwith your subclass, and creates an instance of your subclass bycalling thenewInstance method on thatClass object.newInstance requires yoursubclass to have a public constructor without any parameters.
  3. A default constructor without arguments will automatically begenerated if your subclass doesn't have any constructors. But ifyour subclass defines any constructors, you must explicitly definea public constructor without arguments.

Step 1.1: Additional JCA ProviderRequirements and Recommendations for EncryptionImplementations

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

In addition, each provider should perform self-integritychecking to ensure that the JAR file containing its code has notbeen manipulated in an attempt to invoke provider methods directlyrather than through JCA. For further information, seeHow a Provider Can Do Self-IntegrityChecking.

In order for provider classes to become unusable if instantiatedby an application directly, bypassing JCA, providers shouldimplement the following:

For providers that may be exported outside the U.S.,CipherSpi implementations must include animplementation of theengineGetKeySize method which,given aKey, returns the key size. If there arerestrictions on available cryptographic strength specified injurisdiction policy files, eachCipher initializationmethod callsengineGetKeySize and then compares theresult with the maximum allowable key size for the particularlocation and circumstances of the applet or application being run.If the key size is too large, the initialization method throws anexception.

Additionaloptional features that providers may implementare

Step 2: Give your Provider aName

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

Step 3: Write yourMasterClass, a subclass of Provider

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

Your subclass should be afinal class, and itsconstructor should

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

For a property in the above format, the value of the propertymust be the value for the corresponding attribute. (SeeAppendix A of the Java CryptographyArchitecture API Specification & Reference for the definitionof each standard attribute.)

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

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

For further master class property setting examples, see the JDK 7 source codefor the following classes:

These files show how theSun andSunJCE providers setproperties.

Step 3.1: Additional Steps forCipher Implementations

As mentioned above, in the case of aCipherproperty,algName may actually represent atransformation. Atransformation is a string thatdescribes the operation (or set of operations) to be performed by aCipher object on some given input. A transformationalways includes the name of a cryptographic algorithm (e.g.,AES), and may be followed by a mode and a paddingscheme.

A transformation is of the form:

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

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

When requesting a block cipher in stream cipher mode (forexample;AES inCFB orOFBmode), a client may optionally specify the number of bits to beprocessed at a time, by appending this number to the mode name asshown in the following sample transformations:

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

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

A provider may supply a separate class for each combination ofalgorithm/mode/padding. Alternatively, a provider may decideto provide more generic classes representing sub-transformationscorresponding toalgorithm oralgorithm/mode oralgorithm//padding (note the double slashes); in this casethe requested mode and/or padding are set automatically by thegetInstance methods ofCipher, whichinvoke theengineSetMode andengineSetPadding methods of the provider's subclass ofCipherSpi.

That is, aCipher property in a provider masterclass may have one of the formats shown in the table below.

Cipher Property FormatDescription
Cipher.algNameA provider's subclass ofCipherSpiimplementsalgName with pluggable mode and padding
Cipher.algName/modeA provider's subclass ofCipherSpiimplementsalgName in the specifiedmode, withpluggable padding
Cipher.algName//paddingA provider's subclass ofCipherSpiimplementsalgName with the specifiedpadding, withpluggable mode
Cipher.algName/mode/paddingA provider's subclass ofCipherSpiimplementsalgName with the specifiedmode andpadding

(SeeAppendix A of theJava Cryptography Architecture Reference Guide for thestandard algorithm names, modes, and padding schemes that should beused.)

For example, a provider may supply a subclass ofCipherSpi that implementsAES/ECB/PKCS5Padding,one that implementsAES/CBC/PKCS5Padding, one thatimplementsAES/CFB/PKCS5Padding, and yet another one thatimplementsAES/OFB/PKCS5Padding. That provider would havethe followingCipher properties in its masterclass:

Another provider may implement a class for each of the abovemodes (i.e., one class forECB, one forCBC, one forCFB, and one forOFB), one class forPKCS5Padding, and a genericAES class that subclassesfromCipherSpi. That provider would have the followingCipher properties in its master class:

ThegetInstance factory method of theCipher engine class follows these rules in order toinstantiate a provider's implementation ofCipherSpifor a transformation of the form "algorithm":

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

    If the answer is YES, instantiate this class, for whose mode andpadding scheme default values (as supplied by the provider) areused.

    If the answer is NO, throw aNoSuchAlgorithmExceptionexception.

ThegetInstance factory method of theCipher engine class follows these rules in order toinstantiate a provider's implementation ofCipherSpifor a transformation of the form"algorithm/mode/padding":

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

    If the answer is YES, instantiate it.

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

    If the answer is YES, instantiate it, and callengineSetPadding(padding) on the newinstance.

    If the answer is NO, go to the next step.
  3. Check if the provider has registered a subclass ofCipherSpi 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.
  4. Check if the provider has registered a subclass ofCipherSpi for the sub-transformation"algorithm".

    If the answer is YES, instantiate it, and callengineSetMode(mode) andengineSetPadding(padding) on the newinstance.

    If the answer is NO, throw aNoSuchAlgorithmExceptionexception.

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

Step 5: Place Your Provider in a JARFile

Place your provider code in a JAR file, in preparation forsigning it in the next step. For more information on thejartool, seejar (forSolaris, Linux, or macOS) (forMicrosoft Windows).

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

This command creates a JAR file with the specified namecontaining the specified classes.

Step 6: Optional -- Sign your JARFile

If your provider is supplying encryption algorithms through theCipher KeyAgreement,KeyGenerator, Mac, orSecretKeyFactory classes,you will need to sign your JAR file so that the JCA canauthenticate the code at runtime. For details, seeStep 1a. If you areNOT providing animplementation of this type you can skip this step.

Step 6.1: Get a Code-SigningCertificate

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

Below are the steps you should use to get a code-signingcertificate. For more information on thekeytool tool, seekeytool (forSolaris, Linux, or macOS) (forMicrosoft Windows).

  1. Usekeytool to generate a 2048-bit RSA keypair:

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

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


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


    The option values in angle brackets (< and>)represent the actual values that must be supplied. For example,<alias> must be replaced with whatever aliasname you wish to be used to refer to the newly-generated keystoreentry 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. Forexample, 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 becreated.

    • If command lines you type are not allowed to be aslong as thekeytool -genkeypair command you want toexecute (for example, if you are typing to a Microsoft Windows DOSprompt), you can create and execute a plain-text batch filecontaining the command. That is, create a new text file thatcontains nothing but the fullkeytool -genkeypaircommand. (Remember to type it all on one line.) Save the file witha.bat extension. Then in your DOS window, type the filename (with its path, if necessary). This will cause the command in the batch file to be executed.


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

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

    Here,<alias> is the alias for the RSAkeypair entry created in the previous step. This command generatesa Certificate Signing Request (CSR), using the PKCS#10 format. Itstores the CSR in the file whose name is specified in<csr file name>.

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

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

  5. Import the certificates you received from the JCA CodeSigning Certification Authority into your keystore with thekeytool command.

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

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

    Then import the code-signing certificate:

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

    Here,<alias> is the same alias as thatwhich you created in step 1 where you generated a RSA keypair. Thiscommand replaces the self-signed certificate in the keystore entryspecified by<alias> with the one signedby the JCA Code Signing Certification Authority.

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

Step 6.2: Sign YourProvider

Sign the JAR file created in step five with the code-signingcertificate obtained inStep 6. For moreinformation on thejarsigner tool, seejarsigner(for Solaris, Linux, or macOS)(for MicrosoftWindows).

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

Here,<alias> is the alias into the keystorefor the entry containing the code-signing certificate received fromthe JCA Code Signing Certification Authority (the same alias asthat specified in the commands inStep6.1).

You can test verification of the signature via thefollowing:

    jarsigner -verify <JAR file name>

The text "jar verified" will be displayed if the verificationwas 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 providerJAR with the same certificate/key that you used to sign the appletor webstart application. See theJava Rich Internet Applications Guide for more information on deploying RIAs, and thejarsigner 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 newprovider so that it is available via the JCA.

Step 7.1: Install theProvider

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

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

Installing the ProviderClasses

The first thing you must do is make your classes available sothat they can be found when requested. You ship your providerclasses 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 extensionif it is placed in the standard place for the JAR files of aninstalled extension:

    <java-home>/lib/ext           [Solaris, Linux, or macOS]    <java-home>\lib\ext           [Windows]

Here<java-home> refers to the directory wherethe runtime software is installed, which is the top-level directoryof the Java Runtime Environment (JRE) or thejredirectory in the Java SE (JDK) software. For example, if youhave JDK 6 installed on Solaris in a directory named/home/user1/jdk1.6.0, or on Microsoft Windows in adirectory namedC:\jdk1.6.0, then you need to installthe JAR file in the following directory:

    /home/user1/jdk1.6.0/jre/lib/ext    [Solaris, Linux, or macOS]    C:\jdk1.6.0\jre\lib\ext             [Windows]

Similarly, if you have JRE 6 installed on Solaris in a directorynamed/home/user1/jre1.6.0, or on Microsoft Windows ina directory namedC:\jre1.6.0, you need to install theJAR file in the following directory:

    /home/user1/jre1.6.0/lib/ext        [Solaris, Linux, or macOS]    C:\jre1.6.0\lib\ext                 [Windows]

For more information oninstalled extensions, seeInstalledExtensions.

For more information onbundled extensions, seeBundled Extensions.

Configuring theProvider

The next step is to add the provider to your list of approvedproviders. This is done statically by editing the securityproperties file

    <java-home>/lib/security/java.security        [Solaris, Linux, or macOS]    <java-home>\lib\security\java.security        [Windows]

Here<java-home> refers to the directory wherethe JRE was installed. For example, if you have JDK 6 installed onSolaris in a directory named/home/user1/jdk1.6.0, oron Microsoft indows in a directory namedC:\jdk1.6.0,then you need to edit the following file:

    /home/user1/jdk1.6.0/jre/lib/security/java.security [Solaris, Linux, or macOS]    C:\jdk1.6.0\jre\lib\security\java.security          [Windows]

Similarly, if you have the JRE 6 installed on Solaris in adirectory named/home/user1/jre1.6.0, or on Windows ina directory namedC:\jre1.6.0, then you need to editthis file:

    /home/user1/jre1.6.0/lib/security/java.security     [Solaris, Linux, or macOS]    C:\jre1.6.0\lib\security\java.security              [Windows]

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

    security.provider.n=masterClassName

This declares a provider, and specifies its preference ordern. The preference order is the order in which providers aresearched for requested algorithms when no specific provider isrequested. The order is 1-based; 1 is the most preferred, followedby 2, and so on.

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

Java comes standard with providersnamedSUN,SunRsaSign, andSunJCE which areautomatically configured as a static provider in thejava.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

(TheSun provider's master class is theSunclass in thesun.security.provider package.)

The JCA providerSunJCE and other security-relatedproviders shipped with the Java platform are also automaticallyconfigured as static providers.

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

Suppose that your master class is theCryptoX classin thecom.cryptox.provider package, and that youwould like to make your provider the fourth preferred provider. Todo so, edit thejava.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 doso, a program (such as your test program, to be written inStep 8) can call either theaddProviderorinsertProviderAt method in theSecurity class. This type of registration is notpersistent and can only be done by code which is granted thefollowing permission:

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

where{name} is replaced by the actual providername.

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

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

Step 7.2: Set ProviderPermissions

Whenever providers are not installed extensions,permissions must be granted for whenapplets or applications are run while a security manager isinstalled. There is typically a security manager installed wheneveran applet is running, and a security manager may be installed foran application either via code in the application itself or via acommand-line argument. Permissions do not need to be granted toinstalled extensions, since the default systempolicy file grants all permissions toinstalled extensions.

Whenever a client does not install your provider as an installedextension, your provider may need the following permissions grantedto it in the client environment:

To ensure your provider works when a security manager isinstalled and the provider is not an installed extension, you needto test such an installation and execution environment. Inaddition, prior to testing you need to grant appropriatepermissions to your provider and to any other providers it uses.For example, a sample statement granting permissions to a providerwhose name is "MyJCE" and whose code is inmyjce_provider.jar appears below. Such a statementcould appear in a policy file. In this example, themyjce_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 TestPrograms

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

The first tests your program should perform are ones to ensurethat your provider is found, and that its name, version number, andadditional information is as expected. To do so, you could writecode like the following, substituting your provider name forMyPro:

    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. Forinstance, if you implemented the AES encryption algorithm, youcould check to ensure it's found when requested by using thefollowing code (again substituting your provider name for"MyPro"):

    Cipher c = Cipher.getInstance("AES", "MyPro");    System.out.println("My Cipher algorithm name is " + c.getAlgorithm());

If you don't specify a provider name in the call togetInstance, all registered providers will besearched, in preference order (seeConfiguring the Provider), until oneimplementing the algorithm is found.

If your provider implements an exemption mechanism, you shouldwrite a test applet or application that uses the exemptionmechanism. Such an applet/application also needs to be signed, andneeds to have a "permission policy file" bundled with it. SeeHow to Make Applications"Exempt" from Cryptographic Restrictions in theJavaCryptography Architecture Reference Guide for completeinformation on creating and testing such an application.

Step 9: Run your TestPrograms

Run your test program(s). Debug your code and continue testingas needed. If the Java Security API cannot seem to find one of youralgorithms, review the steps above and ensure they are allcompleted.

Be sure to include testing of your programs using differentinstallation options (e.g. making the provider an installedextension or placing it on the class path) and executionenvironments (with or without a security manager running).Installation options are discussed inStep7.1. In particular, you need to ensure your provider works whena security manager is installed and the provider is not aninstalled extension -- and thus the provider must have permissionsgranted to it; therefore, you need to test such an installation andexecution environment, after granting required permissions to yourprovider and to any other providers it uses, as described inStep 7.2.

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

Step 10: Apply for U.S. GovernmentExport Approval If Required

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

Note: If your provider callsCipher.getInstance() and the returnedCipher object needs to perform strong cryptographyregardless of what cryptographic strength is allowed by the user'sdownloaded jurisdiction policy files, you should include a copy ofthecryptoPerms permission policy file which youintend to bundle in the JAR file for your provider and whichspecifies an appropriate permission for the required cryptographicstrength. The necessity for this file is just like the requirementthat applets and applications "exempt" from cryptographicrestrictions must include acryptoPerms permissionpolicy file in their JAR file. For more information on the creationand inclusion of such a file, seeHow to Make Applications "Exempt" fromCryptographic Restrictions in theJava CryptographyArchitecture Reference Guide.

Here are two URLs that may be useful:

Step 11: Document your Providerand its Supported Services

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

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

Message Digests andMACs

For each Message Digest and MAC algorithm, indicate whether ornot your implementation is cloneable. This is not technicallynecessary, but it may save clients some time and coding by tellingthem whether or not intermediate Message Digests or MACs may bepossible through cloning. Clients who do not know whether or not aMessageDigest orMac implementation iscloneable can find out by attempting to clone the object andcatching the potential exception, as illustrated by the followingexample:

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

where:

Key Pair Generators

For a key pair generator algorithm, in case the client does notexplicitly initialize the key pair generator (via a call to aninitialize method), each provider must supply anddocument a default initialization. For example, the Diffie-Hellmankey pair generator supplied by theSunJCE provider uses adefault prime modulus size (keysize) of 1024 bits.

Key Factories

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

Algorithm Parameter Generators

In case the client does not explicitly initialize the algorithmparameter generator (via a call to aninit method intheAlgorithmParameterGenerator engine class), eachprovider must supply and document a default initialization. Forexample, theSunJCE provider uses a default prime modulussize (keysize) of 1024 bits for the generation ofDiffie-Hellman parameters, theSun provider a defaultmodulus prime size of 1024 bits for the generation of DSAparameters.

Signature Algorithms

If you implement a signature algorithm, you should document theformat in which the signature (generated by one of thesign methods) is encoded. For example, the SHA256withDSAsignature algorithm supplied by the "SUN" provider encodes thesignature as a standardASN.1 SEQUENCE of twointegers,r ands.

Random Number Generation (SecureRandom) Algorithms

For a random number generation algorithm, provide informationregarding how "random" the numbers generated are, and the qualityof the seed when the random number generator is self-seeding. Alsonote what happens when a SecureRandom object (and its encapsulatedSecureRandomSpi implementation object) is deserialized: Ifsubsequent calls to thenextBytes method (whichinvokes theengineNextBytes method of the encapsulatedSecureRandomSpi object) of the restored object yield the exact same(random) bytes as the original object would, then let users knowthat if this behaviour is undesirable, they should seed therestored random object by calling itssetSeedmethod.

Certificate Factories

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

Keystores

A provider should document any relevant information regardingthe keystore implementation, such as its underlying dataformat.

Step 12: Make your Class Files andDocumentation Available to Clients

After writing, configuring, testing, installing and documentingyour provider software, make documentation available to yourcustomers.

How a Provider CanDo Self-Integrity Checking

Each provider should do self-integrity checking to ensure thatthe JAR file containing its code has not been tampered with, forexample in an attempt to invoke provider methods directly ratherthan through JCA. Providers that provide implementations forencryption services (Cipher, KeyAgreement, KeyGenerator,MAC orSecretKey factory) must be digitallysigned and should be signed with a certificate issued by "trusted"Certification Authorities. Currently, the following twoCertification Authorities are considered "trusted":

Please refer toStep 6.2 for detailedinformation on how to get a code-signing certificate from SunMicrosystems' JCA Code Signing CA and the certificate of thatCA.

After getting the signing certificate from above CertificationAuthority, provider packages should embed within themselves thebytes for its own signing certificate, for example in an array likethebytesOfProviderCert array referred to in theIdentifying Each of the Signers andDetermining If One is Trusted section below. At runtime, theembedded certificate will be used in determining whether or not theprovider code is authentic.

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

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

Each of these steps is described in the following sections:

Notes on theSample Code

Note: The sample codeMyJCE.java is a complete codeexample that implements these steps. You can download this code foryour reference. TheNotes on the SampleCode section traces how these concepts are implemented in thesample 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 codeto authenticate the JCA framework to assure themselves of theintegrity and authenticity of the JCA that they plugged into. InJDK 6, this is no longer necessary.

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

    Class cipherCls = Class.forName("javax.crypto.Cipher");    CodeSource cs = cipherCls.getProtectionDomain().getCodeSource();    if (cs != null) {        // Authenticate JCE framework
. . . }

Finding the ProviderJAR File: Basics

Determining the Provider's JAR File URL

The URL for the provider's JAR file can be obtained bydetermining the provider'sCodeSource and then callingthegetLocation method on theCodeSource.

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

Creating a JarFileReferring to the JAR File

Once you have the URL for the provider's JAR file, you cancreate ajava.util.jar.JarFile referring to the JARfile. This instance is needed in the step forverifying the Provider JAR file.

To create the JAR file, first open a connection to the specifiedURL by calling itsopenConnection method. Since theURL is a JAR URL, the type isjava.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 aJarURLConnection, you can callitsgetJarFile method to get the JAR file:

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

Verifying theProvider JAR File: Basics

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

The basic approach is:

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

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

Verification Setup

Our approach is to define a classJarVerifier tohandle the retrieval of a JAR file from a given URL and verifywhether the JAR file is signed with the specified certificate.

The constructor ofJarVerifier takes the providerURL as a parameter which will be used to retrieve the JAR filelater.

The actual jar verification is implemented in theverify method which takes the provider code signingcertificate 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 theverify method will go through the JARfile entries twice: the first time checking the signature on eachentry and the second time verifying the signer is trusted.

Note: In our code snippets thejarFilevariable is theJarFile object of the provider's jarfile.

JAR File SignatureCheck

An authentic provider JAR file is signed. So the JAR file hasbeen 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");    }

VerifyingSignatures

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

    // Ensure all the entries' signatures verify correctly    byte[] buffer = new byte[8192];    Enumeration entries = jarFile.entries();    while (entries.hasMoreElements()) {        JarEntry je = (JarEntry) entries.nextElement();        // Skip directories.        if (je.isDirectory())            continue;        entriesVec.addElement(je);        InputStream is = jarFile.getInputStream(je);        // Read in each jar entry. A security exception will        // be thrown if a signature/digest check fails.        int n;        while ((n = is.read(buffer, 0, buffer.length)) != -1) {            // Don't care        }        is.close();    }

Ensuring Signers AreTrusted

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

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

The loop setup is the following:

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

Getting the Listof Certificates

The certificates for the signers of a JAR file entryJarEntry can be obtained simply by calling theJarEntrygetCertificates method:

    Certificate[] certs = je.getCertificates();

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

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

Identifying Each of theSigners and Determining If One is Trusted

The certificate array returned by theJarEntrygetCertificates method contains one or morecertificate chains. There is one chain per signer of theentry. Each chain contains one or more certificates. Eachcertificate in a chain authenticates the public key in the previouscertificate.

The first certificate in a chain is the signer's certificatewhich contains the public key corresponding to the private keyactually used to sign the entry. Each subsequent certificate is acertificate for the issuer of the previous certificate. Since theself-integrity check is based on whether the JAR file is signedwith the provider's signing cert, the trust decision will be madeupon only the first certificate, the signer's certificate.

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

The following sample code loops through all the certificatechains, compares the first certificate in a chain to the embeddedprovider signing certificate, and only returnstrue ifa 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");    }

ThegetAChain method is defined as follows:

    /**     * Extracts ONE certificate chain from the specified certificate array     * which may contain multiple certificate chains, starting from index     * 'startIndex'.     */    private static X509Certificate[] getAChain(            Certificate[] certs, int startIndex) {        if (startIndex > certs.length - 1)            return null;        int i;        // Keep going until the next certificate is not the        // issuer of this certificate.        for (i = startIndex; i < certs.length - 1; i++) {            if (!((X509Certificate)certs[i + 1]).getSubjectDN().                    equals(((X509Certificate)certs[i]).getIssuerDN())) {                break;            }        }        // Construct and return the found certificate chain.        int certChainSize = (i-startIndex) + 1;        X509Certificate[] ret = new X509Certificate[certChainSize];        for (int j = 0; j < certChainSize; j++ ) {            ret[j] = (X509Certificate) certs[startIndex + j];        }        return ret;    }

Notes on themyJCE Code Sample

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

Note: The methodselfIntegrityCheckingshould be called by all the constructors of its cryptographicengine classes to ensure that its integrity is not compromised.

ProviderMyJCE performs self-integrity checking inthe following steps:

  1. Determine the URL to access the provider JAR file using its ownclass,MyJCE.class.
  2. Instantiate aJarVerifier object with the providerURL in Step 1.
  3. Create aX509Certificate object from the embeddedbyte arraybytesOfProviderCert.
  4. Call theJarVerifier.verify method to verify allentries in the provider JAR file are signed and are signed with thesame certificate instantiated in Step 3.

Note: The classJarVerifier will retrievethe JAR file from the given URL, make sure the JAR file is signed,all entries have valid signatures, and that entries are signed withthe specifiedX509Certificate.

A security exception is thrown byJarVerifier.verify in several cases:

TheMyJCE.java sample codeis comprised of the code snippets shown above. In addition, itincludes error handling, sample code signing certificate bytes, andcode for instantiating aX509Certificate object fromthe embedded sample code signing certificate bytes.

Regarding the use ofAccessController.doPrivileged,please seeAPI For PrivilegedBlocks for information on the use ofdoPrivileged.

FurtherImplementation Details and Requirements

Alias Names

For many cryptographic algorithms and types, there is a singleofficial "standard name" defined inAppendix A of theJava CryptographyArchitecture Reference Guide.

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

In the JDK, there is an aliasing scheme that enables clients touse aliases when referring to algorithms or types, rather thantheir standard names. For example, the "SUN" provider's masterclass (Sun.java) defines the alias "SHA1/DSA" for thealgorithm whose standard name is "SHA1withDSA". Thus, the followingstatements are equivalent:

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

Aliases can be defined in your "master class" (seeStep 3). To define an alias, create a propertynamed

Alg.Alias.engineClassName.aliasName

whereengineClassName is the name of an engine class(e.g.,Signature), andaliasName is your aliasname. Thevalue of the property must be the standardalgorithm (or type) name for the algorithm (or type) beingaliased.

As an example, the "SUN" provider defines the alias "SHA1/DSA"for the signature algorithm whose standard name is "SHA1withDSA" bysetting a property namedAlg.Alias.Signature.SHA1/DSAto have the valueSHA1withDSA via the following:

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

Note that aliases defined by one provider are available only tothat provider and not to any other providers. Thus, aliases definedby theSunJCE provider are available only to theSunJCE provider.

ServiceInterdependencies

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

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

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

Here are some common types of algorithm interdependencies:

Signature and Message Digest Algorithms

A signature algorithm often requires use of a message digestalgorithm. For example, theSHA256withDSA signature algorithmrequires theSHA256 message digest algorithm.

Signature and (Pseudo-)Random Number Generation Algorithms

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

Key Pair Generation and Message Digest Algorithms

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

Algorithm Parameter Generation and Message DigestAlgorithms

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

KeyStores and Message Digest Algorithms

A keystore implementation will often utilize a message digestalgorithm to compute keyed hashes (where thekey is auser-provided password) to check the integrity of a keystore andmake sure that the keystore has not been tampered with.

Key Pair Generation Algorithms and Algorithm ParameterGenerators

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

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

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

Algorithm Parameter Generators and Algorithm Parameters

An algorithm parameter generator'sengineGenerateParameters method must return anAlgorithmParameters instance.

Signature and Key Pair Generation Algorithms or KeyFactories

If you are implementing a signature algorithm, yourimplementation'sengineInitSign andengineInitVerify methods will require passed-in keysthat are valid for the underlying algorithm (e.g., DSA keys for theDSS algorithm). You can do one of the following:

  1. Also create your own classes implementing appropriateinterfaces (e.g. classes implementing theDSAPrivateKey andDSAPublicKey interfacesfrom the packagejava.security.interfaces), and createyour own key pair generator and/or key factory returning keys ofthose types. Require the keys passed toengineInitSignandengineInitVerify to be the types of keys you haveimplemented, that is, keys generated from your key pair generatoror key factory. Or you can,
  2. Accept keys from other key pair generators or other keyfactories, as long as they are instances of appropriate interfacesthat enable your signature implementation to obtain the informationit needs (such as the private and public keys and the keyparameters). For example, theengineInitSign methodfor a DSS Signature class could accept any private keys that areinstances ofjava.security.interfaces.DSAPrivateKey.

KeyStores and Key and Certificate Factories

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

DefaultInitializations

In case the client does not explicitly initialize a key pairgenerator or an algorithm parameter generator, each provider ofsuch a service must supply (and document) a default initialization.For example, theSun provider uses a default modulus size(strength) of 1024 bits for the generation of DSA parameters, andthe "SunJCE" provider uses a default modulus size (keysize) of 1024bits for the generation of Diffie-Hellman parameters.

Default Key PairGenerator Parameter Requirements

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

For example, the DSA key pair generator in theSunprovider supplies a set of pre-computedp,q, andg default values for thegeneration of 512, 768, and 1024-bit key pairs. The followingp,q, andg values are usedas the default values for the generation of 1024-bit DSA keypairs:

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 d14801c7q = 9760508f 15230bcc b292b982 a2eb840b f0581cf5g = 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

(Thep andq values given here weregenerated by the prime generation standard, using the 160-bit

SEED:  8d515589 4229d5e6 89ee01e6 018a237e 2cae64cd

With this seed, the algorithm foundp andq when the counter was at 92.)

TheProvider.Service Class

Since its introduction, security providers have published theirservice information via appropriately formatted key-value Stringpairs they put in their Hashtable entries. While this mechanism issimple and convenient, it limits the amount customization possible.As a result, JDK 5.0 introduced a second option, theProvider.Service class. It offers an alternative wayfor providers to advertise their services and supports additionalfeatures as described below. Note that this addition is fullycompatible with the older method of using String valued Hashtableentries. A provider on JDK 5.0 can choose either method as itprefers, or even use both at the same time.

AProvider.Service object encapsulates allinformation about a service. This is the provider that offers theservice, its type (e.g.MessageDigest orSignature), the algorithm name, and the name of theclass that implements the service. Optionally, it also includes alist of alternate algorithm names for this service (aliases) andattributes, which are a map of (name, value) String pairs. Inaddition, it defines the methodsnewInstance() andsupportsParameter(). They have defaultimplementations, but can be overridden by providers if needed, asmay be the case with providers that interface with hardwaresecurity tokens.

ThenewInstance() method is used by the securityframework when it needs to construct new implementation instances.The default implementation uses reflection to invoke the standardconstructor for the respective type of service. For all standardservices exceptCertStore, this is the no-argsconstructor. TheconstructorParameter tonewInstance() must be null in theses cases. Forservices of typeCertStore, the constructor that takesaCertStoreParameters object is invoked, andconstructorParameter must be a non-null instance ofCertStoreParameters. A security provider can overridethenewInstance() method to implement instantiation asappropriate for that implementation. It could use direct invocationor call a constructor that passes additional information specificto the Provider instance or token. For example, if multipleSmartcard readers are present on the system, it might passinformation about which reader the newly created service is to beassociated with. However, despite customization all implementationsmust follow the conventions aboutconstructorParameterdescribed above.

ThesupportsParameter() tests whether the Servicecan use the specified parameter. It returns false if this servicecannot use the parameter. It returns true if this service can usethe parameter, if a fast test is infeasible, or if the status isunknown. It is used by the security framework with some types ofservices to quickly exclude non-matching implementations fromconsideration. It is currently only defined for the followingstandard services:Signature,Cipher,Mac, andKeyAgreement. Theparameter must be an instance ofKey in thesecases. For example, forSignature services, theframework tests whether the service can use the supplied Key beforeinstantiating the service. The default implementation examines theattributesSupportedKeyFormats andSupportedKeyClasses as described below. Again, aprovider may override this methods to implement additionaltests.

TheSupportedKeyFormats attribute is a list of thesupported formats for encoded keys (as returned bykey.getFormat()) separated by the "|" (pipe) character.For example,X.509|PKCS#8. TheSupportedKeyClasses attribute is a list of the namesof classes of interfaces separated by the "|" character. A keyobject is considered to be acceptable if it is assignable to atleast one of those classes or interfaces named. In other words, ifthe class of the key object is a subclass of one of the listedclasses (or the class itself) or if it implements the listedinterface. An example value is"java.security.interfaces.RSAPrivateKey|java.security.interfaces.RSAPublicKey".

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

If legacy Properties methods are used to add entries, theProvider class makes sure that the property strings are parsed intoequivalent Service objects prior to lookup viagetService(). Similarly, if theputService()method is used, equivalent property strings are placed into theprovider's hashtable at the same time. If a provider implementationoverrides any of the methods in the Provider class, it has toensure that its implementation does not interfere with thisconversion. To avoid problems, we recommend that implementations donot override any of the methods in theProviderclass.

Signature Formats

If you implement a signature algorithm, the documentation yousupply (Step 11) should specify the format inwhich the signature (generated by one of thesignmethods) is encoded.

For example, theSHA256withDSA signature algorithm suppliedby theSun provider encodes the signature as a standardASN.1 sequence of twoASN.1 INTEGER values:r ands, in that order:

SEQUENCE ::= {        r INTEGER,        s INTEGER }

DSA Interfaces and theirRequired Implementations

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

The following sections discuss requirements for implementationsof these interfaces.

DSAKeyPairGeneratorImplementation

This interface is obsolete. It used to be needed to enableclients to provide DSA-specific parameters to be used rather thanthe default parameters your implementation supplies. However, inJava it is no longer necessary; a newKeyPairGeneratorinitialize method that takes anAlgorithmParameterSpec parameter enables clients toindicate algorithm-specific parameters.

DSAParamsImplementation

If you are implementing a DSA key pair generator, you need aclass implementingDSAParams for holding and returningthep,q, andgparameters.

ADSAParams implementation is also required if youimplement theDSAPrivateKey andDSAPublicKey interfaces.DSAPublicKey andDSAPrivateKey both extend the DSAKey interface, whichcontains agetParams method that must return aDSAParams object. SeeDSAPrivateKey and DSAPublicKeyImplementations for more information.

Note: there is aDSAParams implementationbuilt into the JDK: thejava.security.spec.DSAParameterSpec class.

DSAPrivateKeyandDSAPublicKeyImplementations

If you implement a DSA key pair generator or key factory, youneed to create classes implementing theDSAPrivateKeyandDSAPublicKey interfaces.

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

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

Also, yourengineGetKeySpec andengineTranslateKey methods will expect the passed-inkey to be an instance of aDSAPrivateKey orDSAPublicKey implementation. ThegetParams method provided by the interfaceimplementations is useful for obtaining and extracting theparameters from the keys and then using the parameters, for exampleas parameters to theDSAParameterSpec constructorcalled to create a parameter specification from parameter valuesthat could be used to initialize aKeyPairGeneratorobject for DSA.

If you implement a DSA signature algorithm, yourengineInitSign method (in yourSignatureSpi subclass) will expect to be passed aDSAPrivateKey and yourengineInitVerifymethod will expect to be passed aDSAPublicKey.

Please note: TheDSAPublicKey andDSAPrivateKey interfaces define a very generic,provider-independent interface to DSA public and private keys,respectively. TheengineGetKeySpec andengineTranslateKey methods (in yourKeyFactorySpi subclass) could additionally check ifthe passed-in key is actually an instance of their provider's ownimplementation ofDSAPrivateKey orDSAPublicKey, e.g., to take advantage ofprovider-specific implementation details. The same is true for theDSA signature algorithmengineInitSign andengineInitVerify methods (in yourSignatureSpi subclass).

To see what methods need to be implemented by classes thatimplement theDSAPublicKey andDSAPrivateKey interfaces, first note the followinginterface signatures:

In thejava.security.interfaces package:

   public interface DSAPrivateKey extends DSAKey,                java.security.PrivateKey   public interface DSAPublicKey extends DSAKey,                java.security.PublicKey   public interface DSAKey

In thejava.security package:

   public interface PrivateKey extends Key   public interface PublicKey extends Key   public interface Key extends java.io.Serializable

In order to implement theDSAPrivateKey andDSAPublicKey interfaces, you must implement themethods they define as well as those defined by interfaces theyextend, directly or indirectly.

Thus, for private keys, you need to supply a class thatimplements

RSA Interfaces and theirRequired Implementations

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

The following sections discuss requirements for implementationsof these interfaces.

RSAPrivateKey,RSAPrivateCrtKey , andRSAPublicKeyImplementations

If you implement an RSA key pair generator or key factory, youneed to create classes implementing theRSAPrivateKey(and/orRSAPrivateCrtKey) andRSAPublicKey interfaces.(RSAPrivateCrtKey is the interface to an RSA privatekey, using theChinese Remainder Theorem (CRT)representation.)

If you implement an RSA key pair generator, yourgenerateKeyPair method (in yourKeyPairGeneratorSpi subclass) will return instances ofyour implementations of those interfaces.

If you implement an RSA key factory, yourengineGeneratePrivate method (in yourKeyFactorySpi subclass) will return an instance ofyourRSAPrivateKey (orRSAPrivateCrtKey)implementation, and yourengineGeneratePublic methodwill return an instance of yourRSAPublicKeyimplementation.

Also, yourengineGetKeySpec andengineTranslateKey methods will expect the passed-inkey to be an instance of anRSAPrivateKey,RSAPrivateCrtKey, orRSAPublicKeyimplementation.

If you implement an RSA signature algorithm, yourengineInitSign method (in yourSignatureSpi subclass) will expect to be passed eitheranRSAPrivateKey or anRSAPrivateCrtKey,and yourengineInitVerify method will expect to bepassed anRSAPublicKey.

Please note: TheRSAPublicKey,RSAPrivateKey, andRSAPrivateCrtKeyinterfaces define a very generic, provider-independent interface toRSA public and private keys. TheengineGetKeySpec andengineTranslateKey methods (in yourKeyFactorySpi subclass) could additionally check ifthe passed-in key is actually an instance of their provider's ownimplementation ofRSAPrivateKey,RSAPrivateCrtKey, orRSAPublicKey, e.g.,to take advantage of provider-specific implementation details. Thesame is true for the RSA signature algorithmengineInitSign andengineInitVerifymethods (in yourSignatureSpi subclass).

To see what methods need to be implemented by classes thatimplement theRSAPublicKey,RSAPrivateKey, andRSAPrivateCrtKeyinterfaces, first note the following interface signatures:

In thejava.security.interfaces package:

    public interface RSAPrivateKey extends java.security.PrivateKey    public interface RSAPrivateCrtKey extends RSAPrivateKey    public interface RSAPublicKey extends java.security.PublicKey

In thejava.security package:

    public interface PrivateKey extends Key    public interface PublicKey extends Key    public interface Key extends java.io.Serializable

In order to implement theRSAPrivateKey,RSAPrivateCrtKey, andRSAPublicKeyinterfaces, you must implement the methods they define as well asthose defined by interfaces they extend, directly orindirectly.

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

  • thegetModulus andgetPrivateExponentmethods from theRSAPrivateKey interface.
  • thegetAlgorithm,getEncoded, andgetFormat methods from thejava.security.Keyinterface, sinceRSAPrivateKey extendsjava.security.PrivateKey, andPrivateKeyextendsKey.

Similarly, for RSA private keys using theChinese RemainderTheorem (CRT) representation, you need to supply a class thatimplements:

  • all the methods listed above for RSA private keys, sinceRSAPrivateCrtKey extendsjava.security.interfaces.RSAPrivateKey.
  • thegetPublicExponent,getPrimeP,getPrimeQ,getPrimeExponentP,getPrimeExponentQ, andgetCrtCoefficientmethods from theRSAPrivateKey interface.

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

  • thegetModulus andgetPublicExponentmethods from theRSAPublicKeyinterface.
  • thegetAlgorithm,getEncoded, andgetFormat methods from thejava.security.Keyinterface, sinceRSAPublicKey extendsjava.security.PublicKey, andPublicKeyextendsKey.

JCA contains a number ofAlgorithmParameterSpecimplementations for the most frequently used cipher and keyagreement algorithm parameters. If you are operating on algorithmparameters that should be for a different type of algorithm notprovided by JCA, you will need to supply your ownAlgorithmParameterSpec implementation appropriate forthat type of algorithm.

Diffie-Hellman Interfaces andtheir Required Implementations

JCA contains the following interfaces (in thejavax.crypto.interfaces package) for the convenienceof programmers implementing Diffie-Hellman services:

The following sections discuss requirements for implementationsof these interfaces.

DHPrivateKeyandDHPublicKeyImplementations

If you implement a Diffie-Hellman key pair generator or keyfactory, you need to create classes implementing theDHPrivateKey andDHPublicKeyinterfaces.

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

If you implement a Diffie-Hellman key factory, yourengineGeneratePrivate method (in yourKeyFactorySpi subclass) will return an instance ofyourDHPrivateKey implementation, and yourengineGeneratePublic method will return an instance ofyourDHPublicKey implementation.

Also, yourengineGetKeySpec andengineTranslateKey methods will expect the passed-inkey to be an instance of aDHPrivateKey orDHPublicKey implementation. ThegetParamsmethod provided by the interface implementations is useful forobtaining and extracting the parameters from the keys. You can thenuse the parameters, for example, as parameters to theDHParameterSpec constructor called to create aparameter specification from parameter values used to initialize aKeyPairGenerator object for Diffie-Hellman.

If you implement the Diffie-Hellman key agreement algorithm,yourengineInit method (in yourKeyAgreementSpi subclass) will expect to be passed aDHPrivateKey and yourengineDoPhasemethod will expect to be passed aDHPublicKey.

Note: TheDHPublicKey andDHPrivateKey interfaces define a very generic,provider-independent interface to Diffie-Hellman public and privatekeys, respectively. TheengineGetKeySpec andengineTranslateKey methods (in yourKeyFactorySpi subclass) could additionally check ifthe passed-in key is actually an instance of their provider's ownimplementation ofDHPrivateKey orDHPublicKey, e.g., to take advantage ofprovider-specific implementation details. The same is true for theDiffie-Hellman algorithmengineInit andengineDoPhase methods (in yourKeyAgreementSpi subclass).

To see what methods need to be implemented by classes thatimplement theDHPublicKey andDHPrivateKey interfaces, first note the followinginterface signatures:

In thejavax.crypto.interfaces package:

    public interface DHPrivateKey extends DHKey, java.security.PrivateKey    public interface DHPublicKey extends DHKey, java.security.PublicKey    public interface DHKey

In thejava.security package:

    public interface PrivateKey extends Key    public interface PublicKey extends Key    public interface Key extends java.io.Serializable

To implement theDHPrivateKey andDHPublicKey interfaces, you must implement the methodsthey define as well as those defined by interfaces they extend,directly or indirectly.

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

  • thegetX method from theDHPrivateKeyinterface.
  • thegetParams method from thejavax.crypto.interfaces.DHKeyinterface, sinceDHPrivateKey extendsDHKey.
  • thegetAlgorithm,getEncoded, andgetFormat methods from thejava.security.Keyinterface, sinceDHPrivateKey extendsjava.security.PrivateKey, andPrivateKeyextendsKey.

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

  • thegetY method from theDHPublicKeyinterface.
  • thegetParams method from thejavax.crypto.interfaces.DHKeyinterface, sinceDHPublicKey extendsDHKey.
  • thegetAlgorithm,getEncoded, andgetFormat methods from thejava.security.Keyinterface, sinceDHPublicKey extendsjava.security.PublicKey, andPublicKeyextendsKey.

Interfaces for OtherAlgorithm Types

As noted above, the Java Security API contains interfaces forthe convenience of programmers implementing services like DSA, RSAand ECC. If there are services without API support, you need todefine your own APIs.

If you are implementing a key pair generator for a differentalgorithm, you should create an interface with one or moreinitialize methods that clients can call when theywant to provide algorithm-specific parameters to be used ratherthan the default parameters your implementation supplies. Yoursubclass ofKeyPairGeneratorSpi should implement thisinterface.

For algorithms without direct API support, it is recommendedthat you create similar interfaces and provide implementationclasses. Your public key interface should extend thePublicKeyinterface. Similarly, your private key interface should extend thePrivateKeyinterface.

Algorithm ParameterSpecification Interfaces and Classes

An algorithm parameter specification is a transparentrepresentation of the sets of parameters used with analgorithm.

Atransparent representation of parameters means that youcan access each value individually, through one of thegetmethods defined in the corresponding specification class (e.g.,DSAParameterSpec definesgetP,getQ, andgetG methods, to access the p,q, and g parameters, respectively).

This is contrasted with anopaque representation, assupplied by the AlgorithmParameters engine class, in which you haveno direct access to the key material values; you can only get thename of the algorithm associated with the parameter set (viagetAlgorithm) and some kind of encoding for theparameter set (viagetEncoded).

If you supply anAlgorithmParametersSpi,AlgorithmParameterGeneratorSpi, orKeyPairGeneratorSpi implementation, you must utilizetheAlgorithmParameterSpec interface, since each ofthose classes contain methods that take anAlgorithmParameterSpec parameter. Such methods need todetermine which actual implementation of that interface has beenpassed in, and act accordingly.

JCA contains a number ofAlgorithmParameterSpecimplementations for the most frequently used signature, cipher andkey agreement algorithm parameters. If you are operating onalgorithm parameters that should be for a different type ofalgorithm not provided by JCA, you will need to supply your ownAlgorithmParameterSpec implementation appropriate forthat type of algorithm.

Java defines the following algorithm parameter specificationinterfaces and classes in thejava.security.spec andjavax.crypto.spec packages:

TheAlgorithmParameterSpec Interface

AlgorithmParameterSpec is an interface to atransparent specification of cryptographic parameters.

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

TheDSAParameterSpec Class

This class (which implements theAlgorithmParameterSpec andDSAParamsinterfaces) specifies the set of parameters used with the DSAalgorithm. It has the following methods:

    public BigInteger getP()    public BigInteger getQ()    public BigInteger getG()

These methods return the DSA algorithm parameters: the primep, the sub-primeq, and the baseg.

Many types of DSA services will find this class useful - forexample, it is utilized by the DSA signature, key pair generator,algorithm parameter generator, and algorithm parameters classesimplemented by theSun provider. As a specific example, analgorithm parameters implementation must include an implementationfor thegetParameterSpec method, which returns anAlgorithmParameterSpec. The DSA algorithm parametersimplementation supplied bySun returns an instance of theDSAParameterSpec class.

TheIvParameterSpecClass

This class (which implements theAlgorithmParameterSpec interface) specifies theinitialization vector (IV) used with a cipher in feedback mode.

Method inIvParameterSpec
MethodDescription
byte[] getIV()Returns the initialization vector (IV).

TheOAEPParameterSpecClass

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

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

ThePBEParameterSpecClass

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

Methods inPBEParameterSpec
MethodDescription
int getIterationCount()Returns the iteration count.
byte[] getSalt()Returns the salt.

TheRC2ParameterSpecClass

This class (which implements theAlgorithmParameterSpec interface) specifies the set ofparameters used with the RC2 algorithm.

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

TheRC5ParameterSpecClass

This class (which implements theAlgorithmParameterSpec interface) specifies the set ofparameters used with the RC5 algorithm.

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

TheDHParameterSpecClass

This class (which implements theAlgorithmParameterSpec interface) specifies the set ofparameters used with the Diffie-Hellman algorithm.

Methods inDHParameterSpec
MethodDescription
BigInteger getG()Returns the base generatorg.
int getL()Returns the size in bits,l, of the randomexponent (private value).
BigInteger getP()Returns the prime modulusp.

Many types of Diffie-Hellman services will find this classuseful; for example, it is used by the Diffie-Hellman keyagreement, key pair generator, algorithm parameter generator, andalgorithm parameters classes implemented by the "SunJCE" provider.As a specific example, an algorithm parameters implementation mustinclude an implementation for thegetParameterSpecmethod, which returns anAlgorithmParameterSpec. TheDiffie-Hellman algorithm parameters implementation supplied by"SunJCE" returns an instance of theDHParameterSpecclass.

Key Specification Interfacesand Classes Required by Key Factories

A key factory provides bi-directional conversions between opaquekeys (of typeKey) and key specifications. If youimplement a key factory, you thus need to understand and utilizekey specifications. In some cases, you also need to implement yourown key specifications.

Further information about key specifications, the interfaces andclasses supplied in Java, and key factory requirements with respectto specifications, is provided below.

Key specifications are transparent representations of the keymaterial that constitutes a key. If the key is stored on a hardwaredevice, its specification may contain information that helpsidentify the key on the device.

Atransparent representation of keys means that you canaccess each key material value individually, through one of theget methods defined in the corresponding specificationclass. For example,java.security.spec.DSAPrivateKeySpec definesgetX,getP,getQ, andgetG methods, to access the private keyx, and the DSA algorithm parameters used to calculatethe key: the primep, the sub-primeq,and the baseg.

This is contrasted with anopaque representation, asdefined by the Key interface, in which you have no direct access tothe parameter fields. In other words, an "opaque" representationgives you limited access to the key - just the three methodsdefined by the Key interface:getAlgorithm,getFormat, andgetEncoded.

A key may be specified in an algorithm-specific way, or in analgorithm-independent encoding format (such as ASN.1). For example,a DSA private key may be specified by its componentsx,p,q, andg (seeDSAPrivateKeySpec), or it maybe specified using its DER encoding (seePKCS8EncodedKeySpec).

Java defines the following key specification interfaces andclasses in thejava.security.spec andjavax.crypto.spec packages:

TheKeySpecInterface

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

Java supplies several classes implementing theKeySpec interface:DSAPrivateKeySpec,DSAPublicKeySpec,RSAPrivateKeySpec,RSAPublicKeySpec,EncodedKeySpec,PKCS8EncodedKeySpec, andX509EncodedKeySpec.

If your provider uses key types (e.g.,Your_PublicKey_type andYour_PrivateKey_type) for which the JDK does notalready provide correspondingKeySpec classes, thereare two possible scenarios, one of which requires that youimplement your own key specifications:

  1. If your users will never have to access specific key materialvalues of your key type, you will not have to provide anyKeySpec classes for your key type.

    In this scenario, your users will always createYour_PublicKey_type andYour_PrivateKey_type keys through the appropriateKeyPairGenerator supplied by your provider for thatkey type. If they want to store the generated keys for later usage,they retrieve the keys' encodings (using thegetEncoded method of theKey interface).When they want to create anYour_PublicKey_type orYour_PrivateKey_type key from the encoding (e.g., inorder to initialize a Signature object for signing orverification), they create an instance ofX509EncodedKeySpec orPKCS8EncodedKeySpecfrom the encoding, and feed it to the appropriateKeyFactory supplied by your provider for thatalgorithm, whosegeneratePublic andgeneratePrivate methods will return the requestedPublicKey (an instance ofYour_PublicKey_type) orPrivateKey (aninstance ofYour_PrivateKey_type) object,respectively.
  2. If you anticipate a need for users to access specific keymaterial values of your key type, or to construct a key of your keytype from key material and associated parameter values, rather thanfrom its encoding (as in the above case), you have to specify newKeySpec classes (classes that implement theKeySpec interface) with the appropriate constructormethods andget methods for returning key material fieldsand associated parameter values for your key type. You will specifythose classes in a similar manner as is done by theDSAPrivateKeySpec andDSAPublicKeySpecclasses provided in JDK 6. You need to ship those classes alongwith your provider classes, for example, as part of your providerJAR file.

TheDSAPrivateKeySpecClass

This class (which implements theKeySpec Interface) specifies a DSAprivate key with its associated parameters. It has the followingmethods:

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

These methods return the private keyx, and the DSAalgorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg.

TheDSAPublicKeySpecClass

This class (which implements theKeySpec Interface) specifies a DSApublic key with its associated parameters. It has the followingmethods:

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

These methods return the public keyy, and the DSAalgorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg.

TheRSAPrivateKeySpecClass

This class (which implements theKeySpec Interface) specifies an RSAprivate key. It has the following methods:

Method inRSAPrivateKeySpecDescription
public BigInteger getModulus()Returns the modulus.
public BigInteger getPrivateExponent()Returns the private exponent.

These methods return the RSA modulusn and privateexponentd values that constitute the RSA privatekey.

TheRSAPrivateCrtKeySpecClass

This class (which extends theRSAPrivateKeySpec class)specifies an RSA private key, as defined in the PKCS#1 standard,using theChinese Remainder Theorem (CRT) informationvalues. It has the following methods (in addition to the methodsinherited from its superclassRSAPrivateKeySpec ):

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

These methods return the public exponente and theCRT information integers: the prime factorp of themodulusn, the prime factorq ofn, the exponentd mod (p-1), the exponentd mod (q-1), and the Chinese Remainder Theoremcoefficient(inverse of q) mod p.

An RSA private key logically consists of only the modulus andthe private exponent. The presence of the CRT values is intendedfor efficiency.

TheRSAPublicKeySpecClass

This class (which implements theKeySpec Interface) specifies an RSApublic key. It has the following methods:

Method inRSAPublicKeySpecDescription
public BigInteger getModulus()Returns the modulus.
public BigInteger getPublicExponent()Returns the public exponent.

These methods return the RSA modulusn and publicexponente values that constitute the RSA publickey.

TheEncodedKeySpecClass

This abstract class (which implements theKeySpec Interface) represents a publicor private key in encoded format.

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

JDK 6 supplies two classes implementing theEncodedKeySpec interface:PKCS8EncodedKeySpec andX509EncodedKeySpec. If desired, you cansupply your ownEncodedKeySpec implementations forthose or other types of key encodings.

ThePKCS8EncodedKeySpec Class

This class, which is a subclass ofEncodedKeySpec, represents theDER encoding of a private key, according to the format specified inthe PKCS #8 standard.

ItsgetEncoded method returns the key bytes,encoded according to the PKCS #8 standard. ItsgetFormat method returns the string "PKCS#8".

TheX509EncodedKeySpecClass

This class, which is a subclass ofEncodedKeySpec, represents theDER encoding of a public or private key, according to the formatspecified in the X.509 standard.

ItsgetEncoded method returns the key bytes,encoded according to the X.509 standard. ItsgetFormatmethod returns the string "X.509".DHPrivateKeySpec,DHPublicKeySpec,DESKeySpec,DESedeKeySpec,PBEKeySpec, andSecretKeySpec.

TheDHPrivateKeySpecClass

This class (which implements theKeySpecinterface) specifies a Diffie-Hellman private key with itsassociated parameters.

Method inDHPrivateKeySpecDescription
BigInteger getG()Returns the base generatorg.
BigInteger getP()Returns the prime modulusp.
BigInteger getX()Returns the private valuex.

TheDHPublicKeySpecClass

This class (which implements theKeySpecinterface) specifies a Diffie-Hellman public key with itsassociated parameters.

Method inDHPublicKeySpecDescription
BigInteger getG()Returns the base generatorg.
BigInteger getP()Returns the prime modulusp.
BigInteger getY()Returns the public valuey.

TheDESKeySpecClass

This class (which implements theKeySpecinterface) specifies a DES key.

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

TheDESedeKeySpecClass

This class (which implements theKeySpecinterface) specifies a DES-EDE (Triple DES) key.

Method inDESedeKeySpecDescription
byte[] getKey()Returns the DES-EDE key.
static boolean isParityAdjusted(byte[] key, intoffset)Checks if the given DES-EDE key is parity-adjusted.

ThePBEKeySpecClass

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

Method inPBEKeySpecDescription
void clearPasswordClears the internal copy of the password.
int getIterationCountReturns the iteration count or 0 if not specified.
int getKeyLengthReturns the to-be-derived key length or 0 if notspecified.
char[] getPasswordReturns a copy of the password.
byte[] getSaltReturns a copy of the salt or null if not specified.

TheSecretKeySpecClass

This class implements theKeySpecinterface. Since it also implements theSecretKeyinterface, it can be used to construct aSecretKeyobject in a provider-independent fashion, i.e., without having togo through a provider-basedSecretKeyFactory.

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

Secret-KeyGeneration

If you provide a secret-key generator (subclass ofjavax.crypto.KeyGeneratorSpi) for a particularsecret-key algorithm, you may return the generated secret-keyobject (which must be an instance ofjavax.crypto.SecretKey, seeengineGenerateKey) in one of the followingways:

  • You implement a class whose instances represent secret-keys ofthe algorithm associated with your key generator. Your keygenerator implementation returns instances of that class. Thisapproach is useful if the keys generated by your key generator haveprovider-specific properties.
  • Your key generator returns an instance ofSecretKeySpec,which already implements thejavax.crypto.SecretKeyinterface. You pass the (raw) key bytes and the name of thesecret-key algorithm associated with your key generator to theSecretKeySpec constructor. This approach is useful ifthe underlying (raw) key bytes can be represented as a byte arrayand have no key-parameters associated with them.

Adding New ObjectIdentifiers

The following information applies to providers who supply analgorithm that is not listed as one of the standard algorithms inAppendix A of theJavaCryptography Architecture Reference Guide.

Mapping from OID to Name

Sometimes the JCA needs to instantiate a cryptographic algorithmimplementation from an algorithm identifier (for example, asencoded in a certificate), which by definition includes the objectidentifier (OID) of the algorithm. For example, in order to verifythe signature on an X.509 certificate, the JCA determines thesignature algorithm from the signature algorithm identifier that isencoded in the certificate, instantiates a Signature object forthat algorithm, and initializes the Signature object forverification.

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

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

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

An example of where the JCA needs to perform this type ofmapping is when your algorithm ("Foo") is a signaturealgorithm and users run thekeytool command andspecify your (signature) algorithm alias.

    % keytool -genkeypair -sigalg 1.2.3.4.5.6.7.8

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

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

Other examples of where this type of mapping is performed are(1) when your algorithm is a keytype algorithm and your programparses a certificate (using the X.509 implementation of the SUNprovider) and extracts the public key from the certificate in orderto initialize a Signature object for verification, and (2) whenkeytool users try to access a private key of yourkeytype (for example, to perform a digital signature) after havinggenerated the corresponding keypair. In these cases, your providermaster file should contain the following entries:

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

Mapping from Name to OID

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

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

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

An example of where the JCA needs to perform this kind ofmapping is when users runkeytool in any mode thattakes a-sigalg option. For example, when the-genkeypair and-certreq commands areinvoked, the user can specify your (signature) algorithm with the-sigalg option.

EnsuringExportability

A key feature of JCA is the exportability of the JCA frameworkand of the provider cryptography implementations if certainconditions are met.

Due to import control restrictions by the governments of a fewcountries, the jurisdiction policy files shipped with the JDK 6from Sun Microsystems specify that "strong" but limitedcryptography may be used. An "unlimited" version of these filesindicating no restrictions on cryptographic strengths is availablefor those living in eligible countries (which is most countries).But only the "strong" version can be imported into those countrieswhose governments mandate restrictions. The JCA framework willenforce the restrictions specified in the installed jurisdictionpolicy files.

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

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

  • The constructor of each SPI implementation class should doself-integrity checking, as described inHow a Provider Can Do Self-IntegrityChecking.
  • The provider code should be written in such a way that providerclasses become unusable if instantiated by an application directly,bypassing JCA. SeeStep 1: Write Your ServiceImplementation Code in theSteps to Implement and Integratea Provider section.
  • The provider package must be signed by an entity trusted by theJCA framework. (SeeStep 6.1 throughStep 6.2.) U.S. vendors whose providers may beexported outside the U.S. first need to apply for U.S. governmentexport approval. (SeeStep 10.)

Appendix A: Thejava.security.properties File

Below is part of thejava.security file that showsthe default list of installed providers. It appears in every JREinstallation. The file also contains other entries, but forbrevity, we show only part of the file here. See the complete fileat:

<java-home>/lib/security/java.security     [Solaris, Linux, or macOS]<java-home>\lib\security\java.security     [Win32]

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

SeeStep 5 for an example of addinginformation about your provider to this file.

## This is the "master security properties file".## In this file, various security properties are set for use by# java.security classes. This is where users can statically register# Cryptography Package Providers ("providers" for short). The term# "provider" refers to a package or set of packages that supply a# concrete implementation of a subset of the cryptography aspects of# the Java Security API. A provider may, for example, implement one or# more digital signature algorithms or message digest algorithms.## Each provider must implement a subclass of the Provider class.# To register a provider in this master security properties file,# specify the Provider subclass name and priority in the format##    security.provider.<n>=<className>## This declares a provider, and specifies its preference# order n. The preference order is the order in which providers are# searched for requested algorithms (when no specific provider is# requested). The order is 1-based; 1 is the most preferred, followed# by 2, and so on.## <className> must specify the subclass of the Provider class whose# constructor sets the values of various properties that are required# for the Java Security API to look up the algorithms or other# facilities implemented by the provider.## There must be at least one provider specification in java.security.# There is a default provider that comes standard with the JDK. It# is called the "SUN" provider, and its Provider subclass# named Sun appears in the sun.security.provider package. Thus, the# "SUN" provider is registered via the following:##    security.provider.1=sun.security.provider.Sun## (The number 1 is used for the default provider.)## Note: Providers can be dynamically registered instead by calls to# either the addProvider or insertProviderAt method in the Security# class.## List of providers and their preference orders (see above):#security.provider.1=sun.security.pkcs11.SunPKCS11 \    ${java.home}/lib/security/sunpkcs11-solaris.cfgsecurity.provider.2=sun.security.provider.Sunsecurity.provider.3=sun.security.rsa.SunRsaSignsecurity.provider.4=com.sun.net.ssl.internal.ssl.Providersecurity.provider.5=com.sun.crypto.provider.SunJCEsecurity.provider.6=sun.security.jgss.SunProvidersecurity.provider.7=com.sun.security.sasl.Providersecurity.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRIsecurity.provider.9=sun.security.smartcardio.SunPCSC# Rest of file deleted

Copyright © 1993, 2020, Oracleand/or its affiliates. All rights reserved.
Contact Us

[8]ページ先頭

©2009-2025 Movatter.jp