Provider Class
Security Class
MessageDigest
Class
Signature Class
AlgorithmParameterSpec
Interface
DSAParameterSpec
Class
AlgorithmParameters
Class
AlgorithmParameterGenerator
Class
Key Interfaces
Key Specification Interfaces
and Classes
KeySpec Interface
DSAPrivateKeySpec
Class
DSAPublicKeySpec
Class
RSAPrivateKeySpec
Class
RSAPrivateCrtKeySpec
Class
RSAMultiPrimePrivateCrtKeySpec
Class
RSAPublicKeySpec
Class
EncodedKeySpec
Class
PKCS8EncodedKeySpec
Class
X509EncodedKeySpec
Class
KeyFactory Class
CertificateFactory
Class
KeyPair Class
KeyPairGenerator Class
KeyStore Class
SecureRandom
Class
Cipher Class
CipherStream Classes
CipherInputStream Class
CipherOutputStream Class
KeyGenerator Class
SecretKeyFactory Class
SealedObject Class
KeyAgreement Class
Mac Class
MessageDigest
Object
Key Specifications and KeyFactory
The Security API is a core API of the Java programming language, built around the
java.securitypackage (and its subpackages). This API is designed to allow developers to incorporate both low-level and high-level security functionality into their programs.The first release of Security API in JDK 1.1 introduced the "Java Cryptography Architecture" (JCA), a framework for accessing and developing cryptographic functionality for the Java platform. In JDK 1.1, the JCA included APIs for digital signatures and message digests.
In subsequent releases, the Java 2 SDK significantly extended the Java Cryptography Architecture, as described in this document. It also upgraded the certificate management infrastructure to support X.509 v3 certificates, and introduced a new Java Security Architecture for fine-grain, highly configurable, flexible, and extensible access control.
The Java Cryptography Architecture encompasses the parts of the Java 2 SDK Security API related to cryptography, as well as a set of conventions and specifications provided in this document. It includes a "provider" architecture that allows for multiple and interoperable cryptography implementations.
The JavaTM Cryptography Extension (JCE) provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Support for encryption includes symmetric, asymmetric, block, and stream ciphers. The software also supports secure streams and sealed objects.
JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has been integrated into the Java 2 SDK since the 1.4 release.
The JCE API covers:
- Symmetric bulk encryption, such as DES, RC2, and IDEA
- Symmetric stream encryption, such as RC4
- Asymmetric encryption, such as RSA
- Password-based encryption (PBE)
- Key Agreement
- Message Authentication Codes (MAC)
J2SE 5 comes standard with a JCE provider named "
SunJCE", which comes pre-installed and registered and which supplies the following cryptographic services:
- An implementation of the DES (FIPS PUB 46-1), Triple DES, and Blowfish encryption algorithms in the Electronic Code Book (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), Output Feedback (OFB), and Propagating Cipher Block Chaining (PCBC) modes. (Note: Throughout this document, the terms "Triple DES" and "DES-EDE" will be used interchangeably.)
- Key generators for generating keys suitable for the DES, Triple DES, Blowfish, HMAC-MD5, and HMAC-SHA1 algorithms.
- An implementation of the MD5 with DES-CBC password-based encryption (PBE) algorithm defined in PKCS #5.
- "Secret-key factories" providing bi-directional conversions between opaque DES, Triple DES and PBE key objects and transparent representations of their underlying key material.
- An implementation of the Diffie-Hellman key agreement algorithm between two or more parties.
- A Diffie-Hellman key pair generator for generating a pair of public and private values suitable for the Diffie-Hellman algorithm.
- A Diffie-Hellman algorithm parameter generator.
- A Diffie-Hellman "key factory" providing bi-directional conversions between opaque Diffie-Hellman key objects and transparent representations of their underlying key material.
- Algorithm parameter managers for Diffie-Hellman, DES, Triple DES, Blowfish, and PBE parameters.
- An implementation of the HMAC-MD5 and HMAC-SHA1 keyed-hashing algorithms defined in RFC 2104.
- An implementation of the padding scheme described in PKCS #5.
- A keystore implementation for the proprietary keystore type named "JCEKS".
A Note on Terminology
The JCE within the JDK includes two software components:
Throughout this document, the term "JCE" by itself refers to the JCE framework in J2SE 5. Whenever the JCE provider supplied with J2SE 5 is mentioned, it will be referred to explicitly as the "SunJCE" provider.
- the framework that defines and supports cryptographic services that providers can supply implementations for. This framework includes everything in the
javax.cryptopackage.- a provider named "SunJCE"
Note: The most recent version of this JCA specification can be found online at: http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html.
The Java Cryptography Architecture (JCA) was designed around these principles:
- implementation independence and interoperability
- algorithm independence and extensibility
Implementation independence and algorithm independence are complementary; you can use cryptographic services, such as digital signatures and message digests, without worrying about the implementation details or even the algorithms that form the basis for these concepts. When complete algorithm-independence is not possible, the JCA provides standardized, algorithm-specific APIs. When implementation-independence is not desirable, the JCA lets developers indicate a specific implementation.
Algorithm independence is achieved by defining types of cryptographic "engines" (services), and defining classes that provide the functionality of these cryptographic engines. These classes are called engine classes, and examples are the
MessageDigest,Signature,KeyFactory, andKeyPairGeneratorclasses.Implementation independence is achieved using a "provider"-based architecture. The term Cryptographic Service Provider (used interchangeably with "provider" in this document) refers to a package or set of packages that implement one or more cryptographic services, such as digital signature algorithms, message digest algorithms, and key conversion services. A program may simply request a particular type of object (such as a
Signatureobject) implementing a particular service (such as the DSA signature algorithm) and get an implementation from one of the installed providers. If desired, a program may instead request an implementation from a specific provider. Providers may be updated transparently to the application, for example when faster or more secure versions are available.Implementation interoperability means that various implementations can work with each other, use each other's keys, or verify each other's signatures. This would mean, for example, that for the same algorithms, a key generated by one provider would be usable by another, and a signature generated by one provider would be verifiable by another.
Algorithm extensibility means that new algorithms that fit in one of the supported engine classes can be added easily.
Cryptographic Service Providers
The Java Cryptography Architecture introduced the notion of a Cryptographic Service Provider (used interchangeably with "provider" in this document). This term refers to a package (or a set of packages) that supplies a concrete implementation of a subset of the cryptography aspects of the Security API.
For example, in JDK 1.1 a provider could contain an implementation of one or more digital signature algorithms, message digest algorithms, and key generation algorithms. Java 2 SDK adds five additional types of services: key factories, keystore creation and management, algorithm parameter management, algorithm parameter generation, and certificate factories. It also enables a provider to supply a random number generation (RNG) algorithm. Previously, RNGs were not provider-based; a particular algorithm was hard-coded in the JDK.
As previously noted, a program may simply request a particular type of object (such as a
Signatureobject) for a particular service (such as the DSA signature algorithm) and get an implementation from one of the installed providers. Alternatively, the program can request the objects from a specific provider. (Each provider has a name used to refer to it.)Sun's version of the Java runtime environment comes standard with a default provider, named
SUN. Other Java runtime environments may not necessarily supply theSUNprovider. TheSUNprovider package includes:
- An implementation of the Digital Signature Algorithm (DSA), described in NIST FIPS 186.
- An implementation of the MD5 (RFC 1321) and SHA-1 (NIST FIPS 180-1) message digest algorithms.
- A DSA key pair generator for generating a pair of public and private keys suitable for the DSA algorithm.
- A DSA algorithm parameter generator.
- A DSA algorithm parameter manager.
- A DSA key factory providing bi-directional conversions between (opaque) DSA private and public key objects and their underlying key material.
- An implementation of the proprietary "SHA1PRNG" pseudo-random number generation algorithm, following the recommendations in the IEEE P1363 standard (Appendix G.7).
- A certificate path builder and validator for PKIX, as defined in the Internet X.509 Public Key Infrastructure Certificate and CRL Profile (available as a draft from Internet Engineering Task Force at the time of this writing.).
- A certificate store implementation for retrieving certificates and CRLs from Collection and LDAP directories, using the PKIX LDAP V2 Schema (RFC 2587).
- A certificate factory for X.509 certificates and Certificate Revocation Lists (CRLs).
- A keystore implementation for the proprietary keystore type named
JKS.Each SDK installation has one or more provider packages installed. New providers may be added statically or dynamically (see the Provider and Security classes). The Java Cryptography Architecture offers a set of APIs that allow users to query which providers are installed and what services they support.
Clients may configure their runtime with different providers, and specify a preference order for each of them. The preference order is the order in which providers are searched for requested services when no specific provider is requested.
Key Management
A database called a "keystore" can be used to manage a repository of keys and certificates. A keystore is available to applications that need it for authentication or signing purposes.
Applications can access a keystore via an implementation of the
KeyStoreclass, which is in thejava.securitypackage. A defaultKeyStoreimplementation is provided by Sun Microsystems. It implements the keystore as a file, using a proprietary keystore type (format) named "JKS".Applications can choose different types of keystore implementations from different providers, using the
getInstancefactory method supplied in theKeyStoreclass.See the Key Management section for more information.
This section covers the major concepts introduced in the API.
Engine Classes and Algorithms
An engine class defines a cryptographic service in an abstract fashion (without a concrete implementation).
A cryptographic service is always associated with a particular algorithm or type, and it either provides cryptographic operations (like those for digital signatures or message digests), generates or supplies the cryptographic material (keys or parameters) required for cryptographic operations, or generates data objects (keystores or certificates) that encapsulate cryptographic keys (which can be used in a cryptographic operation) in a secure fashion. For example, two of the engine classes are the
SignatureandKeyFactoryclasses. TheSignatureclass provides access to the functionality of a digital signature algorithm. A DSAKeyFactorysupplies a DSA private or public key (from its encoding or transparent specification) in a format usable by theinitSignorinitVerifymethods, respectively, of a DSASignatureobject.The Java Cryptography Architecture encompasses the classes of the Java 2 SDK Security package related to cryptography, including the engine classes. Users of the API request and use instances of the engine classes to carry out corresponding operations. The following engine classes are defined in Java 2 SDK:
In the 1.4 release of the Java 2 SDK, the following new engines were added:
MessageDigest: used to calculate the message digest (hash) of specified data.
Signature: used to sign data and verify digital signatures.
KeyPairGenerator: used to generate a pair of public and private keys suitable for a specified algorithm.
KeyFactory: used to convert opaque cryptographic keys of typeKeyinto key specifications (transparent representations of the underlying key material), and vice versa.
CertificateFactory: used to create public key certificates and Certificate Revocation Lists (CRLs).
KeyStore: used to create and manage a keystore.A keystore is a database of keys. Private keys in a keystore have a certificate chain associated with them, which authenticates the corresponding public key. A keystore also contains certificates from trusted entities.
AlgorithmParameters: used to manage the parameters for a particular algorithm, including parameter encoding and decoding.
AlgorithmParameterGenerator: used to generate a set of parameters suitable for a specified algorithm.
SecureRandom: used to generate random or pseudo-random numbers.
CertPathBuilder: used to build certificate chains (also known as certification paths).
CertPathValidator: used to validate certificate chains.
CertStore: used to retrieveCertificates andCRLs from a repository.An engine class provides the interface to the functionality of a specific type of cryptographic service (independent of a particular cryptographic algorithm). It defines Application Programming Interface (API) methods that allow applications to access the specific type of cryptographic service it provides. The actual implementations (from one or more providers) are those for specific algorithms. The
Note: A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).
Signatureengine class, for example, provides access to the functionality of a digital signature algorithm. The actual implementation supplied in aSignatureSpisubclass would be that for a specific kind of signature algorithm, such as SHA-1 with DSA, SHA-1 with RSA, or MD5 with RSA.The application interfaces supplied by an engine class are implemented in terms of a Service Provider Interface (SPI). That is, for each engine class, there is a corresponding abstract SPI class, which defines the SPI methods that cryptographic service providers must implement.
An instance of an engine class, the API object, encapsulates (as a private field) an instance of the corresponding SPI class, the SPI object. All API methods of an API object are declared final and their implementations invoke the corresponding SPI methods of the encapsulated SPI object. An instance of an engine class (and of its corresponding SPI class) is created by a call to the
getInstancefactory method of the engine class.The name of each SPI class is the same as that of the corresponding engine class, followed by
Spi. For example, the SPI class corresponding to theSignatureengine class is theSignatureSpiclass.Each SPI class is abstract. To supply the implementation of a particular type of service, for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.
Another example of an engine class is the
MessageDigestclass, which provides access to a message digest algorithm. Its implementations, inMessageDigestSpisubclasses, may be those of various message digest algorithms such as SHA-1, MD5, or MD2.As a final example, the
KeyFactoryengine class supports the conversion from opaque keys to transparent key specifications, and vice versa. (See the Key Specification Interfaces and Classes section.) TheKeyFactorySpisubclass supplies an actual implementation for a specific type of keys, for example, DSA public and private keys.Implementations and Providers
Implementations for various cryptographic services are provided by JCA Cryptographic Service Providers. Cryptographic service providers are essentially packages that supply one or more cryptographic service implementations. The Engine Classes and Algorithms section includes a list of implemenations supplied by SUN, the Java 2 SDK's default provider.
Other providers may define their own implementations of these services or of other services, such as one of the RSA-based signature algorithms or the MD2 message digest algorithm.
Factory Methods to Obtain Implementation Instances
For each engine class in the API, a particular implementation is requested and instantiated by calling a factory method on the engine class. A factory method is a static method that returns an instance of a class.
The basic mechanism for obtaining an appropriate
Signatureobject, for example, is as follows: A user requests such an object by calling thegetInstancemethod in theSignatureclass, specifying the name of a signature algorithm (such as "SHA1withDSA"), and, optionally, the name of the provider or theProviderclass. ThegetInstancemethod finds an implementation that satisfies the supplied algorithm and provider parameters. If no provider is specified,getInstancesearches the registered providers, in preference order, for one with an implementation of the specified algorithm. See TheProviderClass for more information about registering providers.Cryptographic Concepts
This section provides a high-level description of the concepts implemented by the API, and the exact meaning of the technical terms used in the API specification.
Encryption and Decryption
Encryption is the process of taking data (called cleartext) and a short string (a key), and producing data (ciphertext) meaningless to a third-party who does not know the key. Decryption is the inverse process: that of taking ciphertext and a short key string, and producing cleartext.
Password-Based Encryption
Password-Based Encryption (PBE) derives an encryption key from a password. In order to make the task of getting from password to key very time-consuming for an attacker, most PBE implementations will mix in a random number, known as a salt, to create the key.
Cipher
Encryption and decryption are done using a cipher. A cipher is an object capable of carrying out encryption and decryption according to an encryption scheme (algorithm).
Key Agreement
Key agreement is a protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information.
Message Authentication Code
A Message Authentication Code (MAC) provides a way to check the integrity of information transmitted over or stored in an unreliable medium, based on a secret key. Typically, message authentication codes are used between two parties that share a secret key in order to validate information transmitted between these parties.
A MAC mechanism that is based on cryptographic hash functions is referred to as HMAC. HMAC can be used with any cryptographic hash function, e.g., MD5 or SHA-1, in combination with a secret shared key. HMAC is specified in RFC 2104.
Here are the differences in JCE between v1.4 and J2SE 5:
- Support for Additional Features of PKCS #11
- Integration with Solaris Cryptographic Framework
- Support for ECC Algorithm
- Added
ByteBufferAPI Support to JCA/JCE- Support for
RC2ParameterSpec- Full support for XML Encryption RSA-OAEP Algorithm
- Simplified retrieval of
PKCS8EncodedKeySpecfromjavax.crypto.EncryptedPrivateKeyInfo- Support for "PBEWithSHA1AndDESede" and "PBEWithSHA1AndRC2_40" Ciphers
- Support for XML Encryption Padding Algorithm in JCE Block Encryption Ciphers
- Ability to Dynamically Determine Maximum Allowable Key Length
- Support for RSA encryption to SunJCE provider
- Support for RC2 and ARCFOUR Ciphers to SunJCE provider
- Support for HmacSHA256, HmacSHA384 and HmacSHA512
Support for PKCS #11 Based Crypto Provider
In J2SE 5, a JCA/JCE provider,SunPKCS11that acts as a generic gateway to the native PKCS#11 API has been implemented. PKCS#11 is the de-facto standard for crypto accelerators and also widely used to access cryptographic smartcards. The administrator/user can configure this provider to talk any PKCS#11 v2.x compliant token.Here's an example of the configuration file format.
Integration with Solaris Cryptographic Framework
On Solaris 10, the default Java security provider configuration has been changed in J2SE 5 to include an instance of the
SunPKCS11provider that uses the Solaris Cryptographic Framework. It is the provider with the highest precedence thereby allowing all existing applications to take advantage of the improved performance on Solaris 10. There is no change in behavior on Solaris 8 and Solaris 9 systems.As a result of this change, many cryptographic operations will execute several times as fast as before on all Solaris 10 systems. On systems with cryptographic hardware acceleration, the performance improvements may be two orders of magnitude.
Support for ECC Algorithm
Prior to J2SE 5, the JCA/JCE framework did not include support classes for ECC-related crypto algorithms. Users who wanted to use ECC had to depend on a 3rd party library that implemented ECC. However, this did not integrate well with existing JCA/JCE framework.Starting in J2SE 5, full support for ECC classes to facilitate providers that support ECC have been included.
The following interfaces have been added:
- java.security.spec.ECField
- java.security.interfaces.ECKey
- java.security.interfaces.ECPublicKey
- java.security.interfaces.ECPrivateKey
The following classes have been added:
Added ByteBuffer API Support
Methods that take ByteBuffer arguments have been added to the JCE API and SPI classes that are used to process bulk data. Providers can override the engine* methods if they can process ByteBuffers more efficiently than byte[].The following JCE methods have been added to support ByteBuffers:
javax.crypto.Mac.update(ByteBuffer input)The following JCA methods have been added to support ByteBuffers:
javax.crypto.MacSpi.engineUpdate(ByteBuffer input)
javax.crypto.Cipher.update(ByteBuffer input, ByteBuffer output)
javax.crypto.Cipher.doFinal(ByteBuffer input, ByteBuffer output)
javax.crypto.CipherSpi.engineUpdate(ByteBuffer input, ByteBuffer output)
javax.crypto.CipherSpi.engineDoFinal(ByteBuffer input, ByteBuffer output)java.security.MessageDigest.update(ByteBuffer input)
java.security.Signature.update(ByteBuffer data)
java.security.SignatureSpi.engineUpdate(ByteBuffer data)
java.security.MessageDigestSpi.engineUpdate(ByteBuffer input)Support for RC2ParameterSpec
The RC2 algorithm implementation has been enhanced in J2SE 5 to support effective key size that is distinct from the length of the input key.Full support for XML Encryption RSA-OAEP Algorithm
Prior to J2SE 5, JCE did not define any parameter class for specifying the non-default values used in OAEP and PSS padding as defined in PKCS#1 v2.1 and the RSA-OAEP Key Transport algorithm in the W3C Recommendation for XML Encryption. Therefore, there was no generic way for applications to specify non-default values used in OAEP and PSS padding.
In J2SE 5, new parameter classes have been added to fully support OAEP padding and the existing PSS parameter class was enhanced with APIs to fully support RSA PSS signature implementations. Also, SunJCE provider has been enhanced to accept
OAEPParameterSpecwhen OAEPPadding is used.The following classes have been added:
The following methods and fields have been added to
java.security.spec.PSSParameterSpec:public static final PSSParameterSpec DEFAULT
public PSSParameterSpec(String mdName, String mgfName,
AlgorithmParameterSpec mgfSpec,
int saltLen, int trailerField)
public String getDigestAlgorithm()
public String getMGFAlgorithm()
public AlgorithmParameterSpec getMGFParameters()
public int getTrailerField()
PKCS8EncodedKeySpec
from javax.crypto.EncryptedPrivateKeyInfoIn J2SE 5,javax.crypto.EncryptedPrivateKeyInfoonly has one method,getKeySpec(Cipher)for retrieving thePKCS8EncodedKeySpecfrom the encrypted data. This limitation requires users to specify a cipher which is initialized with the decryption key and parameters. When users only have the decryption key, they would have to first retrieve the parameters out of thisEncryptedPrivateKeyInfoobject, get hold of matchingCipherimplementation, initialize it, and then call thegetKeySpec(Cipher)method.To make
EncyptedPrivateKeyInfoeasier to use and to make its API consistent withjavax.crypto.SealedObject, the following methods have been added to javax.crypto.EncryptedPrivateKeyInfo:getKeySpec(Key decryptKey)
getKeySpec(Key decryptKey, String provider)
In 1.4.2, the crypto jurisdiction policy files bundled in J2SE limits the maximum key length (and parameter value for some crypto algorithms) that can be used for encryption/decryption. Users who desire unlimited version of crypto jurisdiction files must download them separately.Also, an exception is thrown when the Cipher instance is initialized with keys (or parameters for certain crypto algorithms) exceeds the maximum values allowed by the crypto jurisdiction files.
In J2SE 5, the
Cipherclass has been updated to provide the maximum values for key length and parameters configured in the jurisdiction policy files, so that applications can use a shorter key length when the default (limited strength) jurisdiction policy files are installed.The following methods have been added to javax.crypto.Cipher:
public static final int getMaxAllowedKeyLength(String transformation)
throws NoSuchAlgorithmException
public static final AlgorithmParameterSpec
getMaxAllowedParameterSpec(String transformation)
throws NoSuchAlgorithmException;
Support for HmacSHA-256, HmacSHA-384, and HmacSHA-512 algorithms have been added to J2SE 5.
A publicly accessible RSA encryption implementation has been added to the SunJCE provider.
The SunJCE provider now implements the RC2 (RFC 2268) and ARCFOUR (an RC4TM-compatible algorithm) ciphers.
Added support for PBEWithSHA1AndDESede and PBEWithSHA1AndRC2_40 ciphers in SunJCE provider.
W3C XML Encryption defines a new padding algorithm, "ISO10126Padding," for block ciphers. See 5.2 Block Encryption Algorithms for more information.To allow Sun's provider to be used by XML Encryption implementations and JSR 106 providers, we have added support for this padding in J2SE 5.
This section discusses the core classes and interfaces provided in the Java Cryptography Architecture:
engine classes
- the
ProviderandSecurityclasses
- the
MessageDigest,Signature,KeyPairGenerator,KeyFactory,AlgorithmParameters,AlgorithmParameterGenerator,CertificateFactory,KeyStore,SecureRandom,CertPathBuilder,CertPathValidator, andCertStore.
the Keyinterfaces and classes
the Algorithm Parameter Specification Interfaces and Classes and the Key Specification Interfaces and Classes This section shows the signatures of the main methods in each class and interface. Examples for some of these classes (
MessageDigest,Signature,KeyPairGenerator,SecureRandom,KeyFactory, and key specification classes) are supplied in the corresponding Examples sections. The complete reference documentation for the relevant Security API packages can be found in:
java.security package summaryjava.security.spec package summaryjava.security.interfaces package summaryjava.security.cert package summary
Provider ClassThe term "Cryptographic Service Provider" (used interchangeably with "provider" in this document) refers to a package or set of packages that supply a concrete implementation of a subset of the Java 2 SDK Security API cryptography features. The
Providerclass is the interface to such a package or set of packages. It has methods for accessing the provider name, version number, and other information. Please note that in addition to registering implementations of cryptographic services, theProviderclass can also be used to register implementations of other security services that might get defined as part of the Java 2 SDK Security API or one of its extensions.To supply implementations of cryptographic services, an entity (e.g., a development group) writes the implementation code and creates a subclass of the
Providerclass. The constructor of theProvidersubclass sets the values of various properties; the Java 2 SDK Security API uses these values to look up the services that the provider implements. In other words, the subclass specifies the names of the classes implementing the services.There are several types of services that can be implemented by provider packages; for more information, see Engine Classes and Algorithms.
The different implementations may have different characteristics. Some may be software-based, while others may be hardware-based. Some may be platform-independent, while others may be platform-specific. Some provider source code may be available for review and evaluation, while some may not. The Java Cryptography Architecture (JCA) lets both end-users and developers decide what their needs are.
In this section we explain how end-users install the cryptography implementations that fit their needs, and how developers request the implementations that fit theirs.
Note: For information about implementing a provider, see the guide How To Implement a Provider for the Java Cryptography Architecture.
How Provider Implementations Are Requested and Supplied
For each engine class in the API, a particular implementation is requested and instantiated by calling agetInstancemethod on the engine class, specifying the name of the desired algorithm and, optionally, the name of the provider (or theProviderclass) whose implementation is desired.If no provider is specified,
getInstancesearches the registered providers for an implementation of the requested cryptographic service associated with the named algorithm. In any given Java Virtual Machine (JVM), providers are installed in a given preference order, the order in which the provider list is searched if a specific provider is not requested. For example, suppose there are two providers installed in a JVM,PROVIDER_1andPROVIDER_2. Assume that:Now let's look at three scenarios:
PROVIDER_1implements SHA1withDSA, SHA-1, MD5, DES, and DES3.
PROVIDER_1has preference order 1 (the highest priority).
PROVIDER_2implements SHA1withDSA, MD5withRSA, MD2withRSA, MD2, MD5, RC4, RC5, DES, and RSA.PROVIDER_2has preference order 2.
- If we are looking for an MD5 implementation. Both providers supply such an implementation. The
PROVIDER_1implementation is returned sincePROVIDER_1has the highest priority and is searched first.- If we are looking for an MD5withRSA signature algorithm,
PROVIDER_1is first searched for it. No implementation is found, soPROVIDER_2is searched. Since an implementation is found, it is returned.- Suppose we are looking for a SHA1withRSA signature algorithm. Since no installed provider implements it, a
NoSuchAlgorithmExceptionis thrown.The
getInstancemethods that include a provider argument are for developers who want to specify which provider they want an algorithm from. A federal agency, for example, will want to use a provider implementation that has received federal certification. Let's assume that the SHA1withDSA implementation fromPROVIDER_1has not received such certification, while the DSA implementation ofPROVIDER_2has received it.A federal agency program would then have the following call, specifying
PROVIDER_2since it has the certified implementation:Signature dsa = Signature.getInstance("SHA1withDSA", "PROVIDER_2");In this case, if
PROVIDER_2was not installed, aNoSuchProviderExceptionwould be thrown, even if another installed provider implements the algorithm requested.A program also has the option of getting a list of all the installed providers (using the
getProvidersmethod in theSecurityclass) and choosing one from the list.Installing Providers
There are two parts to installing a provider: installing the provider package classes, and configuring the provider.
Installing the Provider Classes
There are two possible ways to install the provider classes:
- Place a zip or JAR file containing the classes anywhere in your classpath.
- Supply your provider JAR file as an "installed" or "bundled" extension. For more information on how to deploy an extension, see How is an extension deployed?.
Configuring the Provider
The next step is to add the provider to your list of approved providers. This step can be done statically by editing the
java.securityfile in thelib/securitydirectory of the SDK; therefore, if the SDK is installed in a directory calledj2sdk1.2, the file would bej2sdk1.2/lib/security/java.security. One of the types of properties you can set injava.securityhas the following form:security.provider.n=masterClassNameThis 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.
masterClassNamemust specify the provider's master class. The provider's documentation will specify its master class. This class is always a subclass of theProviderclass. The subclass constructor sets the values of various properties that are required for the Java Cryptography API to look up the algorithms or other facilities the provider implements.Suppose that the master class is
COM.acme.provider.Acme, and that you would like to configureAcmeas your third preferred provider. To do so, you would add the following line to thejava.securityfile:Providers may also be registered dynamically. To do so, call either thesecurity.provider.3=COM.acme.provider.AcmeaddProviderorinsertProviderAtmethod in theSecurityclass. This type of registration is not persistent and can only be done by "trusted" programs. See Security.
ProviderClass MethodsEach
Providerclass instance has a (currently case-sensitive) name, a version number, and a string description of the provider and its services. You can query theProviderinstance for this information by calling the following methods:public String getName() public double getVersion() public String getInfo()
Security ClassThe
Securityclass manages installed providers and security-wide properties. It only contains static methods and is never instantiated. The methods for adding or removing providers, and for settingSecurityproperties, can only be executed by a trusted program. Currently, a "trusted program" is eitherThe determination that code is considered trusted to perform an attempted action (such as adding a provider) requires that the applet is granted permission for that particular action.
- a local application not running under a security manager, or
- an applet or application with permission to execute the specified method (see below).
For example, in the Policy reference implementation, the policy configuration file(s) for a SDK installation specify what permissions (which types of system resource accesses) are allowed by code from specified code sources. (See below and the "Default Policy Implementation and Policy File Syntax" and "Java Security Architecture Specification" files for more information.)
Code being executed is always considered to come from a particular "code source". The code source includes not only the location (URL) where the applet originated from, but also a reference to the public key(s) corresponding to the private key(s) used to sign the code. Public keys in a code source are referenced by (symbolic) alias names from the user's keystore .
In a policy configuration file, a code source is represented by two components: a code base (URL), and an alias name (preceded by
signedBy), where the alias name identifies the keystore entry containing the public key that must be used to verify the code's signature.Each "grant" statement in such a file grants a specified code source a set of permissions, specifying which actions are allowed.
Here is a sample policy configuration file:
This configuration file specifies that only code loaded from a signed JAR file from beneath thegrant codeBase "file:/home/sysadmin/", signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; permission java.security.SecurityPermission "putProviderProperty.*"; };/home/sysadmin/directory on the local file system can add or remove providers or set provider properties. (Note that the signature of the JAR file can be verified using the public key referenced by the alias namesysadminin the user's keystore.)Either component of the code source (or both) may be missing. Here's an example of a configuration file where
codeBaseis missing:If this policy is in effect, code that comes in a JAR File signed bygrant signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };sysadmincan add/remove providers--regardless of where the JAR File originated.Here's an example without a signer:
In this case, code that comes from anywhere within thegrant codeBase "file:/home/sysadmin/" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };/home/sysadmin/directory on the local filesystem can add/remove providers. The code does not need to be signed.An example where neither
codeBasenorsignedByis included is:Here, with both code source components missing, any code (regardless of where it originates, or whether or not it is signed, or who signed it) can add/remove providers.grant { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };Managing Providers
The following tables summarize the methods in the
Securityclass you can use to query whichProviders are installed, as well as to install or remove providers at runtime.
Quering Providers Method Description static Provider[] getProviders()Returns an array containing all the installed providers (technically, the Providersubclass for each package provider). The order of theProviders in the array is their preference order.static Provider getProvider
(String providerName)Returns the ProvidernamedproviderName. It returnsnullif theProvideris not found.
Adding Providers Method Description static int
addProvider(Provider provider)Adds a Providerto the end of the list of installedProviders. It returns the preference position in which theProviderwas added, or-1if theProviderwas not added because it was already installed.static int insertProviderAt
(Provider provider, int position)Adds a new
Providerat a specified position. If the given provider is installed at the requested position, the provider formerly at that position and all providers with a position greater thanpositionare shifted up one position (towards the end of the list). This method returns the preference position in which theProviderwas added, or-1if theProviderwas not added because it was already installed.
Removing Providers Method Description static void removeProvider(String name)Removes the Providerwith the specified name. It returns silently if the provider is not installed. When the specified provider is removed, all providers located at a position greater than where the specified provider was are shifted down one position (towards the head of the list of installed providers).
Note: If you want to change the preference position of a provider, you must first remove it, and then insert it back in at the new preference position.
Security Properties
The
Securityclass maintains a list of system-wide security properties. These properties are accessible and settable by a trusted program via the following methods:static String getProperty(String key) static void setProperty(String key, String datum)
MessageDigest ClassThe
MessageDigestclass is an engine class designed to provide the functionality of cryptographically secure message digests such as SHA-1 or MD5. A cryptographically secure message digest takes arbitrary-sized input (a byte array), and generates a fixed-size output, called a digest or hash. A digest has two properties:
- It should be computationally infeasible to find two messages that hashed to the same value.
- The digest should not reveal anything about the input that was used to generate it.
Message digests are used to produce unique and reliable identifiers of data. They are sometimes called the "digital fingerprints" of data.
Creating a
MessageDigestObjectThe first step for computing a digest is to create a message digest instance. As with all engine classes, the way to get a
MessageDigestobject for a particular type of message digest algorithm is to call thegetInstancestatic factory method on theMessageDigestclass:static MessageDigest getInstance(String algorithm)
Note: The algorithm name is not case-sensitive. For example, all the following calls are equivalent:MessageDigest.getInstance("SHA-1") MessageDigest.getInstance("sha-1") MessageDigest.getInstance("sHa-1")
A caller may optionally specify the name of a provider or a
Providerinstance, which guarantees that the implementation of the algorithm requested is from the specified provider:
static MessageDigest getInstance(String algorithm, String provider) static MessageDigest getInstance(String algorithm, Provider provider)A call to
getInstancereturns an initialized message digest object. It thus does not need further initialization.Updating a Message Digest Object
The next step for calculating the digest of some data is to supply the data to the initialized message digest object. This is done by calling one of the
updatemethods:
void update(byte input) void update(byte[] input) void update(byte[] input, int offset, int len)Computing the Digest
After the data has been supplied by calls to
updatemethods, the digest is computed using a call to one of thedigestmethods:
byte[] digest() byte[] digest(byte[] input) int digest(byte[] buf, int offset, int len)The first two methods return the computed digest. The latter method stores the computed digest in the provided buffer
buf, starting atoffset.lenis the number of bytes inbufallotted for the digest. The method returns the number of bytes actually stored inbuf.A call to the
digestmethod that takes an input byte array argument is equivalent to making a call towith the specified input, followed by a call to thevoid update(byte[] input)digestmethod without any arguments.Please see the Examples section for more details.
Signature ClassTheSignatureclass is an engine class designed to provide the functionality of a cryptographic digital signature algorithm such as DSA or RSA with MD5. A cryptographically secure signature algorithm takes arbitrary-sized input and a private key and generates a relatively short (often fixed-size) string of bytes, called the signature, with the following properties:
- Given the public key corresponding to the private key used to generate the signature, it should be possible to verify the authenticity and integrity of the input.
- The signature and the public key do not reveal anything about the private key.
A
Signatureobject can be used to sign data. It can also be used to verify whether or not an alleged signature is in fact the authentic signature of the data associated with it. Please see the Examples section for an example of signing and verifying data.
SignatureObject StatesSignatureobjects are modal objects. This means that aSignatureobject is always in a given state, where it may only do one type of operation. States are represented as final integer constants defined in their respective classes.The three states a
Signatureobject may have are:When it is first created, a
UNINITIALIZEDSIGNVERIFYSignatureobject is in theUNINITIALIZEDstate. TheSignatureclass defines two initialization methods,initSignandinitVerify, which change the state toSIGNandVERIFY, respectively.Creating a
SignatureObjectThe first step for signing or verifying a signature is to create aSignatureinstance. As with all engine classes, the way to get aSignatureobject for a particular type of signature algorithm is to call thegetInstancestatic factory method on theSignatureclass:static Signature getInstance(String algorithm)A caller may optionally specify the name of a provider or the
Note: The algorithm name is not case-sensitive.
Providerclass, which will guarantee that the implementation of the algorithm requested is from the named provider:
static Signature getInstance(String algorithm, String provider) static Signature getInstance(String algorithm, Provider provider)Initializing a
SignatureObjectA
Signatureobject must be initialized before it is used. The initialization method depends on whether the object is going to be used for signing or for verification.If it is going to be used for signing, the object must first be initialized with the private key of the entity whose signature is going to be generated. This initialization is done by calling the method:
This method puts thefinal void initSign(PrivateKey privateKey)Signatureobject in theSIGNstate.If instead the
Signatureobject is going to be used for verification, it must first be initialized with the public key of the entity whose signature is going to be verified. This initialization is done by calling either of these methods:
final void initVerify(PublicKey publicKey) final void initVerify(Certificate certificate)This method puts the
Signatureobject in theVERIFYstate.Signing
If the
Signatureobject has been initialized for signing (if it is in theSIGNstate), the data to be signed can then be supplied to the object. This is done by making one or more calls to one of theupdatemethods:
final void update(byte b) final void update(byte[] data) final void update(byte[] data, int off, int len)Calls to the
updatemethod(s) should be made until all the data to be signed has been supplied to theSignatureobject.To generate the signature, simply call one of the
signmethods:final byte[] sign() final int sign(byte[] outbuf, int offset, int len)The first method returns the signature result in a byte array. The second stores the signature result in the provided buffer outbuf, starting at offset. len is the number of bytes in outbuf allotted for the signature. The method returns the number of bytes actually stored.
Signature encoding is algorithm specific. See Appendix B for more information about the use of ASN.1 encoding in the Java Cryptography Architecture.
A call to a
signmethod resets the signature object to the state it was in when previously initialized for signing via a call toinitSign. That is, the object is reset and available to generate another signature with the same private key, if desired, via new calls toupdateandsign.Alternatively, a new call can be made to
initSignspecifying a different private key, or toinitVerify(to initialize theSignatureobject to verify a signature).Verifying
If the
Signatureobject has been initialized for verification (if it is in theVERIFYstate), it can then verify if an alleged signature is in fact the authentic signature of the data associated with it. To start the process, the data to be verified (as opposed to the signature itself) is supplied to the object. The data is passed to the object by calling one of theupdatemethods:final void update(byte b) final void update(byte[] data) final void update(byte[] data, int off, int len)Calls to the
updatemethod(s) should be made until all the data to be verified has been supplied to theSignatureobject. The signature can now be verified by calling one of theverifymethods:final boolean verify(byte[] signature) final boolean verify(byte[] signature, int offset, int length)The argument must be a byte array containing the signature. The argument must be a byte array containing the signature. This byte array would hold the signature bytes which were returned by a previous call to one of the
signmethods.The
verifymethod returns abooleanindicating whether or not the encoded signature is the authentic signature of the data supplied to theupdatemethod(s).A call to the
verifymethod resets the signature object to its state when it was initialized for verification via a call toinitVerify. That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call toinitVerify.Alternatively, a new call can be made to
initVerifyspecifying a different public key (to initialize theSignatureobject for verifying a signature from a different entity), or toinitSign(to initialize theSignatureobject for generating a signature).
Algorithm Parameter Specification Interfaces and Classes
An algorithm parameter specification is a transparent representation of the sets of parameters used with an algorithm.
A transparent representation of a set of parameters means that you can access each parameter value in the set individually. You can access these values through one of the
getmethods defined in the corresponding specification class (e.g.,DSAParameterSpecdefinesgetP,getQ, andgetGmethods, to accessp,q, andg, respectively).In contrast, the
AlgorithmParametersclass supplies an opaque representation, in which you have no direct access to the parameter fields. You can only get the name of the algorithm associated with the parameter set (viagetAlgorithm) and some kind of encoding for the parameter set (viagetEncoded).The algorithm parameter specification interfaces and classes in the
java.security.specpackage are described in the following sections.The
AlgorithmParameterSpecInterfaceAlgorithmParameterSpecis an interface to a transparent specification of cryptographic parameters.This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all parameter specifications. All parameter specifications must implement this interface.
The
DSAParameterSpecClassThis class (which implements theAlgorithmParameterSpecinterface) specifies the set of parameters used with the DSA algorithm. It has the following methods:These methods return the DSA algorithm parameters: the primeBigInteger getP() BigInteger getQ() BigInteger getG()p, the sub-primeq, and the baseg.The
AlgorithmParametersClassTheAlgorithmParametersclass is an engine class that provides an opaque representation of cryptographic parameters.An opaque representation is one in which you have no direct access to the parameter fields; you can only get the name of the algorithm associated with the parameter set and some kind of encoding for the parameter set. This is in contrast to a transparent representation of parameters, in which you can access each value individually, through one of the
getmethods defined in the corresponding specification class. Note that you can call theAlgorithmParametersgetParameterSpecmethod to convert anAlgorithmParametersobject to a transparent specification (see the following section).Creating an
AlgorithmParametersObjectAs with all engine classes, the way to get an
AlgorithmParametersobject for a particular type of algorithm is to call thegetInstancestatic factory method on theAlgorithmParametersclass:
static AlgorithmParameters getInstance(String algorithm)A caller may optionally specify the name of a provider or the
Note: The algorithm name is not case-sensitive.
Providerclass, which will guarantee that the algorithm parameter implementation requested is from the named provider:static AlgorithmParameters getInstance(String algorithm, String provider) static AlgorithmParameters getInstance(String algorithm, Provider provider)Initializing an
AlgorithmParametersObjectOnce an
AlgorithmParametersobject is instantiated, it must be initialized via a call toinit, using an appropriate parameter specification or parameter encoding:In thesevoid init(AlgorithmParameterSpec paramSpec) void init(byte[] params) void init(byte[] params, String format)initmethods,paramsis an array containing the encoded parameters, andformatis the name of the decoding format. In theinitmethod with aparamsargument but noformatargument, the primary decoding format for parameters is used. The primary decoding format is ASN.1, if an ASN.1 specification for the parameters exists.
Note:AlgorithmParametersobjects can be initialized only once. They are not reusable.
Obtaining the Encoded Parameters
A byte encoding of the parameters represented in an
AlgorithmParametersobject may be obtained via a call togetEncoded:This method returns the parameters in their primary encoding format. The primary encoding format for parameters is ASN.1, if an ASN.1 specification for this type of parameters exists.byte[] getEncoded()If you want the parameters returned in a specified encoding format, use
Ifbyte[] getEncoded(String format)formatis null, the primary encoding format for parameters is used, as in the othergetEncodedmethod.
Note: In the defaultAlgorithmParametersimplementation, supplied by the "SUN" provider, theformatargument is currently ignored.
Converting an
AlgorithmParametersObject to a Transparent SpecificationA transparent parameter specification for the algorithm parameters may be obtained from an
AlgorithmParametersobject via a call togetParameterSpec:AlgorithmParameterSpec getParameterSpec(Class paramSpec)paramSpecidentifies the specification class in which the parameters should be returned. The specification class could be, for example,DSAParameterSpec.classto indicate that the parameters should be returned in an instance of theDSAParameterSpecclass. (This class is in thejava.security.specpackage.)The
AlgorithmParameterGeneratorClassTheAlgorithmParameterGeneratorclass is an engine class used to generate a set of parameters suitable for a certain algorithm (the algorithm specified when anAlgorithmParameterGeneratorinstance is created).Creating an
AlgorithmParameterGeneratorObjectAs with all engine classes, the way to get an
AlgorithmParameterGeneratorobject for a particular type of algorithm is to call thegetInstancestatic factory method on theAlgorithmParameterGeneratorclass:
static AlgorithmParameterGenerator getInstance( String algorithm)
Note: The algorithm name is not case-sensitive.
A caller may optionally specify the name of a provider or the
Providerclass, which will guarantee that the algorithm parameter generator implementation is from the named provider:static AlgorithmParameterGenerator getInstance( String algorithm, String provider) static AlgorithmParameterGenerator getInstance( String algorithm, Provider provider)Initializing an
AlgorithmParameterGeneratorObjectThe
AlgorithmParameterGeneratorobject can be initialized in two different ways: an algorithm-independent manner or an algorithm-specific manner.The algorithm-independent approach uses the fact that all parameter generators share the concept of a "size" and a source of randomness. The measure of size is universally shared by all algorithm parameters, though it is interpreted differently for different algorithms. For example, in the case of parameters for the DSA algorithm, "size" corresponds to the size of the prime modulus, in bits. (See Appendix B: Algorithms for information about the sizes for specific algorithms.) When using this approach, algorithm-specific parameter generation values--if any--default to some standard values. One
initmethod that takes these two universally shared types of arguments:Anothervoid init(int size, SecureRandom random);initmethod takes only asizeargument and uses a system-provided source of randomness:void init(int size)A third approach initializes a parameter generator object using algorithm-specific semantics, which are represented by a set of algorithm-specific parameter generation values supplied in an
AlgorithmParameterSpecobject:To generate Diffie-Hellman system parameters, for example, the parameter generation values usually consist of the size of the prime modulus and the size of the random exponent, both specified in number of bits. (The Diffie-Hellman algorithm has been part of the JCE since JCE 1.2.)void init(AlgorithmParameterSpec genParamSpec, SecureRandom random) void init(AlgorithmParameterSpec genParamSpec)Generating Algorithm Parameters
Once you have created and initialized anAlgorithmParameterGeneratorobject, you can use thegenerateParametersmethod to generate the algorithm parameters:AlgorithmParameters generateParameters()
Key InterfacesThe
Keyinterface is the top-level interface for all opaque keys. It defines the functionality shared by all opaque key objects.An opaque key representation is one in which you have no direct access to the key material that constitutes a key. In other words: "opaque" gives you limited access to the key--just the three methods defined by the
Keyinterface (see below):getAlgorithm,getFormat, andgetEncoded. This is in contrast to a transparent representation, in which you can access each key material value individually, through one of thegetmethods defined in the corresponding specification class.All opaque keys have three characteristics:
Keys are generally obtained through key generators, certificates, key specifications (using a
- An Algorithm
- The key algorithm for that key. The key algorithm is usually an encryption or asymmetric operation algorithm (such as DSA or RSA), which will work with those algorithms and with related algorithms (such as MD5 with RSA, SHA-1 with RSA, etc.) The name of the algorithm of a key is obtained using this method:
String getAlgorithm()- An Encoded Form
- The external encoded form for the key used when a standard representation of the key is needed outside the Java Virtual Machine, as when transmitting the key to some other party. The key is encoded according to a standard format (such as X.509 or PKCS #8), and is returned using the method:
byte[] getEncoded()- A Format
- The name of the format of the encoded key. It is returned by the method:
String getFormat()KeyFactory), or aKeyStoreimplementation accessing a keystore database used to manage keys.It is possible to parse encoded keys, in an algorithm-dependent manner, using a
KeyFactory.It is also possible to parse certificates, using a
CertificateFactory.Here is a list of interfaces which extend the
Keyinterface in thejava.security.interfacespackage:
The
PublicKeyandPrivateKeyInterfacesThe
PublicKeyandPrivateKeyinterfaces (which both extend theKeyinterface) are methodless interfaces, used for type-safety and type-identification.
Key specifications are transparent representations of the key material that constitutes a key. If the key is stored on a hardware device, its specification may contain information that helps identify the key on the device.
A transparent representation of keys means that you can access each key material value individually, through one of the
getmethods defined in the corresponding specification class. For example,DSAPrivateKeySpecdefinesgetX,getP,getQ, andgetGmethods, to access the private keyx, and the DSA algorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg.This representation is contrasted with an opaque representation, as defined by the
Keyinterface, in which you have no direct access to the key material fields. In other words, an "opaque" representation gives you limited access to the key--just the three methods defined by theKeyinterface:getAlgorithm,getFormat, andgetEncoded.A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components
x,p,q, andg(seeDSAPrivateKeySpec), or it may be specified using its DER encoding (seePKCS8EncodedKeySpec).In the following sections, we discuss the key specification interfaces and classes in the
java.security.specpackage.The
KeySpecInterfaceThis interface contains no methods or constants. Its only purpose is to group and provide type safety for all key specifications. All key specifications must implement this interface.
The
DSAPrivateKeySpecClassThis class (which implements theKeySpecinterface) specifies a DSA private key with its associated parameters.DSAPrivateKeySpechas the following methods:These methods return the private keyBigInteger getX() BigInteger getP() BigInteger getQ() BigInteger getG()x, and the DSA algorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg.The
DSAPublicKeySpecClassThis class (which implements theKeySpecinterface) specifies a DSA public key with its associated parameters.DSAPublicKeySpechas the following methods:These methods return the public keyBigInteger getY() BigInteger getP() BigInteger getQ() BigInteger getG()y, and the DSA algorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg.The
RSAPrivateKeySpecClassThis class (which implements theKeySpecinterface) specifies an RSA private key.RSAPrivateKeySpechas the following methods:These methods return the RSA modulusBigInteger getModulus() BigInteger getPrivateExponent()nand private exponentdvalues that constitute the RSA private key.The
RSAPrivateCrtKeySpecClassThis class (which extends theRSAPrivateKeySpecclass) specifies an RSA private key, as defined in the PKCS #1 standard, using the Chinese Remainder Theorem (CRT) information values.RSAPrivateCrtKeySpechas the following methods (in addition to the methods inherited from its superclassRSAPrivateKeySpec):These methods return the public exponentBigInteger getPublicExponent() BigInteger getPrimeP() BigInteger getPrimeQ() BigInteger getPrimeExponentP() BigInteger getPrimeExponentQ() BigInteger getCrtCoefficient()eand the CRT information integers: the prime factorpof the modulusn, the prime factorqofn, the exponentd mod (p-1), the exponentd mod (q-1), and the Chinese Remainder Theorem coefficient(inverse of q) mod p.An RSA private key logically consists of only the modulus and the private exponent. The presence of the CRT values is intended for efficiency.
The
RSAMultiPrimePrivateCrtKeySpecClassThis class (which extends theRSAPrivateKeySpecclass) specifies an RSA multi-prime private key, as defined in the PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information values.RSAMultiPrimePrivateCrtKeySpechas the following methods (in addition to the methods inherited from its superclassRSAPrivateKeySpec):These methods return the public exponentBigInteger getPublicExponent() BigInteger getPrimeP() BigInteger getPrimeQ() BigInteger getPrimeExponentP() BigInteger getPrimeExponentQ() BigInteger getCrtCoefficient() RSAOtherPrimeInfo[] getOtherPrimeInfo()eand the CRT information integers: the prime factorpof the modulusn, the prime factorqofn, the exponentd mod (p-1), the exponentd mod (q-1), and the Chinese Remainder Theorem coefficient(inverse of q) mod p.Method
getOtherPrimeInforeturns a copy of theotherPrimeInfo(defined in PKCS#1 v 2.1) or null if there are only two prime factors (pandq).An RSA private key logically consists of only the modulus and the private exponent. The presence of the CRT values is intended for efficiency.
The
RSAPublicKeySpecClassThis class (which implements theKeySpecinterface) specifies an RSA public key.RSAPublicKeySpechas the following methods:These methods return the RSA modulusBigInteger getModulus() BigInteger getPublicExponent()nand public exponentevalues that constitute the RSA public key.The
EncodedKeySpecClassThis abstract class (which implements theKeySpecinterface) represents a public or private key in encoded format. ItsgetEncodedmethod returns the encoded key:and itsabstract byte[] getEncoded();getFormatmethod returns the name of the encoding format:abstract String getFormat();See the next sections for the concrete implementations
PKCS8EncodedKeySpecandX509EncodedKeySpec.The
PKCS8EncodedKeySpecClassThis class, which is a subclass ofEncodedKeySpec, represents the DER encoding of a private key, according to the format specified in the PKCS #8 standard. ItsgetEncodedmethod returns the key bytes, encoded according to the PKCS #8 standard. ItsgetFormatmethod returns the string "PKCS#8".The
X509EncodedKeySpecClassThis class, which is a subclass ofEncodedKeySpec, represents the DER encoding of a public key, according to the format specified in the X.509 standard. ItsgetEncodedmethod returns the key bytes, encoded according to the X.509 standard. ItsgetFormatmethod returns the string "X.509".
KeyFactory ClassTheKeyFactoryclass is an engine class designed to provide conversions between opaque cryptographic keys (of typeKey) and key specifications (transparent representations of the underlying key material).Key factories are bi-directional. They allow you to build an opaque key object from a given key specification (key material), or to retrieve the underlying key material of a key object in a suitable format.
Multiple compatible key specifications can exist for the same key. For example, a DSA public key may be specified by its components
y,p,q, andg(seeDSAPublicKeySpec), or it may be specified using its DER encoding according to the X.509 standard (seeX509EncodedKeySpec).A key factory can be used to translate between compatible key specifications. Key parsing can be achieved through translation between compatible key specifications, e.g., when you translate from
X509EncodedKeySpectoDSAPublicKeySpec, you basically parse the encoded key into its components. For an example, see the end of the Generating/Verifying Signatures Using Key Specifications andKeyFactorysection.Creating a
KeyFactoryObjectAs with all engine classes, the way to get a
KeyFactoryobject for a particular type of key algorithm is to call thegetInstancestatic factory method on theKeyFactoryclass:
static KeyFactory getInstance(String algorithm)A caller may optionally specify the name of a provider or the
Note: The algorithm name is not case-sensitive.
Providerclass, which will guarantee that the implementation of the key factory requested is from the named provider.static KeyFactory getInstance(String algorithm, String provider) static KeyFactory getInstance(String algorithm, Provider provider)Converting Between a Key Specification and a Key Object
If you have a key specification for a public key, you can obtain an opaque
PublicKeyobject from the specification by using thegeneratePublicmethod:PublicKey generatePublic(KeySpec keySpec)Similarly, if you have a key specification for a private key, you can obtain an opaque
PrivateKeyobject from the specification by using thegeneratePrivatemethod:PrivateKey generatePrivate(KeySpec keySpec)Converting Between a Key Object and a Key Specification
If you have a
Keyobject, you can get a corresponding key specification object by calling thegetKeySpecmethod:KeySpec getKeySpec(Key key, Class keySpec)keySpecidentifies the specification class in which the key material should be returned. It could, for example, beDSAPublicKeySpec.class, to indicate that the key material should be returned in an instance of theDSAPublicKeySpecclass.Please see the Examples section for more details.
CertificateFactory ClassTheCertificateFactoryclass is an engine class that defines the functionality of a certificate factory, which is used to generate certificate and certificate revocation list (CRL) objects from their encodings.A certificate factory for X.509 must return certificates that are an instance of
java.security.cert.X509Certificate, and CRLs that are an instance ofjava.security.cert.X509CRL.Creating a
CertificateFactoryObjectAs with all engine classes, the way to get a
CertificateFactoryobject for a particular certificate or CRL type is to call thegetInstancestatic factory method on theCertificateFactoryclass:
static CertificateFactory getInstance(String type)A caller may optionally specify the name of a provider or the
Note: The type name is not case-sensitive.
Providerclass, which will guarantee that the implementation of the certificate factory requested is from the named provider.static CertificateFactory getInstance(String type, String provider) static CertificateFactory getInstance(String type, Provider provider)Generating Certificate Objects
To generate a certificate object and initialize it with the data read from an input stream, use thegenerateCertificatemethod:To return a (possibly empty) collection view of the certificates read from a given input stream, use thefinal Certificate generateCertificate(InputStream inStream)generateCertificatesmethod:final Collection generateCertificates(InputStream inStream)Generating CRL Objects
To generate a certificate revocation list (CRL) object and initialize it with the data read from an input stream, use thegenerateCRLmethod:To return a (possibly empty) collection view of the CRLs read from a given input stream, use thefinal CRL generateCRL(InputStream inStream)generateCRLsmethod:final Collection generateCRLs(InputStream inStream)Generating
CertPathObjectsTo generate aCertPathobject and initialize it with data read from an input stream, use one of the followinggenerateCertPathmethods (with or without specifying the encoding to be used for the data):To generate afinal CertPath generateCertPath(InputStream inStream) final CertPath generateCertPath(InputStream inStream, String encoding)CertPathobject and initialize it with a list of certificates, use the following method:To retrieve a list of thefinal CertPath generateCertPath(List certificates)CertPathencodings supported by this certificate factory, you can call thegetCertPathEncodingsmethod:The default encoding will be listed first.final Iterator getCertPathEncodings()
KeyPair ClassThe
KeyPairclass is a simple holder for a key pair (a public key and a private key). It has two public methods, one for returning the private key, and the other for returning the public key:PrivateKey getPrivate() PublicKey getPublic()
KeyPairGenerator ClassThe
KeyPairGeneratorclass is an engine class used to generate pairs of public and private keys.There are two ways to generate a key pair: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object.
Please see the Examples section for examples of calls to the methods documented below.
Creating a
KeyPairGeneratorAll key pair generation starts with a
KeyPairGenerator. This generation is done using one of the factory methods onKeyPairGenerator:
static KeyPairGenerator getInstance(String algorithm) static KeyPairGenerator getInstance(String algorithm, String provider) static KeyPairGenerator getInstance(String algorithm, Provider provider)
Note: The algorithm name is not case-sensitive.
Initializing a
KeyPairGeneratorA key pair generator for a particular algorithm creates a public/private key pair that can be used with this algorithm. It also associates algorithm-specific parameters with each of the generated keys.A key pair generator needs to be initialized before it can generate keys. In most cases, algorithm-independent initialization is sufficient. But in other cases, algorithm-specific initialization is used.
Algorithm-Independent Initialization
All key pair generators share the concepts of a keysize and a source of randomness. The keysize is interpreted differently for different algorithms. For example, in the case of the DSA algorithm, the keysize corresponds to the length of the modulus. (See Appendix B: Algorithms for information about the keysizes for specific algorithms.)
An
initializemethod takes two universally shared types of arguments:Anothervoid initialize(int keysize, SecureRandom random)initializemethod takes only akeysizeargument; it uses a system-provided source of randomness:void initialize(int keysize)Since no other parameters are specified when you call the above algorithm-independent
initializemethods, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with each of the keys.If the algorithm is a "DSA" algorithm, and the modulus size (keysize) is 512, 768, or 1024, then the "SUN" provider uses a set of precomputed values for the
p,q, andgparameters. If the modulus size is not one of the above values, the "SUN" provider creates a new set of parameters. Other providers might have precomputed parameter sets for more than just the three modulus sizes mentioned above. Still others might not have a list of precomputed parameters at all and instead always create new parameter sets.Algorithm-Specific Initialization
For situations where a set of algorithm-specific parameters already exists (such as "community parameters" in DSA), there are two
initializemethods that have anAlgorithmParameterSpecargument. One also has aSecureRandomargument, while the source of randomness is system-provided for the other:See the Examples section for more details.void initialize(AlgorithmParameterSpec params, SecureRandom random) void initialize(AlgorithmParameterSpec params)Generating a Key Pair
The procedure for generating a key pair is always the same, regardless of initialization (and of the algorithm). You always call the following method from
KeyPairGenerator:Multiple calls toKeyPair generateKeyPair()generateKeyPairwill yield different key pairs.
A database called a "keystore" can be used to manage a repository of keys and certificates. (A certificate is a digitally signed statement from one entity, saying that the public key of some other entity has a particular value.)Keystore Location
The keystore is by default stored in a file named
.keystorein the user's home directory, as determined by the "user.home" system property. On Solaris systems "user.home" defaults to the user's home directory. On Win32 systems, given user name uName, "user.home" defaults to:
- C:\Winnt\Profiles\uName on multi-user Windows NT systems
- C:\Windows\Profiles\uName on multi-user Windows 95/98/2000 systems
- C:\Windows on single-user Windows 95/98/2000 systems
Keystore Implementation
TheKeyStoreclass supplies well-defined interfaces to access and modify the information in a keystore. It is possible for there to be multiple different concrete implementations, where each implementation is that for a particular type of keystore.Currently, there are two command-line tools that make use of
KeyStore:keytoolandjarsigner, and also a GUI-based tool namedpolicytool. It is also used by thePolicyreference implementation when it processes policy files specifying the permissions (allowed accesses to system resources) to be granted to code from various sources. SinceKeyStoreis publicly available, SDK users can write additional security applications that use it.There is a built-in default implementation, provided by Sun Microsystems. It implements the keystore as a file, utilizing a proprietary keystore type (format) named "JKS". It protects each private key with its individual password, and also protects the integrity of the entire keystore with a (possibly different) password.
Keystore implementations are provider-based. More specifically, the application interfaces supplied by
KeyStoreare implemented in terms of a "Service Provider Interface" (SPI). That is, there is a corresponding abstractKeystoreSpiclass, also in thejava.securitypackage, which defines the SPI methods that "providers" must implement. (The term "provider" refers to a package or a set of packages that supply a concrete implementation of a subset of services that can be accessed by the Java 2 SDK Security API.) Therefore, to provide a keystore implementation clients must implement a "provider" and supply aKeystoreSpisubclass implementation, as described in How to Implement a Provider for the Java Cryptography Architecture.Applications can choose different types of keystore implementations from different providers, using the
getInstancefactory method in theKeyStoreclass. A keystore type defines the storage and data format of the keystore information, and the algorithms used to protect private keys in the keystore and the integrity of the keystore itself. Keystore implementations of different types are not compatible.The default keystore type is "jks" (the proprietary type of the keystore implementation provided by the "SUN" provider). This is specified by the following line in the security properties file:
To have tools and other applications use a keystore implementation other than the default keystore, you can change that line to specify a different keystore type. Another solution would be to let users of your tools and applications specify a keystore type, and pass that value to thekeystore.type=jksgetInstancemethod of KeyStore.An example of the former approach is the following: If you have a provider package that supplies a keystore implementation for a keystore type called
pkcs12, change the line tokeystore.type=pkcs12
Note: Keystore type designations are not case-sensitive. For example, "JKS" would be considered the same as "jks".
The
KeyStoreClassTheKeyStoreclass is an engine class that supplies well-defined interfaces to access and modify the information in a keystore.This class represents an in-memory collection of keys and certificates.
KeyStoremanages two types of entries:Each entry in a keystore is identified by an "alias" string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms.
- Key Entry
This type of keystore entry holds very sensitive cryptographic key information, which is stored in a protected format to prevent unauthorized access. Typically, a key stored in this type of entry is a secret key, or a private key accompanied by the certificate chain authenticating the corresponding public key.
Private keys and certificate chains are used by a given entity for self-authentication using digital signatures. For example, software distribution organizations digitally sign JAR files as part of releasing and/or licensing software.
- Trusted Certificate Entry
This type of entry contains a single public key certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate.
This type of entry can be used to authenticate other parties.
Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This convention allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats).
The main
KeyStoremethods are described below.Creating a
KeyStoreObjectAs with all engine classes, the way to get a
KeyStoreobject is to call thegetInstancestatic factory method on theKeyStoreclass:
static KeyStore getInstance(String type)A caller may optionally specify the name of a provider or the
Providerclass, which will guarantee that the implementation of the type requested is from the named provider:
static KeyStore getInstance(String type, String provider) static KeyStore getInstance(String type, Provider provider)Loading a Particular Keystore into Memory
Before aKeyStoreobject can be used, the actual keystore data must be loaded into memory via theloadmethod:The optional password is used to check the integrity of the keystore data. If no password is supplied, no integrity check is performed.final void load(InputStream stream, char[] password)To create an empty keystore, you pass
nullas theInputStreamargument to theloadmethod.Getting a List of the Keystore Aliases
All keystore entries are accessed via unique aliases. The
aliasesmethod returns an enumeration of the alias names in the keystore:final Enumeration aliases()Determining Keystore Entry Types
As stated in TheKeyStoreClass, there are two different types of entries in a keystore.The following methods determine whether the entry specified by the given alias is a key/certificate or a trusted certificate entry, respectively:
final boolean isKeyEntry(String alias) final boolean isCertificateEntry(String alias)Adding/Setting/Deleting Keystore Entries
ThesetCertificateEntrymethod assigns a certificate to a specified alias:Iffinal void setCertificateEntry(String alias, Certificate cert)aliasdoesn't exist, a trusted certificate entry with that alias is created. Ifaliasexists and identifies a trusted certificate entry, the certificate associated with it is replaced bycert.The
setKeyEntrymethods add (ifaliasdoesn't yet exist) or set key entries:In the method withfinal void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain) final void setKeyEntry(String alias, byte[] key, Certificate[] chain)keyas a byte array, it is the bytes for a key in protected format. For example, in the keystore implementation supplied by the "SUN" provider, thekeybyte array is expected to contain a protected private key, encoded as anEncryptedPrivateKeyInfoas defined in the PKCS #8 standard. In the other method, thepasswordis the password used to protect the key.The
deleteEntrymethod deletes an entry:final void deleteEntry(String alias)Getting Information from the Keystore
ThegetKeymethod returns the key associated with the given alias. The key is recovered using the given password:The following methods return the certificate, or certificate chain, respectively, associated with the given alias:final Key getKey(String alias, char[] password)You can determine the name (final Certificate getCertificate(String alias) final Certificate[] getCertificateChain(String alias)alias) of the first entry whose certificate matches a given certificate via the following:final String getCertificateAlias(Certificate cert)Saving the KeyStore
The in-memory keystore can be saved via thestoremethod:The password is used to calculate an integrity checksum of the keystore data, which is appended to the keystore data.final void store(OutputStream stream, char[] password)
SecureRandom ClassThe
SecureRandomclass is an engine class that provides the functionality of a random number generator.Creating a
SecureRandomObjectAs with all engine classes, the way to get aSecureRandomobject is to call thegetInstancestatic factory method on theSecureRandomclass:
static SecureRandom getInstance(String algorithm)A caller may optionally specify the name of a provider or the
Providerclass, which will guarantee that the implementation of the random number generation (RNG) algorithm requested is from the named provider:static final SecureRandom getInstance(String algorithm, String provider) static final SecureRandom getInstance(String algorithm, Provider provider)Seeding or Re-Seeding the
SecureRandomObjectThe
SecureRandomimplementation attempts to completely randomize the internal state of the generator itself unless the caller follows the call to agetInstancemethod with a call to one of thesetSeedmethods:Once thesynchronized public void setSeed(byte[] seed) public void setSeed(long seed)SecureRandomobject has been seeded, it will produce bits as random as the original seeds.At any time a
SecureRandomobject may be re-seeded using one of thesetSeedmethods. The given seed supplements, rather than replaces, the existing seed; therefore, repeated calls are guaranteed never to reduce randomness.Using a
SecureRandomObjectTo get random bytes, a caller simply passes an array of any length, which is then filled with random bytes:
synchronized public void nextBytes(byte[] bytes)Generating Seed Bytes
If desired, it is possible to invoke thegenerateSeedmethod to generate a given number of seed bytes (to seed other random number generators, for example):byte[] generateSeed(int numBytes)
The
Cipherclass provides the functionality of a cryptographic cipher used for encryption and decryption. It forms the core of the JCE framework.Creating a Cipher Object
Like other engine classes in the API,
Cipherobjects are created using thegetInstancefactory methods of theCipherclass. A factory method is a static method that returns an instance of a class, in this case, an instance ofCipher, which implements a requested transformation.To create a
Cipherobject, you must specify the transformation name. You may also specify which provider you want to supply the implementation of the requested transformation:
public static Cipher getInstance(String transformation);
public static Cipher getInstance(String transformation,
String provider);If just a transformation name is specified, the system will determine if there is an implementation of the requested transformation available in the environment, and if there is more than one, if there is a preferred one.
If both a transformation name and a package provider are specified, the system will determine if there is an implementation of the requested transformation in the package requested, and throw an exception if there is not.
A transformation is of the form:
For example, the following are valid transformations:
"DES/CBC/PKCS5Padding"
"DES"Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");Cipher c1 = Cipher.getInstance("DES");Appendix A of this document contains a list of standard names that can be used to specify the algorithm name, mode, and padding scheme components of a transformation.
The objects returned by factory methods are uninitialized, and must be initialized before they become usable.
Initializing a Cipher Object
A Cipher object obtained via
getInstancemust be initialized for one of four modes, which are defined as final integer constants in theCipherclass. The modes can be referenced by their symbolic names, which are shown below along with a description of the purpose of each mode:
- ENCRYPT_MODE
Encryption of data.- DECRYPT_MODE
Decryption of data.- WRAP_MODE
Wrapping a Key into bytes so that the key can be securely transported.- UNWRAP_MODE
Unwrapping of a previously wrapped key into ajava.security.Keyobject.Each of the Cipher initialization methods takes a mode parameter (
opmode), and initializes the Cipher object for that mode. Other parameters include the key (key) or certificate containing the key (certificate), algorithm parameters (params), and a source of randomness (random).To initialize a Cipher object, call one of the following
initmethods:public void init(int opmode, Key key);
public void init(int opmode, Certificate certificate)
public void init(int opmode, Key key,
SecureRandom random);
public void init(int opmode, Certificate certificate,
SecureRandom random)
public void init(int opmode, Key key,
AlgorithmParameterSpec params);
public void init(int opmode, Key key,
AlgorithmParameterSpec params,
SecureRandom random);
public void init(int opmode, Key key,
AlgorithmParameters params)
public void init(int opmode, Key key,
AlgorithmParameters params,
SecureRandom random)If a Cipher object that requires parameters (e.g., an initialization vector) is initialized for encryption, and no parameters are supplied to the
initmethod, the underlying cipher implementation is supposed to supply the required parameters itself, either by generating random parameters or by using a default, provider-specific set of parameters.However, if a Cipher object that requires parameters is initialized for decryption, and no parameters are supplied to the
initmethod, anInvalidKeyExceptionorInvalidAlgorithmParameterExceptionexception will be raised, depending on theinitmethod that has been used.See the section about Managing Algorithm Parameters for more details.
The same parameters that were used for encryption must be used for decryption.
Note that when a Cipher object is initialized, it loses all previously-acquired state. In other words, initializing a Cipher is equivalent to creating a new instance of that Cipher, and initializing it. For example, if a Cipher is first initialized for decryption with a given key, and then initialized for encryption, it will lose any state acquired while in decryption mode.
Encrypting and Decrypting Data
Data can be encrypted or decrypted in one step (single-part operati