Provider.ServiceClassjava.securityProperties FileThe 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:
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.
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.
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.
![]() | ![]() |
| Figure 1: Provider searching | Figure 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.
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.
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.
java.securityjava.security.specjava.security.interfacesjavax.cryptojavax.crypto.specjavax.crypto.interfacesjava.security,javax.crypto,javax.crypto.spec, andjavax.crypto.interfaces.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.
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:
Signature class provides access to thefunctionality of a digital signature algorithm.KeyFactory class supplies a DSA private orpublic key (from its encoding or transparent specification) in aformat usable by the initSign or initVerify methods, respectively,of a DSA Signature object.Cipher class provides access to thefunctionality of an encryption algorithm (such as AES)KeyAgreement class provides access to thefunctionality of a key agreement protocol (such asDiffie-Hellman)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:
MessageDigest - used to calculate the messagedigest (hash) of specified data.Signature - used to sign data and verify digitalsignatures.KeyPairGenerator - used to generate a pair ofpublic and private keys suitable for a specified algorithm.KeyFactory - used to convert opaque cryptographickeys of typeKey intokey specifications(transparent representations of the underlying key material), andvice versa.KeyStore - used to create and manage akeystore. A keystore is a database of keys. Private keys ina keystore have a certificate chain associated with them, whichauthenticates the corresponding public key. A keystore alsocontains certificates from trusted entities.CertificateFactory - used to create public keycertificates and Certificate Revocation Lists (CRLs).AlgorithmParameters - used to manage theparameters for a particular algorithm, including parameter encodingand decoding.AlgorithmParameterGenerator - used to generate aset of parameters suitable for a specified algorithm.SecureRandom - used to generate random orpseudo-random numbers.Cipher: used to encrypt or decrypt some specifieddata.KeyAgreement: used to execute a key agreement (keyexchange) protocol between 2 or more parties.KeyGenerator: used to generate a secret(symmetric) key suitable for a specified algorithm.Mac: used to compute themessage authenticationcode of some specified data.SecretKeyFactory: used to convert opaquecryptographic keys of typeSecretKey intokeyspecifications (transparent representations of the underlyingkey material), and vice versa.ExemptionMechanism: used to provide thefunctionality of an exemption mechanism such askeyrecovery,key weakening,key escrow, or any other(custom) exemption mechanism. Applications or applets that use anexemption mechanism may be granted stronger encryption capabilitiesthan those which don't. However, please note that cryptographicrestrictions are no longer required for most countries, and thusexemption mechanisms may only be useful in those few countrieswhose governments mandate restrictions.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.

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.
Follow the steps below to implement a provider and integrate itinto the JCA framework:
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:
SignatureSpiMessageDigestSpiKeyPairGeneratorSpiSecureRandomSpiAlgorithmParameterGeneratorSpiAlgorithmParametersSpiKeyFactorySpiCertificateFactorySpiKeyStoreSpiCipherSpiKeyAgreementSpiKeyGeneratorSpiMacSpiSecretKeyFactorySpiExemptionMechanismSpi(SeeEngine Classes and Corresponding SPIClasses in this document for information on the JCA and othercryptographic classes.)
In your subclass, you need to:
engine. SeeFurther Implementation Details andRequirements for additional information.Class 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.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
engineWrap andengineUnwrapmethods ofCipherSpi. Wrapping a key enables securetransfer of the key from one place to another. Information aboutwrapping and unwrapping keys is provided in theWrapping and Unwrapping Keyssection of theJava Cryptography Architecture ReferenceGuide.Decide on a name for your provider. This is the name to be usedby client applications to refer to your provider.
The third step is to create a subclass of thejava.security.Provider class.
Your subclass should be afinal class, and itsconstructor should
super, specifying the provider name (seeStep 2), version number, and a string ofinformation about the provider and algorithms it supports. Forexample: super("CryptoX", 1.0, "CryptoX provider v1.0, implementing " + "RSA encryption and key pair generation, and AES encryption.");The list below shows the various types of JCA services, wherethe actual algorithm name is substitued foralgName:
Signature.algNameMessageDigest.algNameKeyPairGenerator.algNameSecureRandom.algNameAlgorithmParameterGenerator.algNameAlgorithmParameters.algNameKeyFactory.algNameCertificateFactory.algNameKeyStore.algNameCipher.algNameKeyAgreement.algNameKeyGenerator.algNameMac.algNameSecretKeyFactory.algNameExemptionMechanism.algNameIn all of these exceptExemptionMechanism andCipher,algName, certType , orstoreType is the "standard" name of the algorithm,certificate type, or keystore type. SeeAppendix A of the Java CryptographyArchitecture Reference Guide for the standard names that shouldbe used.)
In the case ofExemptionMechanism,algNamerefers to the name of the exemption mechanism, which can be one ofthe following:KeyRecovery,KeyEscrow, orKeyWeakening. Case doesnot matter.
In the case ofCipher,algName may actuallyrepresent atransformation, and may be composed of analgorithm name, a particular mode, and a padding scheme. SeeAppendix A of the JavaCryptography Architecture Reference Guide for details.
The value of each property must be the fully qualified name ofthe class implementing the specified algorithm, certificate type,or keystore type. That is, it must be the package name followed bythe class name, where the two are separated by a period.
As an example, the default provider namedSUN implementsthe Digital Signature Algorithm (whose standard name isSHA256withDSA) in a class namedDSA in thesun.security.provider package. Its subclass ofProvider (which is the Sun class in thesun.security.provider package) sets theSignature.SHA256withDSA property to have the valuesun.security.provider.DSA via the following:
put("Signature.SHA256withDSA", "sun.security.provider.DSA")The list below shows more properties that can be defined for thevarious types of services, where the actual algorithm name issubstitued foralgName, certificate type forcertType, keystore type forstoreType, and attributename forattrName:
Signature.algName[one or more spaces]attrNameMessageDigest.algName[one or more spaces]attrNameKeyPairGenerator.algName[one or more spaces]attrNameSecureRandom.algName[one or more spaces]attrNameKeyFactory.algName[one or more spaces]attrNameCertificateFactory.certType[one or more spaces]attrNameKeyStore.storeType[one or more spaces]attrNameAlgorithmParameterGenerator.algName[one or morespaces] attrNameAlgorithmParameters.algName[one or more spaces]attrNameCipher.algName[one or more spaces]attrNameKeyAgreement.algName[one or more spaces]attrNameKeyGenerator.algName[one or more spaces]attrNameMac.algName[one or more spaces]attrNameSecretKeyFactory.algName[one or more spaces]attrNameExemptionMechanism.algName[one or more spaces]attrNameIn 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.
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 Format | Description |
|---|---|
Cipher.algName | A provider's subclass ofCipherSpiimplementsalgName with pluggable mode and padding |
Cipher.algName/mode | A provider's subclass ofCipherSpiimplementsalgName in the specifiedmode, withpluggable padding |
Cipher.algName//padding | A provider's subclass ofCipherSpiimplementsalgName with the specifiedpadding, withpluggable mode |
Cipher.algName/mode/padding | A 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:
Cipher.AES/ECB/PKCS5PaddingCipher.AES/CBC/PKCS5PaddingCipher.AES/CFB/PKCS5PaddingCipher.AES/OFB/PKCS5PaddingAnother 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:
Cipher.AESCipher.AES SupportedModes
Example: "ECB|CBC|CFB|OFB"Cipher.AES SupportedPaddings
Example: "NOPADDING|PKCS5Padding"ThegetInstance factory method of theCipher engine class follows these rules in order toinstantiate a provider's implementation ofCipherSpifor a transformation of the form "algorithm":
CipherSpi for the specified "algorithm".NoSuchAlgorithmExceptionexception.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":
CipherSpi for the specified"algorithm/mode/padding" transformation.CipherSpi for the sub-transformation"algorithm/mode".engineSetPadding(padding) on the newinstance.CipherSpi for the sub-transformation"algorithm//padding" (note the double slashes).engineSetMode(mode) on the new instance.CipherSpi for the sub-transformation"algorithm".engineSetMode(mode) andengineSetPadding(padding) on the newinstance.NoSuchAlgorithmExceptionexception.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.
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.
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.
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).
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.
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>.
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.
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.
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).
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.
The next steps describe how to install and configure your newprovider so that it is available via the JCA.
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.
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.
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.
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"; };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:
java.lang.RuntimePermission to get classprotection domains. The provider may need to get its own protectiondomain in the process of doing self-integrity checking.java.security.SecurityPermission to set providerproperties.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"; };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.
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.
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:
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.
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:
mac is the MAC object they received when theyrequested one via a call toMac.getInstance,i1,i2 andi3 are inputbyte arrays, andi1i1 and i2i1, i2, and i3For 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.
A provider should document all the key specifications supportedby its (secret-)key factory.
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.
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.
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.
A provider should document what types of certificates (and theirversion numbers, if relevant), can be created by the factory.
A provider should document any relevant information regardingthe keystore implementation, such as its underlying dataformat.
After writing, configuring, testing, installing and documentingyour provider software, make documentation available to yourcustomers.
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:
Each of these steps is described in the following sections:
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
. . . }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(); } });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();
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:
Sample code for each of these steps is presented and describedin the following sections:
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.
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"); }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(); }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):
The loop setup is the following:
Enumeration e = entriesVec.elements(); while (e.hasMoreElements()) { JarEntry je = (JarEntry) e.nextElement(); ... }The certificates for the signers of a JAR file 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'. ... } ...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; }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:
MyJCE.class.JarVerifier object with the providerURL in Step 1.X509Certificate object from the embeddedbyte arraybytesOfProviderCert.JarVerifier.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:
verify is null(invalid).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.
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.aliasNamewhereengineClassName 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.
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:
MessageDigest.getInstance("SHA256", "SUN")
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:
A signature algorithm often requires use of a message digestalgorithm. For example, theSHA256withDSA signature algorithmrequires theSHA256 message digest algorithm.
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.
A key pair generation algorithm often requires use of a messagedigest algorithm. For example, DSA keys are generated using theSHA-256 message digest algorithm.
An algorithm parameter generator often requires use of a messagedigest algorithm. For example, DSA parameters are generated usingthe SHA-256 message digest algorithm.
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.
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.
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.
An algorithm parameter generator'sengineGenerateParameters method must return anAlgorithmParameters instance.
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:
DSAPrivateKey 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,engineInitSign methodfor a DSS Signature class could accept any private keys that areinstances ofjava.security.interfaces.DSAPrivateKey.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.
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.
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.)
Provider.Service ClassSince 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.
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 }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.
DSAKeyPairGeneratorImplementationThis 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.
DSAParamsImplementationIf 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.
DSAPrivateKeyandDSAPublicKeyImplementationsIf 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
getX method from theDSAPrivateKey interface.getParams method from thejava.security.interfaces.DSAKeyinterface, sinceDSAPrivateKey extendsDSAKey. Note: ThegetParams methodreturns aDSAParams object, so you must also have aDSAParamsimplementation.getAlgorithm,getEncoded, andgetFormat methods from thejava.security.Keyinterface, sinceDSAPrivateKey extendsjava.security.PrivateKey, andPrivateKeyextendsKey.Similarly, for public DSA keys, you need to supply a class thatimplements:
getY method from theDSAPublicKeyinterface.getParams method from thejava.security.interfaces.DSAKeyinterface, sinceDSAPublicKey extends DSAKey. Note:ThegetParams method returns aDSAParamsobject, so you must also have aDSAParams implementation.getAlgorithm,getEncoded, andgetFormat methods from thejava.security.Keyinterface, sinceDSAPublicKey extendsjava.security.PublicKey, andPublicKeyextendsKey.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 , andRSAPublicKeyImplementationsIf 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:
getModulus andgetPrivateExponentmethods from theRSAPrivateKey interface.getAlgorithm,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:
RSAPrivateCrtKey extendsjava.security.interfaces.RSAPrivateKey.getPublicExponent,getPrimeP,getPrimeQ,getPrimeExponentP,getPrimeExponentQ, andgetCrtCoefficientmethods from theRSAPrivateKey interface.For public RSA keys, you need to supply a class thatimplements:
getModulus andgetPublicExponentmethods from theRSAPublicKeyinterface.getAlgorithm,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.
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.
DHPrivateKeyandDHPublicKeyImplementationsIf 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:
getX method from theDHPrivateKeyinterface.getParams method from thejavax.crypto.interfaces.DHKeyinterface, sinceDHPrivateKey extendsDHKey.getAlgorithm,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:
getY method from theDHPublicKeyinterface.getParams method from thejavax.crypto.interfaces.DHKeyinterface, sinceDHPublicKey extendsDHKey.getAlgorithm,getEncoded, andgetFormat methods from thejava.security.Keyinterface, sinceDHPublicKey extendsjava.security.PublicKey, andPublicKeyextendsKey.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.
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:
AlgorithmParameterSpec InterfaceAlgorithmParameterSpec 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.
DSAParameterSpec ClassThis 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.
IvParameterSpecClassThis class (which implements theAlgorithmParameterSpec interface) specifies theinitialization vector (IV) used with a cipher in feedback mode.
| Method | Description |
|---|---|
byte[] getIV() | Returns the initialization vector (IV). |
OAEPParameterSpecClassThis class specifies the set of parameters used with OAEPPadding, as defined in the PKCS #1 standard.
| Method | Description |
|---|---|
String getDigestAlgorithm() | Returns the message digest algorithm name. |
String getMGFAlgorithm() | Returns the mask generation function algorithm name. |
AlgorithmParameterSpec getMGFParameters() | Returns the parameters for the mask generation function. |
PSource getPSource() | Returns the source of encoding input P. |
PBEParameterSpecClassThis class (which implements theAlgorithmParameterSpec interface) specifies the set ofparameters used with a password-based encryption (PBE)algorithm.
| Method | Description |
|---|---|
int getIterationCount() | Returns the iteration count. |
byte[] getSalt() | Returns the salt. |
RC2ParameterSpecClassThis class (which implements theAlgorithmParameterSpec interface) specifies the set ofparameters used with the RC2 algorithm.
| Method | Description |
|---|---|
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. |
RC5ParameterSpecClassThis class (which implements theAlgorithmParameterSpec interface) specifies the set ofparameters used with the RC5 algorithm.
| Method | Description |
|---|---|
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. |
DHParameterSpecClassThis class (which implements theAlgorithmParameterSpec interface) specifies the set ofparameters used with the Diffie-Hellman algorithm.
| Method | Description |
|---|---|
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.
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:
KeySpecInterfaceThis 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:
KeySpec classes for your key type.Your_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.KeySpec 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.DSAPrivateKeySpecClassThis class (which implements theKeySpec Interface) specifies a DSAprivate key with its associated parameters. It has the followingmethods:
Method inDSAPrivateKeySpec | Description |
|---|---|
public BigInteger getX() | Returns the private key x. |
public BigInteger getP() | Returns the prime p. |
public BigInteger getQ() | Returns the sub-prime q. |
public BigInteger getG() | Returns the base g. |
These methods return the private keyx, and the DSAalgorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg.
This class (which implements theKeySpec Interface) specifies a DSApublic key with its associated parameters. It has the followingmethods:
Method inDSAPublicKeySpec | Description |
|---|---|
public BigInteger getY() | returns the public key y. |
public BigInteger getP() | Returns the prime p. |
public BigInteger getQ() | Returns the sub-prime q. |
public BigInteger getG() | Returns the base g. |
These methods return the public keyy, and the DSAalgorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg.
This class (which implements theKeySpec Interface) specifies an RSAprivate key. It has the following methods:
Method inRSAPrivateKeySpec | Description |
|---|---|
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.
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 inRSAPrivateCrtKeySpec | Description |
|---|---|
public BigInteger getPublicExponent() | Returns the public exponent. |
public BigInteger getPrimeP() | Returns the prime P. |
public BigInteger getPrimeQ() | Returns the prime Q. |
public BigInteger getPrimeExponentP() | Returns the primeExponentP. |
public BigInteger getPrimeExponentQ() | Returns the primeExponentQ. |
public BigInteger getCrtCoefficient() | Returns the crtCoefficient. |
These methods return the public 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.
This class (which implements theKeySpec Interface) specifies an RSApublic key. It has the following methods:
Method inRSAPublicKeySpec | Description |
|---|---|
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.
This abstract class (which implements theKeySpec Interface) represents a publicor private key in encoded format.
Method inEncodedKeySpec | Description |
|---|---|
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.
PKCS8EncodedKeySpec ClassThis 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".
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.
DHPrivateKeySpecClassThis class (which implements theKeySpecinterface) specifies a Diffie-Hellman private key with itsassociated parameters.
Method inDHPrivateKeySpec | Description |
|---|---|
BigInteger getG() | Returns the base generatorg. |
BigInteger getP() | Returns the prime modulusp. |
BigInteger getX() | Returns the private valuex. |
DHPublicKeySpecClassThis class (which implements theKeySpecinterface) specifies a Diffie-Hellman public key with itsassociated parameters.
Method inDHPublicKeySpec | Description |
|---|---|
BigInteger getG() | Returns the base generatorg. |
BigInteger getP() | Returns the prime modulusp. |
BigInteger getY() | Returns the public valuey. |
DESKeySpecClassThis class (which implements theKeySpecinterface) specifies a DES key.
Method inDESKeySpec | Description |
|---|---|
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. |
DESedeKeySpecClassThis class (which implements theKeySpecinterface) specifies a DES-EDE (Triple DES) key.
Method inDESedeKeySpec | Description |
|---|---|
byte[] getKey() | Returns the DES-EDE key. |
static boolean isParityAdjusted(byte[] key, intoffset) | Checks if the given DES-EDE key is parity-adjusted. |
PBEKeySpecClassThis 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 inPBEKeySpec | Description |
|---|---|
void clearPassword | Clears the internal copy of the password. |
int getIterationCount | Returns the iteration count or 0 if not specified. |
int getKeyLength | Returns the to-be-derived key length or 0 if notspecified. |
char[] getPassword | Returns a copy of the password. |
byte[] getSalt | Returns a copy of the salt or null if not specified. |
SecretKeySpecClassThis 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 inSecretKeySpec | Description |
|---|---|
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. |
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:
SecretKeySpec,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.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.
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");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.
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:
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