JavaTM Cryptography Architecture

API Specification & Reference

Last Modified: 14 May 2001


Introduction
Design Principles
Architecture
Concepts
Core Classes and Interfaces
The Provider Class
How Provider Implementations are Requested and Supplied
Installing Providers
The Security Class
The MessageDigest Class
The Signature Class
Algorithm Parameters Classes
Algorithm Parameter Specification Interfaces and Classes
The AlgorithmParameterSpec Interface
The DSAParameterSpec Class
The AlgorithmParameters Class
The AlgorithmParameterGenerator Class
Key Interfaces
Key Specification Interfaces and Classes
The KeySpec Interface
The DSAPrivateKeySpec Class
The DSAPublicKeySpec Class
The RSAPrivateKeySpec Class
The RSAPrivateCrtKeySpec Class
The RSAPublicKeySpec Class
The EncodedKeySpec Class
The PKCS8EncodedKeySpec Class
The X509EncodedKeySpec Class
The KeyFactory Class
The CertificateFactory Class
The KeyPair Class
The KeyPairGenerator Class
Key Management
Keystore Location
Keystore Implementation
The KeyStore Class
The SecureRandom Class
Code Examples
Computing a MessageDigest Object
Generating a Pair of Keys
Generating and Verifying a Signature Using Generated Keys
Generating/Verifying Signatures Using Key Specifications and KeyFactory
Reading Base64-Encoded Certificates
Parsing a Certificate Reply

 
Appendix A: Standard Names

 
Appendix B: Algorithms
 
Appendix C: Hardware Cryptography, IBMJCA4758 specifics

Introduction

The JDK Security API is a core API of the Java programming language, built around the java.security package (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 JDK Security in JDK 1.1 introduced the "Java Cryptography Architecture" (JCA), which refers to 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.

Java 2 SDK significantly extends the Java Cryptography Architecture, as described in this document. It also upgrades the certificate management infrastructure to support X.509 v3 certificates, and introduces 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 Java Cryptography Extension (JCE) extends the JCA API to include APIs for encryption, key exchange, and Message Authentication Code (MAC). Together, the JCE and the cryptography aspects of the SDK provide a complete, platform-independent cryptography API. The JCE is released separately as an extension to the SDK, in accordance with U.S. export control regulations.

This document is both a high-level description and a specification of the Java Cryptography Architecture API and its default provider, as shipped in the Java 2 SDK. A separate document describing the JCE API is provided with the JCE release. See the "Java Security Architecture Specification" for information about the Java Security Architecture aspects of the Security API.
 
 

Design Principles

The Java Cryptography Architecture (JCA) was designed around these principles: Implementation independence and algorithm independence are complementary: their aim is to let users of the API utilize cryptographic concepts, such as digital signatures and message digests, without concern for the implementations or even the algorithms being used to implement these concepts. When complete algorithm-independence is not possible, the JCA provides developers with standardized algorithm-specific APIs. When implementation-independence is not desirable, the JCA lets developers indicate the specific implementations they require.

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, and KeyFactory classes.

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 Signature object) 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 easily be added.

Architecture

Cryptographic Service Providers

The Java Cryptography Architecture introduces 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 supply a concrete implementation of a subset of the cryptography aspects of the Security API.

In JDK 1.1 a provider could, for example, 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 Signature object) 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 a specific provider. (Each provider has a name used to refer to it.)

IBM's version of the Java runtime environment comes standard with a default provider, named "IBMJCA". Other Java runtime environments may not necessarily supply the "IBMJCA" provider. The "IBMJCA" provider package includes:

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 KeyStore class, which is in the java.security package. A default KeyStore implementation is provided by IBM. It implements the keystore as a file, utilizing a proprietary keystore type (format) named "JCAKS",

Applications can choose different types of keystore implementations from different providers, using the "getInstance" factory method supplied in the KeyStore class.

See the Key Management section for more information.

Concepts

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 Signature and KeyFactory classes. The Signature class provides access to the functionality of a digital signature algorithm. A DSA KeyFactory supplies a DSA private or public key (from its encoding or transparent specification) in a format usable by the initSign or initVerify methods, respectively, of a DSA Signature object.

The 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 utilize instances of the engine classes to carry out corresponding operations. The following engine classes are defined in Java 2 SDK:

Note: A "generator" creates objects with brand-new contents, whereas a "factory" creates objects from existing material (for example, an encoding).

An engine class provides the interface to the functionality of a specific type of cryptographic service (independent of a particular cryptographic algorithm). It defines "Application Programming Interface" (API) methods that allow applications to access the specific type of cryptographic service it provides. The actual implementations (from one or more providers) are those for specific algorithms. The Signature engine class, for example, provides access to the functionality of a digital signature algorithm. The actual implementation supplied in a SignatureSpi subclass (see next paragraph) would be that for a specific kind of signature algorithm, such as SHA1 with DSA, SHA1 with RSA, or MD5 with RSA.

The application interfaces supplied by an engine class are implemented in terms of a "Service Provider Interface" (SPI). That is, for each engine class, there is a corresponding abstract SPI class, which defines the Service Provider Interface methods that cryptographic service providers must implement.

An instance of an engine class, the "API object", encapsulates (as a private field) an instance of the corresponding SPI class, the "SPI object". All API methods of an API object are declared "final", and their implementations invoke the corresponding SPI methods of the encapsulated SPI object. An instance of an engine class (and of its corresponding SPI class) is created by a call to the getInstance factory method of the engine class.

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

Each SPI class is abstract. To supply the implementation of a particular type of service, for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.

Another example of an engine class is the MessageDigest class, which provides access to a message digest algorithm. Its implementations, in MessageDigestSpi subclasses, may be those of various message digest algorithms such as SHA-1, MD5, or MD2.

As a final example, the KeyFactory engine class supports the conversion from opaque keys to transparent key specifications, and vice versa. (See the Key Specification Interfaces and Classes section.) The actual implementation supplied in a KeyFactorySpi subclass would be that for a specific type of keys, e.g., 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. For example, the Java Development Kit's default provider, named "IBMJCA", supplies implementations of the DSA signature algorithm, the MD5 and SHA-1 message digest algorithms, the DSA key pair generation algorithm, and the IBMSecureRandom pseudo-random number generation algorithm. It also supplies a key factory for DSA private and public keys, a certificate factory for X.509 certificates and CRLs, an implementation of DSA parameters (including their generation), and a keystore implementation of the proprietary keystore type named "JKS".

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 Signature object, for example, is as follows: A user requests such an object by calling the getInstance method in the Signature class, specifying the name of a signature algorithm (such as "SHA1withDSA"), and, optionally, the name of the provider whose implementation is desired. The getInstance method finds an implementation that satisfies the supplied algorithm and provider parameters. If no provider is specified, getInstance searches the registered providers, in preference order, for one with an implementation of the specified algorithm. See The Provider Class for more information about registering providers.

Core Classes and Interfaces

This section provides a discussion of the core classes and interfaces provided in the Java Cryptography Architecture: This section shows the signatures of the main methods in each class and interface. Usage 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:

The Provider Class

The term "Cryptographic Service Provider" (used interchangeably with "provider" in this document) is used to refer to a package or set of packages that supply a concrete implementation of a subset of the cryptography aspects of the Java 2 SDK Security API. The Provider class 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, the Provider class 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 actually supply implementations of cryptographic services, an entity (e.g., a development group) writes the implementation code and creates a subclass of the Provider class. The constructor of the subclass sets the values of various properties that are required for the Java 2 SDK Security API to look up the services implemented by the provider. That is, it specifies the names of the classes implementing the services.

There are several types of services that can be implemented by provider packages - 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 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 a getInstance method on the engine class, specifying the name of the desired algorithm and, optionally, the name of the provider whose implementation is desired.

If no provider is specified, getInstance searches 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 . That order is the order in which they are searched when no specific provider is requested. For example, suppose there are two providers installed in a JVM, one named "PROVIDER_1" and the other "PROVIDER_2". Further suppose that

If PROVIDER_1 has preference order 1 (the highest priority) and PROVIDER_2 has preference order 2, then the following behavior will occur: The getInstance methods 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 from PROVIDER_1 has not received such certification, while the DSA implementation of PROVIDER_2 has received it.

A Federal program would then have the following call, specifying PROVIDER_2 since it has the certified implementation:

        Signature dsa = Signature.getInstance("SHA1withDSA", "PROVIDER_2");
In this case, if "PROVIDER_2" was not installed, a NoSuchProviderException would be raised, even if a different installed provider implements the algorithm requested.

A program also has the option of getting a list of all the installed Providers (using the getProviders method in the Security class), 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 a couple possible ways of installing the provider classes:

Configuring the Provider

The next step is to add the provider to your list of approved providers. This is done statically by editing the java.security file in the lib/security directory of the SDK. Thus, if the SDK is installed in a directory called j2sdk1.2, the file would be j2sdk1.2/lib/security/java.security. One of the types of properties you can set in java.security is of the following form:
    security.provider.n=masterClassName
This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms (when no specific provider is requested). The order is 1-based; 1 is the most preferred, followed by 2, and so on.

masterClassName must specify the provider's "master" class. The provider's documentation will specify its master class. This class is always a subclass of the Provider class. 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 implemented by the provider.

Suppose that the master class is COM.acme.provider.Acme, and that you would like to configure Acme as your third preferred provider. To do so, add the following line to the java.security file:

    security.provider.3=COM.acme.provider.Acme
Providers may also be registered dynamically. To do so, call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent and can only be done by "trusted" programs. See Security.

Provider Class Methods

Each Provider class instance has a (currently case-sensitive) name, a version number, and a string description of the provider and its services. You can query the Provider instance for this information by calling the following methods:
    public String getName()
    public double getVersion()
    public String getInfo()

The Security Class

The Security class manages installed providers and security-wide properties. It only contains static methods and is never instantiated.

Note: the methods for adding or removing providers, and for setting Security properties, can only be executed by a trusted program. Currently, a "trusted program" is either

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

For example, in the default Policy 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.

The contents of a sample policy configuration file appear below.

  grant signedBy "sysadmin", codeBase "file:/home/sysadmin/" {
    permission java.security.SecurityPermission "Security.insertProvider.*";
    permission java.security.SecurityPermission "Security.removeProvider.*";
    permission java.security.SecurityPermission "Security.setProperty.*";
  };
This specifies that only code that was loaded from a signed JAR file (whose signature can be verified using the public key referenced by the alias name "sysadmin" in the user's keystore) from beneath the "/home/sysadmin/" directory on the local file system can call methods in the Security class to add or remove providers or to set Security properties.

Either component of the code source (or both) may be missing. An example where codeBase is missing is:

  grant signedBy "sysadmin" {
    permission java.security.SecurityPermission "Security.insertProvider.*";
    permission java.security.SecurityPermission "Security.removeProvider.*";
};
If this policy is in effect, code that comes in a JAR File signed by "sysadmin" can add/remove providers - regardless of where the JAR File originated from.

An example without a signer is:

  grant codeBase "file:/home/sysadmin/" {
    permission java.security.SecurityPermission "Security.insertProvider.*";
    permission java.security.SecurityPermission "Security.removeProvider.*";
};
In this case, code that comes from anywhere beneath the "/home/sysadmin/" directory on the local filesystem can add/remove providers. The code does not need to be signed.

An example where neither codeBase nor signedBy is included is:

  grant {
    permission java.security.SecurityPermission "Security.insertProvider.*";
    permission java.security.SecurityPermission "Security.removeProvider.*";
};
Here, with both code source components missing, any code (regardless of where it originated from, or whether or not it is signed, or who signed it) can add/remove providers.

Managing Providers

The Security class may be used to query which Providers are installed, as well as to install new ones at runtime.

Quering Providers

        public Provider[] getProviders()
This method returns an array containing all the installed providers (technically, the Provider subclass for each package provider). The order of the Providers in the array is their preference order.
        public Provider getProvider(String providerName)
This method returns the Provider named providerName. It returns null if the Provider is not found.

Adding Providers

    public static int addProvider(Provider provider) {
This method adds a Provider to the end of the list of installed Providers. It returns the preference position in which the Provider was added, or -1 if the Provider was not added because it was already installed.
        public int insertProviderAt(Provider provider, int position)
This method adds a new Provider, at a specified position. The position is the preference order in which providers are searched for requested algorithms (if no specific provider is requested). The position is 1-based, that is, 1 is most preferred, followed by 2, and so on. If the given provider is installed at the requested position, the provider that used to be at that position, and all providers with a position greater than position, are shifted up one position (towards the end of the list of installed providers).

A Provider cannot be added if it is already installed.

This method returns the actual preference position in which the Provider was added, or -1 if the Provider was not added because it was already installed.

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.

Removing Providers

        public void removeProvider(String name)
This method removes the Provider with 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).

Security Properties

The Security class maintains a list of system-wide security properties. These properties are accessible and settable by a trusted program via the following methods:
        public static String getProperty(String key)
        public static void setProperty(String key, String datum)

The MessageDigest Class

The MessageDigest class is an engine class designed to provide the functionality of cryptographically secure message digests such as SHA1 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 the following properties: Message digests are used to produce unique and reliable identifiers of data. They are sometimes called the "digital fingerprints" of data.

Creating a MessageDigest Object

The first step for computing a digest is to create a message digest instance. As with all engine classes, the way to get a MessageDigest object for a particular type of message digest algorithm is to call the getInstance static factory method on the MessageDigest class:
    public static MessageDigest getInstance(String algorithm)
Note: The algorithm name is case-insensitive. For example, all of the following calls are equivalent:
    MessageDigest.getInstance("SHA")
    MessageDigest.getInstance("sha")
    MessageDigest.getInstance("sHa")
A caller may optionally specify the name of a provider, which will guarantee that the implementation of the algorithm requested is from the named provider:
    public static MessageDigest getInstance(String algorithm, String provider)
A call to getInstance returns 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 making one or more calls to one of the update methods:
    public void update(byte input)
    public void update(byte[] input)
    public void update(byte[] input, int offset, int len)

Computing the Digest

After the data has been supplied by calls to update methods, the digest is computed using a call to one of the digest methods:
    public byte[] digest()
    public byte[] digest(byte[] input)
    public 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 at offset. len is the number of bytes in buf allotted for the digest. The method returns the number of bytes actually stored in buf.

A call to the digest method that takes an input byte array argument is equivalent to making a call to

    public void update(byte[] input)
with the specified input, followed by a call to the digest method without any arguments.

Please see the Examples section for more details.

The Signature Class

The Signature class 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: A Signature object 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.

Signature Object States

Signature objects are modal objects. This means that a Signature object 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 (such as Signature).

The three states a Signature object may have are:

When it is first created, a Signature object is in the UNINITIALIZED state. The Signature class defines two initialization methods, initSign and initVerify, which change the state to SIGN and VERIFY, respectively.

Creating a Signature Object

The first step for signing or verifying a signature is to create a Signature instance. As with all engine classes, the way to get a Signature object for a particular type of signature algorithm is to call the getInstance static factory method on the Signature class:
    public static Signature getInstance(String algorithm)
Note: The algorithm name is case-insensitive.

A caller may optionally specify the name of a provider, which will guarantee that the implementation of the algorithm requested is from the named provider:

    public static Signature getInstance(String algorithm, 
                                        String provider)

Initializing a Signature Object

A Signature object must be initialized before it is used. The initialization method depends on whether the object is first 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:

    public final void initSign(PrivateKey privateKey)
This method puts the Signature object in the SIGN state.

If instead the Signature object 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 the method:

    public final void initVerify(PublicKey publicKey)
This method puts the Signature object in the VERIFY state.

Signing

If the Signature object has been initialized for signing (if it is in the SIGN state), the data to be signed can then be supplied to the object. This is done by making one or more calls to one of the update methods:
    public final void update(byte b)
    public final void update(byte[] data)
    public final void update(byte[] data, int off, int len)
Calls to the update method(s) should be made until all the data to be signed has been supplied to the Signature object.

To generate the signature, simply call one of the sign methods:

    public final byte[] sign()
    public 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.

The signature is encoded as a standard ASN.1 sequence of two integers, r and s. See Appendix B for more information about the use of ASN.1 encoding in the Java Cryptography Architecture.

A call to a sign method resets the signature object to the state it was in when previously initialized for signing via a call to initSign. That is, the object is reset and available to generate another signature with the same private key, if desired, via new calls to update and sign.

Alternatively, a new call can be made to initSign specifying a different private key, or to initVerify (to initialize the Signature object to verify a signature).

Verifying

If the Signature object has been initialized for verification (if it is in the VERIFY state), it can then verify whether or not 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. This is done by making one or more calls to one of the update methods:
    public final void update(byte b)
    public final void update(byte[] data)
    public final void update(byte[] data, int off, int len)
Calls to the update method(s) should be made until all the data has been supplied to the Signature object.

The signature can then be verified by calling the verify method:

    public final boolean verify(byte[] encodedSignature)
The argument must be a byte array containing the signature encoded as a standard ASN.1 sequence of two integers, r and s. This is a standard encoding that is frequently utilized. It is the same as that produced by the sign method.

The verify method returns a boolean indicating whether or not the encoded signature is the authentic signature of the data supplied to the update method(s).

A call to the verify method resets the signature object to the state it was in when previously initialized for verification via a call to initVerify. That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call to initVerify.

Alternatively, a new call can be made to initVerify specifying a different public key (to initialize the Signature object for verifying a signature from a different entity), or to initSign (to initialize the Signature object for generating a signature).

Algorithm Parameters Classes

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, through one of the "get" methods defined in the corresponding specification class (e.g., DSAParameterSpec defines getP, getQ, and getG methods, to access p, q, and g, respectively).

This is contrasted with an opaque representation, as supplied by the AlgorithmParameters class, 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 (via getAlgorithm) and some kind of encoding for the parameter set (via getEncoded).

The algorithm parameter specification interfaces and classes that appear in the java.security.spec package are described below.

The AlgorithmParameterSpec Interface

AlgorithmParameterSpec is 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 DSAParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the DSA algorithm. It has the following methods:
    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()
These methods return the DSA algorithm parameters: the prime p, the sub-prime q, and the base g.

The AlgorithmParameters Class

The AlgorithmParameters class 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 "get" methods defined in the corresponding specification class. Note: you can call the AlgorithmParameters getParameterSpec method to convert an AlgorithmParameters object to a transparent specification (see below).

Creating an AlgorithmParameters Object

As with all engine classes, the way to get an AlgorithmParameters object for a particular type of algorithm is to call the getInstance static factory method on the AlgorithmParameters class:
    public static AlgorithmParameters getInstance(String algorithm)
Note: The algorithm name is case-insensitive.

A caller may optionally specify the name of a provider, which will guarantee that the algorithm parameter implementation requested is from the named provider:

    public static AlgorithmParameters getInstance(String algorithm, String provider)

Initializing an AlgorithmParameters Object

Once an AlgorithmParameters object is instantiated, it must be initialized via a call to init, using an appropriate parameter specification or parameter encoding:
    public void init(AlgorithmParameterSpec paramSpec) 

    public void init(byte[] params)

    public void init(byte[] params, String format)
In the above, params is an array containing the encoded parameters, and format is the name of the decoding format. In the init method with a params argument but no format argument, 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: AlgorithmParameters objects can be initialized only once, that is, they are not reusable.

Obtaining the Encoded Parameters

A byte encoding of the parameters represented in an AlgorithmParameters object may be obtained via a call to getEncoded:
    public byte[] getEncoded()
This 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.

If you want the parameters returned in a specified encoding format, use

    public byte[] getEncoded(String format)
If format is null, the primary encoding format for parameters is used, as in the other getEncoded method.

Please note: in the default AlgorithmParameters implementation, supplied by the "IBMJCA" provider, the format argument is currently ignored.

Converting an AlgorithmParameters Object to a Transparent Specification

A transparent parameter specification for the algorithm parameters may be obtained from an AlgorithmParameters object via a call to getParameterSpec:
    public AlgorithmParameterSpec getParameterSpec(Class paramSpec)
paramSpec identifies the specification class in which the parameters should be returned. It could, for example, be DSAParameterSpec.class, to indicate that the parameters should be returned in an instance of the DSAParameterSpec class (which is in the java.security.spec package).

The AlgorithmParameterGenerator Class

The AlgorithmParameterGenerator class is an engine class used to generate a set of parameters suitable for a certain algorithm (the algorithm specified when an AlgorithmParameterGenerator instance is created).

Creating an AlgorithmParameterGenerator Object

As with all engine classes, the way to get an AlgorithmParameterGenerator object for a particular type of algorithm is to call the getInstance static factory method on the AlgorithmParameterGenerator class:
    public static AlgorithmParameterGenerator getInstance(
                        String algorithm)
Note: The algorithm name is case-insensitive.

A caller may optionally specify the name of a provider, which will guarantee that the algorithm parameter generator implementation is from the named provider:

    public static AlgorithmParameterGenerator getInstance(
                       String algorithm, 
                       String provider)

Initializing an AlgorithmParameterGenerator Object

The AlgorithmParameterGenerator object can be initialized in two different ways: in an algorithm-independent manner, or in 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. There is an init method that takes these two universally shared types of arguments:

    public void init(int size, SecureRandom random);
There is also one that takes just a size argument; it uses a system-provided source of randomness:
    public void init(int size)
The other 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 AlgorithmParameterSpec object:
    public void init(AlgorithmParameterSpec genParamSpec,
                           SecureRandom random)

    public void init(AlgorithmParameterSpec genParamSpec)
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 is supplied as part of JCE 1.2.

Generating Algorithm Parameters

Once you have created and initialized an AlgorithmParameterGenerator object, you can generate the algorithm parameters using the generateParameters method:
    public AlgorithmParameters generateParameters()

Key Interfaces

The Key interface 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 constitues a key. In other words: "opaque" gives you limited access to the key - just the three methods defined by the "Key" interface (see below): getAlgorithm, getFormat, and getEncoded. This is in contrast to a transparent representation, in which you can access each key material value individually, through one of the "get" methods defined in the corresponding specification class.

All opaque keys have three characteristics:

Keys are generally obtained through key generators, certificates, key specifications (using a KeyFactory), or a KeyStore implementation 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.

The PublicKey and PrivateKey Interfaces

The PublicKey and PrivateKey interfaces (which both extend the Key interface) are methodless interfaces, used for type-safety and type-identification.

Key Specification Interfaces and Classes

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 "get" methods defined in the corresponding specification class. For example, DSAPrivateKeySpec defines getX, getP, getQ, and getG methods, to access the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

This is contrasted with an opaque representation, as defined by the Key interface, 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 the Key interface: getAlgorithm, getFormat, and getEncoded.

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, and g (see DSAPrivateKeySpec), or it may be specified using its DER encoding (see PKCS8EncodedKeySpec).

The key specification interfaces and classes appear in the java.security.spec package. They are described below.

The KeySpec Interface

This 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 DSAPrivateKeySpec Class

This class (which implements the KeySpec Interface) specifies a DSA private key with its associated parameters. It has the following methods:
    public BigInteger getX()

    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()
These methods return the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

The DSAPublicKeySpec Class

This class (which implements the KeySpec Interface) specifies a DSA public key with its associated parameters. It has the following methods:
    public BigInteger getY()

    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()
These methods return the public key y, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

The RSAPrivateKeySpec Class

This class (which implements the KeySpec Interface) specifies an RSA private key. It has the following methods:
    public BigInteger getModulus()

    public BigInteger getPrivateExponent()
These methods return the RSA modulus n and private exponent d values that constitute the RSA private key.

The RSAPrivateCrtKeySpec Class

This class (which extends the RSAPrivateKeySpec class) specifies an RSA private key, as defined in the PKCS#1 standard, using the Chinese Remainder Theorem (CRT) information values. It has the following methods (in addition to the methods inherited from its superclass RSAPrivateKeySpec):
    public BigInteger getPublicExponent()

    public BigInteger getPrimeP()

    public BigInteger getPrimeQ()

    public BigInteger getPrimeExponentP()

    public BigInteger getPrimeExponentQ()

    public BigInteger getCrtCoefficient()
These methods return the public exponent e and the CRT information integers: the prime factor p of the modulus n, the prime factor q of n, the exponent d mod (p-1), the exponent d 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 RSAPublicKeySpec Class

This class (which implements the KeySpec Interface) specifies an RSA public key. It has the following methods:
    public BigInteger getModulus()

    public BigInteger getPublicExponent()
These methods return the RSA modulus n and public exponent e values that constitute the RSA public key.

The EncodedKeySpec Class

This abstract class (which implements the KeySpec Interface)represents a public or private key in encoded format. Its getEncoded method returns the encoded key:
    public abstract byte[] getEncoded();
and its getFormat method returns the name of the encoding format:
    public abstract String getFormat();
See below for the concrete implementations PKCS8EncodedKeySpec and X509EncodedKeySpec.

The PKCS8EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a private key, according to the format specified in the PKCS #8 standard.

Its getEncoded method returns the key bytes, encoded according to the PKCS #8 standard. Its getFormat method returns the string "PKCS#8".

The X509EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a public key, according to the format specified in the X.509 standard.

Its getEncoded method returns the key bytes, encoded according to the X.509 standard. Its getFormat method returns the string "X.509".

The KeyFactory Class

The KeyFactory class is an engine class designed to provide conversions between opaque cryptographic keys (of type Key) and key specifications (transparent representations of the underlying key material).

Key factories are bi-directional, i.e., 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 may exist for the same key. For example, a DSA public key may be specified by its components y, p, q, and g (see DSAPublicKeySpec), or it may be specified using its DER encoding according to the X.509 standard (see X509EncodedKeySpec).

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 X509EncodedKeySpec to DSAPublicKeySpec, you basically parse the encoded key into its components. For an example, see the end of the Generating/Verifying Signatures Using Key Specifications and KeyFactory section.

Creating a KeyFactory Object

As with all engine classes, the way to get a KeyFactory object for a particular type of key algorithm is to call the getInstance static factory method on the KeyFactory class:
    public static KeyFactory getInstance(String algorithm)
Note: The algorithm name is case-insensitive.

A caller may optionally specify the name of a provider, which will guarantee that the implementation of the key factory requested is from the named provider.

    public static KeyFactory getInstance(String algorithm, String 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 PublicKey object from the specification by using the generatePublic method:
    public PublicKey generatePublic(KeySpec keySpec)
Similarly, if you have a key specification for a private key, you can obtain an opaque PrivateKey object from the specification by using the generatePrivate method:
    public PrivateKey generatePrivate(KeySpec keySpec)

Converting Between a Key Object and a Key Specification

If you have a Key object, you can get a corresponding key specification object by calling the getKeySpec method:
    public KeySpec getKeySpec(Key key, Class keySpec)
keySpec identifies the specification class in which the key material should be returned. It could, for example, be DSAPublicKeySpec.class, to indicate that the key material should be returned in an instance of the DSAPublicKeySpec class.

Please see the Examples section for more details.

The CertificateFactory Class

The CertificateFactory class 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 of java.security.cert.X509CRL.

Creating a CertificateFactory Object

As with all engine classes, the way to get a CertificateFactory object for a particular certificate or CRL type is to call the getInstance static factory method on the CertificateFactory class:
    public static CertificateFactory getInstance(String type)
Note: The type name is case-insensitive.

A caller may optionally specify the name of a provider, which will guarantee that the implementation of the certificate factory requested is from the named provider.

    public static CertificateFactory getInstance(String type, String provider)

Generating Certificate Objects

To generate a certificate object and initialize it with the data read from an input stream, use the generateCertificate method:
    public final Certificate generateCertificate(InputStream inStream)
To return a (possibly empty) collection view of the certificates read from a given input stream, use the generateCertificates method:
    public 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 the generateCRL method:
    public final CRL generateCRL(InputStream inStream)
To return a (possibly empty) collection view of the CRLs read from a given input stream, use the generateCRLs method:
    public final Collection generateCRLs(InputStream inStream)

The KeyPair Class

The KeyPair class 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:
    public PrivateKey getPrivate()
    public PublicKey getPublic()

The KeyPairGenerator Class

The KeyPairGenerator class 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 KeyPairGenerator

All key pair generation starts with a KeyPairGenerator. This is done using one of the factory methods on KeyPairGenerator:
    public static KeyPairGenerator getInstance(String algorithm)
    public static KeyPairGenerator getInstance(String algorithm, 
        String provider)
Note: The algorithm name is case-insensitive.

Initializing a KeyPairGenerator

A 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 utilized.

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

There is an initialize method that takes these two universally shared types of arguments:

    public void initialize(int keysize, SecureRandom random)
There is also one that takes just a keysize argument; it uses a system-provided source of randomness:
    public void initialize(int keysize)
Since no other parameters are specified when you call the above algorithm-independent initialize methods, 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 "IBMJCA" provider uses a set of precomputed values for the p, q, and g parameters. If the modulus size is not one of the above values, the "IBMJCA" 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 (e.g., so-called "community parameters" in DSA), there are two initialize methods that have an AlgorithmParameterSpec argument. One also has a SecureRandom argument, while the source of randomness is system-provided for the other:
    public void initialize(AlgorithmParameterSpec params,
                   SecureRandom random)

    public void initialize(AlgorithmParameterSpec params)
See the Examples section for more details.

Generating a Key Pair

Generating a key pair is always the same, regardless of initialization (and therefore of algorithm). You always call the following method from KeyPairGenerator:
    public KeyPair generateKeyPair()
Multiple calls to generateKeyPair will yield different key pairs.

Key Management

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 .keystore in 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 Windows 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 systems
  • C:\Windows on single-user Windows 95 systems

Keystore Implementation

The KeyStore class 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: keytool and jarsigner, and also a GUI-based tool named policytool. It is also used by the default Policy implementation when it processes policy files specifying the permissions (allowed accesses to system resources) to be granted to code from various sources. Since KeyStore is publicly available, SDK users can write additional security applications that use it.

There is a built-in default implementation, provided by IBM. It implements the keystore as a file, utilizing a proprietary keystore type (format) named "JCAKS". 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 KeyStore are implemented in terms of a "Service Provider Interface" (SPI). That is, there is a corresponding abstract KeystoreSpi class, also in the java.security package, which defines the Service Provider Interface 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.) Thus, to provide a keystore implementation, clients must implement a "provider" and supply a KeystoreSpi subclass 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 "getInstance" factory method supplied in the KeyStore class. 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 "jcaks" (the proprietary type of the keystore implementation provided by the "IBMJCA" provider). This is specified by the following line in the security properties file:

    keystore.type=jcaks
To have tools and other applications utilize a keystore implementation other than the default, 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 the getInstance method 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 to

    keystore.type=pkcs12
Note: case doesn't matter in keystore type designations. For example, "JKS" would be considered the same as "jks".

The KeyStore Class

The KeyStore class 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. It manages 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.

Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This 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 KeyStore methods are described below.

Creating a KeyStore Object

As with all engine classes, the way to get a KeyStore object is to call the getInstance static factory method on the KeyStore class:
    public static KeyStore getInstance(String type)
A caller may optionally specify the name of a provider, which will guarantee that the implementation of the type requested is from the named provider:
    public static KeyStore getInstance(String type, String provider)

Loading a Particular Keystore into Memory

Before a KeyStore object can be used, the actual keystore data must be loaded into memory via the load method:
    public final void load(InputStream stream, String password)
The optional password is used to check the integrity of the keystore data. If no password is supplied, no integrity check is performed.

In order to create an empty keystore, you pass null as the InputStream argument to the load method.

Getting a List of the Keystore Aliases

All keystore entries are accessed via unique aliases.

The aliases method returns an enumeration of the alias names in the keystore:

    public final Enumeration aliases()

Determining Keystore Entry Types

As stated in The KeyStore Class, 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:

    public final boolean isKeyEntry(String alias)

    public final boolean isCertificateEntry(String alias)

Adding/Setting/Deleting Keystore Entries

The setCertificateEntry method assigns a certificate to a specified alias:
    public final void setCertificateEntry(String alias, Certificate cert)
If alias doesn't exist, a trusted certificate entry with that alias is created. If alias exists and identifies a trusted certificate entry, the certificate associated with it is replaced by cert.

The setKeyEntry methods add (if alias doesn't yet exist) or set key entries:

    public final void setKeyEntry(String alias, Key key, String password,
                                  Certificate[] chain)

    public final void setKeyEntry(String alias, byte[] key,
                                  Certificate[] chain)
In the method with key as a byte array, it is the bytes for a key in protected format. For example, in the keystore implementation supplied by the "IBMJCA" provider, the key byte array is expected to contain a protected private key, encoded as an EncryptedPrivateKeyInfo as defined in the PKCS#8 standard. In the other method, the password is the password used to protect the key.

The deleteEntry method deletes an entry:

    public final void deleteEntry(String alias)

Getting Information from the Keystore

The getKey method returns the key associated with the given alias. The key is recovered using the given password:
    public final Key getKey(String alias, String password)
The following methods return the certificate, or certificate chain, respectively, associated with the given alias:
    public final Certificate getCertificate(String alias)

    public final Certificate[] getCertificateChain(String alias)
You can determine the name (alias) of the first entry whose certificate matches a given certificate via the following:
    public final String getCertificateAlias(Certificate cert)

Saving the KeyStore

The in-memory keystore can be saved via the store method:
    public final void store(OutputStream stream, String password)
The password is used to calculate an integrity checksum of the keystore data, which is appended to the keystore data.

The SecureRandom Class

The SecureRandom class is an engine class that provides the functionality of a random number generator.

Creating a SecureRandom Object

As with all engine classes, the way to get a SecureRandom object is to call the getInstance static factory method on the SecureRandom class:
    public static SecureRandom getInstance(String algorithm)
A caller may optionally specify the name of a provider, which will guarantee that the implementation of the random number generation (RNG) algorithm requested is from the named provider:
    public static final SecureRandom getInstance(String algorithm,
                                                 String provider)

Seeding or Re-Seeding the SecureRandom Object

The SecureRandom implementation attempts to completely randomize the internal state of the generator itself unless the caller follows the call to a getInstance method with a call to one of the setSeed methods:
    synchronized public void setSeed(byte[] seed)
    public void setSeed(long seed)
Once the SecureRandom object has been seeded, it will produce bits as random as the original seeds.

At any time a SecureRandom object may be re-seeded using one of the setSeed methods. The given seed supplements, rather than replaces, the existing seed. Thus, repeated calls are guaranteed never to reduce randomness.

Using a SecureRandom Object

To 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 the generateSeed method to generate a given number of seed bytes (to seed other random number generators, for example):
    public byte[] generateSeed(int numBytes)

Code Examples

Computing a MessageDigest Object

First create the message digest object, as in the following example:
    MessageDigest sha = MessageDigest.getInstance("SHA");
This call assigns a properly initialized message digest object to the sha variable. The implementation implements the Secure Hash Algorithm (SHA), as defined in the National Institute for Standards and Technology's (NIST) FIPS 180-1 document. See Appendix A for a complete discussion of standard names and algorithms.

Next, suppose we have three byte arrays, i1, i2 and i3, which form the total input whose message digest we want to compute. This digest (or "hash") could be calculated via the following calls:

    sha.update(i1);
    sha.update(i2);
    sha.update(i3);
    byte[] hash = sha.digest();
An equivalent alternative series of calls would be:
    sha.update(i1);
    sha.update(i2);
    byte[] hash = sha.digest(i3);
After the message digest has been calculated, the message digest object is automatically reset and ready to receive new data and calculate its digest. All former state (i.e., the data supplied to update calls) is lost.

Some hash implementations may support intermediate hashes through cloning. Suppose we want to calculate separate hashes for:

A way to do it is:
    /* compute the hash for i1 */
    sha.update(i1); 
    byte[] i1Hash = sha.clone().digest();

    /* compute the hash for i1 and i2 */
    sha.update(i2); 
    byte[] i12Hash = sha.clone().digest(); 

    /* compute the hash for i1, i2 and i3 */
    sha.update(i3); 
    byte[] i123hash = sha.digest();
This works only if the SHA implementation is cloneable. While some implementations of message digests are cloneable, others are not. To determine whether or not cloning is possible, attempt to clone the MessageDigest object and catch the potential exception as follows:
try {
   // try and clone it
    /* compute the hash for i1 */
    sha.update(i1); 
    byte[] i1Hash = sha.clone().digest();
    . . .
    byte[] i123hash = sha.digest();
} catch (CloneNotSupportedException cnse) {
  // do something else, such as the code shown below
}
If a message digest is not cloneable, the other, less elegant way to compute intermediate digests is to create several digests. In this case, the number of intermediate digests to be computed must be known in advance:
    MessageDigest i1 = MessageDigest.getMessageDigest("SHA");
    MessageDigest i12 = MessageDigest.getMessageDigest("SHA");
    MessageDigest i123 = MessageDigest.getMessageDigest("SHA");

    byte[] i1Hash = i1.digest(i1);

    i12.update(i1);
    byte[] i12Hash = i12.digest(i2);

    i123.update(i1);
    i123.update(i2);
    byte[] i123Hash = i123.digest(i3);

Generating a Pair of Keys

In this example we will generate a public-private key pair for the algorithm named "DSA" (Digital Signature Algorithm). We will generate keys with a 1024-bit modulus, using a user-derived seed, called userSeed. We don't care which provider supplies the algorithm implementation.

Creating the Key Pair Generator

The first step is to get a key pair generator object for generating keys for the DSA algorithm:
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");

Initializing the Key Pair Generator

The next step is to initialize the key pair generator. In most cases, algorithm-independent initialization is sufficient, but in some cases, algorithm-specific initialization is utilized.
Algorithm-Independent Initialization
All key pair generators share the concepts of a keysize and a source of randomness. A KeyPairGenerator class initialize method has these two types of arguments. Thus, to generate keys with a keysize of 1024 and a new SecureRandom object seeded by the userSeed value, you can use the following code:
    SecureRandom random = SecureRandom.getInstance("IBMSecureRandom", "IBMJCA");
    random.setSeed(userSeed);
    keyGen.initialize(1024, random);
Since no other parameters are specified when you call the above algorithm-independent initialize method, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with each of the keys. The provider may use precomputed parameter values, or may generate new values.
Algorithm-Specific Initialization
For situations where a set of algorithm-specific parameters already exists (e.g., so-called "community parameters" in DSA), there are two initialize methods that have an AlgorithmParameterSpec argument. Suppose your key pair generator is for the "DSA" algorithm, and you have a set of DSA-specific parameters, p, q, and g, that you would like to use to generate your key pair. You could execute the following code to initialize your key pair generator (recall that DSAParameterSpec is an AlgorithmParameterSpec):
    DSAParameterSpec dsaSpec = new DSAParameterSpec(p, q, g);
    SecureRandom random = SecureRandom.getInstance("IBMSecureRandom", "IBMJCA");
    random.setSeed(userSeed);
    keyGen.initialize(dsaSpec, random);
(Note: The parameter named p is a prime number whose length is the modulus length ("size"). Thus, you don't need to call any other method to specify the modulus length.)

Generating the Pair of Keys

The final step is generating the key pair. No matter which type of initialization was utilized (algorithm-independent or algorithm-specific), the same code is used to generate the key pair:
    KeyPair pair = keyGen.generateKeyPair();
 

Generating and Verifying a Signature Using Generated Keys

The following signature generation and verification examples utilize the key pair generated in the key pair example above.

Generating a Signature

We first create a signature object:
    Signature dsa = Signature.getInstance("SHA1withDSA");
Next, using the key pair generated in the key pair example, we initialize the object with the private key, then sign a byte array called data.
    /* Initializing the object with a private key */
    PrivateKey priv = pair.getPrivate();
    dsa.initSign(priv);

    /* Update and sign the data */
    dsa.update(data);
    byte[] sig = dsa.sign();
 

Verifying a Signature

Verifying the signature is straightforward. (Note: here we also use the key pair generated in the key pair example.)
    /* Initializing the object with the public key */
    PublicKey pub = pair.getPublic();
    dsa.initVerify(pub);

    /* Update and verify the data */
    dsa.update(data);
    boolean verifies = dsa.verify(sig);
    System.out.println("signature verifies: " + verifies);

Generating/Verifying Signatures Using Key Specifications and KeyFactory

Suppose that, rather than having a public/private key pair (as, for example, was generated in the key pair example above), you simply have the components of your DSA private key: x (the private key), p (the prime), q (the sub-prime), and g (the base).

Further suppose you want to use your private key to digitally sign some data, which is in a byte array named someData. You would do the following steps, which also illustrate creating a key specification and using a key factory to obtain a PrivateKey from the key specification (initSign requires a PrivateKey):

    DSAPrivateKeySpec dsaPrivKeySpec =
        new DSAPrivateKeySpec(x, p, q, g);

    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PrivateKey privKey = keyFactory.generatePrivate(dsaPrivKeySpec);

    Signature sig = Signature.getInstance("SHA1withDSA");
    sig.initSign(privKey);
    sig.update(someData);
    byte[] signature = sig.sign();
Suppose Alice wants to use the data you signed. In order for her to do so, and to verify your signature, you need to send her three things: You can store the someData bytes in one file, and the signature bytes in another, and send those to Alice.

For the public key, assume, as in the signing example above, you have the components of the DSA public key corresponding to the DSA private key used to sign the data. Then you can create a DSAPublicKeySpec from those components:

        DSAPublicKeySpec dsaPubKeySpec =
                new DSAPublicKeySpec(y, p, q, g);
You still need to extract the key bytes so that you can put them in a file. To do so, you can first call the generatePublic method on the DSA key factory already created in the example above:
        PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);
Then you can extract the (encoded) key bytes via the following:
        byte[] encKey = pubKey.getEncoded();
You can now store these bytes in a file, and send it to Alice along with the files containing the data and the signature.

Now, assume Alice has received these files, and she copied the data bytes from the data file to a byte array named data, the signature bytes from the signature file to a byte array named signature, and the encoded public key bytes from the public key file to a byte array named encodedPubKey.

Alice can now execute the following code to verify the signature. The code also illustrates how to use a key factory in order to instantiate a DSA public key from its encoding (initVerify requires a PublicKey).

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encodedPubKey);

    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance("SHA1withDSA");
    sig.initVerify(pubKey);
    sig.update(data);
    sig.verify(signature);
Note: In the above, Alice needed to generate a PublicKey from the encoded key bits, since initVerify requires a PublicKey. Once she has a PublicKey, she could also use the KeyFactory getKeySpec method to convert it to a DSAPublicKeySpec so that she can access the components, if desired, as in:
    DSAPublicKeySpec dsaPubKeySpec =
        (DSAPublicKeySpec)keyFactory.getKeySpec(pubKey,
            DSAPublicKeySpec.class)
Now she can access the DSA public key components y, p, q, and g through the corresponding "get" methods on the DSAPublicKeySpec class (getY, getP, getQ, and getG).

Reading Base64-Encoded Certificates

The following example reads a file with Base64-encoded certificates, which are each bounded at the beginning by
-----BEGIN CERTIFICATE-----
and at the end by
-----END CERTIFICATE-----
We convert the FileInputStream (which does not support mark and reset) to a ByteArrayInputStream (which supports those methods), so that each call to generateCertificate consumes only one certificate, and the read position of the input stream is positioned to the next certificate in the file:
 
 
FileInputStream fis = new FileInputStream(filename);
DataInputStream dis = new DataInputStream(fis);

CertificateFactory cf = CertificateFactory.getInstance("X.509");

byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

while (bais.available() > 0) {
   Certificate cert = cf.generateCertificate(bais);
   System.out.println(cert.toString());
}

Parsing a Certificate Reply

The following example parses a PKCS#7-formatted certificate reply stored in a file and extracts all the certificates from it:
 
 
FileInputStream fis = new FileInputStream(filename);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection c = cf.generateCertificates(fis);
Iterator i = c.iterator();
while (i.hasNext()) {
   Certificate cert = (Certificate)i.next();
   System.out.println(cert);
}

Appendix A: Standard Names

The Java 2 SDK Security API requires and utilizes a set of standard names for algorithms, certificate and keystore types. This specification establishes the following names as standard names.
 

See Appendix B for algorithm specifications.

Message Digest Algorithms

The algorithm names in this section can be specified when generating an instance of MessageDigest.

SHA: The Secure Hash Algorithm, as defined in Secure Hash Standard, NIST FIPS 180-1.

MD2: The MD2 message digest algorithm as defined in RFC 1319.

MD5: The MD5 message digest algorithm as defined in RFC 1321.

Key and Parameter Algorithms

The algorithm names in this section can be specified when generating an instance of KeyPairGenerator, KeyFactory, AlgorithmParameterGenerator, and AlgorithmParameters.

RSA: The RSA encryption algorithm as defined in PKCS#1.

DSA: The Digital Signature Algorithm as defined in FIPS PUB 186.

Digital Signature Algorithms

The algorithm names in this section can be specified when generating an instance of Signature.

SHA1withDSA: The DSA with SHA-1 signature algorithm which uses the SHA-1 digest algorithm and DSA to create and verify DSA digital signatures as defined in FIPS PUB 186.

MD2withRSA: The MD2 with RSA Encryption signature algorithm which uses the MD2 digest algorithm and RSA to create and verify RSA digital signatures as defined in PKCS#1.

MD5withRSA: The MD5 with RSA Encryption signature algorithm which uses the MD5 digest algorithm and RSA to create and verify RSA digital signatures as defined in PKCS#1.

SHA1withRSA: The signature algorithm with SHA-1 and the RSA encryption algorithm as defined in the OSI Interoperability Workshop, using the padding conventions described in PKCS #1.

Random Number Generation (RNG) Algorithms

The algorithm names in this section can be specified when generating an instance of SecureRandom.

IBMSecureRandom: The name of the pseudo-random number generation (PRNG) algorithm supplied by the IBMJCA provider. This implementation follows the IEEE P1363 standard, Appendix G.7: "Expansion of source bits", and uses SHA1 as the foundation of the PRNG. It computes the SHA1 hash over a true-random seed value concatenated with a 64-bit counter which is incremented by 1 for each operation. From the 160-bit SHA1 output, only 64 bits are used.

Certificate Types

The types in this section can be specified when generating an instance of CertificateFactory.

X.509: The certificate type defined in X.509.

Keystore Types

The types in this section can be specified when generating an instance of KeyStore.

JCAKS: The name of the keystore implementation provided by the IBMJCA provider.

PKCS12: The transfer syntax for personal identity information as defined in PKCS#12.

Service Attributes

A cryptographic service is always associated with a particular algorithm or type. For example, a digital signature service is always associated with a particular algorithm (e.g., DSA), and a CertificateFactory service is always associated with a particular certificate type (e.g., X.509).

The attributes in this section are for cryptographic services. The service attributes can be used as filters for selecting providers.

Both the attibute name and value are case insensitive.

KeySize: The maximum key size that the provider supports for the cryptographic service.

ImplementedIn: Whether the implementation for the cryptographic service is done by software or hardware. The value of this attribute is "software" or "hardware".


Appendix B: Algorithms

This appendix specifies details concerning some of the algorithms defined in Appendix A. Any provider supplying an implementation of the listed algorithms must comply with the specifications in this appendix. Note: The most recent version of this document is available from the public web site http://java.sun.com/j2se/sdk/1.3/docs/guide/security/index.html.

To add a new algorithm not specified herein, you should first survey other people or companies supplying provider packages to see if they have already added that algorithm, and, if so, use the definitions they published, if available. Otherwise, you should create and make available a template, similar to those found in this Appendix B, with the specifications for the algorithm you provide.

Specification Template

The algorithm specifications below contain the following fields:

Name

The name by which the algorithm is known. This is the name passed to the getInstance method (when requesting the algorithm), and returned by the getAlgorithm method to determine the name of an existing algorithm object. These methods are in the relevant engine classes: Signature, MessageDigest, KeyPairGenerator, and AlgorithmParameterGenerator.

Type

The type of algorithm: Signature, MessageDigest, KeyPairGenerator, or ParameterGenerator.

Description

General notes about the algorithm, including any standards implemented by the algorithm, applicable patents, etc.

KeyPair Algorithm (Optional)

The keypair algorithm for this algorithm.

Keysize (Optional)

For a keyed algorithm or key generation algorithm: the legal keysizes.

Size (Optional)

For an algorithm parameter generation algorithm: the legal "sizes" for algorithm parameter generation.

Parameter Defaults (Optional)

For a key generation algorithm: the default parameter values.

Signature format (Optional)

For a Signature algorithm, the format of the signature, that is, the input and output of the verify and sign methods, respectively.

Algorithm Specifications

SHA-1 Message Digest Algorithm

Name: SHA

Type: MessageDigest

Description: The message digest algorithm as defined in NIST's FIPS 180-1. The output of this algorithm is a 160-bit digest.

MD2 Message Digest Algorithm

Name: MD2

Type: MessageDigest

Description: The message digest algorithm as defined in RFC 1319. The output of this algorithm is a 128-bit (16 byte) digest.

MD5 Message Digest Algorithm

Name: MD5

Type: MessageDigest

Description: The message digest algorithm as defined in RFC 1321. The output of this algorithm is a 128-bit (16 byte) digest.

The Digital Signature Algorithm

Name: SHA1withDSA

Type: Signature

Description: This algorithm is the signature algorithm described in NIST FIPS 186, using DSA with the SHA1 message digest algorithm.

KeyPair Algorithm: DSA

Signature Format: an ASN.1 sequence of two INTEGER values: r and s, in that order: SEQUENCE ::= { r INTEGER, s INTEGER }

RSA-based Signature Algorithms, with MD2, MD5 or SHA1

Names: MD2withRSA, MD5withRSA and SHA1withRSA

Type: Signature

Description: These are the signature algorithms that use the MD2, MD5, and SHA1 message digest algorithms (respectively) with RSA encryption.

KeyPair Algorithm: RSA

Signature Format: A DER-encoded PKCS#1 block as defined in RSA Laboratory's Public Key Cryptography Standards Note #1. The data encrypted is the digest of the data signed.

DSA KeyPair Generation Algorithm

Name: DSA

Type: KeyPairGenerator

Description: This algorithm is the key pair generation algorithm described in NIST FIPS 186 for DSA.

Keysize: The length, in bits, of the modulus p. This must range from 512 to 1024, and must be a multiple of 64. The default keysize is 1024.

Parameter Defaults: The following default parameter values are used for keysizes of 512, 768, and 1024 bits.

512-bit Key Parameters
SEED = b869c82b 35d70e1b 1ff91b28 e37a62ec dc34409b

counter = 123

p = fca682ce 8e12caba 26efccf7 110e526d b078b05e decbcd1e b4a208f3
    ae1617ae 01f35b91 a47e6df6 3413c5e1 2ed0899b cd132acd 50d99151
    bdc43ee7 37592e17

q = 962eddcc 369cba8e bb260ee6 b6a126d9 346e38c5
         
g = 678471b2 7a9cf44e e91a49c5 147db1a9 aaf244f0 5a434d64 86931d2d
    14271b9e 35030b71 fd73da17 9069b32e 2935630e 1c206235 4d0da20a
    6c416e50 be794ca4

768-bit key parameters
SEED = 77d0f8c4 dad15eb8 c4f2f8d6 726cefd9 6d5bb399

counter = 263

p = e9e64259 9d355f37 c97ffd35 67120b8e 25c9cd43 e927b3a9 670fbec5
    d8901419 22d2c3b3 ad248009 3799869d 1e846aab 49fab0ad 26d2ce6a
    22219d47 0bce7d77 7d4a21fb e9c270b5 7f607002 f3cef839 3694cf45
    ee3688c1 1a8c56ab 127a3daf

q = 9cdbd84c 9f1ac2f3 8d0f80f4 2ab952e7 338bf511

g = 30470ad5 a005fb14 ce2d9dcd 87e38bc7 d1b1c5fa cbaecbe9 5f190aa7
    a31d23c4 dbbcbe06 17454440 1a5b2c02 0965d8c2 bd2171d3 66844577
    1f74ba08 4d2029d8 3c1c1585 47f3a9f1 a2715be2 3d51ae4d 3e5a1f6a
    7064f316 933a346d 3f529252

1024-bit key parameters
SEED = 8d515589 4229d5e6 89ee01e6 018a237e 2cae64cd

counter = 92

p = fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80
    b6512669 455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b
    801d346f f26660b7 6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6
    1bf83b57 e7c6a8a6 150f04fb 83f6d3c5 1ec30235 54135a16 9132f675
    f3ae2b61 d72aeff2 2203199d d14801c7

q = 9760508f 15230bcc b292b982 a2eb840b f0581cf5
         
g = f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b
    3d078267 5159578e bad4594f e6710710 8180b449 167123e8 4c281613
    b7cf0932 8cc8a6e1 3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f
    0bfa2135 62f1fb62 7a01243b cca4f1be a8519089 a883dfe1 5ae59f06
    928b665e 807b5525 64014c3b fecf492a

RSA KeyPair Generation Algorithm

Name: RSA

Type: KeyPairGenerator

Description: This algorithm is the key pair generation algorithm described in PKCS#1.

Strength: Any integer that is a multiple of 8, greater than or equal to 512.

DSA Parameter Generation Algorithm

Name: DSA

Type: ParameterGenerator

Description: This algorithm is the parameter generation algorithm described in NIST FIPS 186 for DSA.

Size: The length, in bits, of the modulus p. This must range from 512 to 1024, and must be a multiple of 64. The default size is 1024.

Appendix C: Hardware Cryptography, IBMJCA4758 specifics

Introduction

 
The IBMJCA4758 implementation adds a provider that extends JCA to seamlessly add the capability to use hardware cryptography via the IBM Common Cryptographic Architecture (CCA) interfaces. This new provider takes advantage of hardware cryptography within the existing JCA architecture and gives Java 2 programmers the significant security and performance advantages of hardware cryptography with minimal changes to existing Java applications.  As the complexities of hardware cryptography are taken care of within the normal Java Cryptography Architecture advanced security and performance using hardware cryptographic devices is made easily available.

IBM CCA is a set of software elements that provide common application interfaces to secure, high-speed cryptographic services on various platforms via hardware cryptographic devices.  These devices include the IBM 4758 PCI Cryptographic Coprocessor and the Cryptographic Coprocessor.  The amount and type of  hardware cryptographic services available depends on your platform and hardware device.  For more information please refer to your platform's hardware cryptography information and service/support organization and  "Configuring and using hardware cryptographic devices" for more information.

IBMJCA4758 provides for all the engine classes available in JCA including: Message Digest, Signature and KeyFactory classes.  This makes available Message Digests via the MD2, MD5 and SHA-1 algorithms.  It further provides digital signature and verification via the RSA and DSA algorithms (DSA is available in hardware on the OS/390 and z/OS platforms only) .  This implementation also includes true Random number generation, key generation via key factories, key/certificate generation and key/certificate management via a keytool application.
 

Types of cryptographic hardware utilization

In the hardware cryptography environment there are multiple ways to take advantage of the hardware.  There are three types of hardware utilization that this provider supports.  The three types of hardware utilization are all tied to the key pair that was generated.  That is once a key pair is generated that key pair is then tied to a type of hardware utilization.  The three types of hardware utilization are; "RETAINED", "PKDS" and "CLEAR" and will be described in more detail below.  The types of hardware utilization make trade offs between increased security and increased performance, but it is normally the case that any of the types of hardware cryptographic utilization will be both more secure and significantly faster than similar cryptographic functions as performed by a software only implementation.
 

Retained hardware key pairs

The hardware can be used to maximize the security of the environment. The most secure implementation of cryptography supported by this provider is to store the keys on the actual hardware cryptographic device and never allow the private key, the sensitive part of the key pair, to be retrieved or viewed.  This is called a "RETAINED" key pair as the private key is retained on the actual hardware device and is never allowed to be viewed or retrieved in the clear.  What is returned to the application or stored in the keystore at key pair generation is only a reference to the private key called a label. When the key is needed, the request is sent to the hardware card via the label where the key is retained and the cryptographic operation is performed on that card using the retained key and the results returned.  This is the most secure of the key types, but also tends to be the slowest as the cryptographic calls for a specific key pair must go to the hardware device that has that key pair and therefore can not take advantage of multiple cryptographic devices that could be available on the system.
 

PKDS hardware key pairs

The hardware can also be used to provide increased security, but also take advantage of multiple hardware devices on the system. The medium level of security supported buy this provider is called a "PKDS" key pair.  When this type of key pair is generated, the private key is encrypted with the systems master key so that the clear text version of this key can never be viewed or retrieved and the key pair is stored in a system key storage area. (This key storage area varies in type on the various platforms from a RACF protected data set on OS/390 to a file on NT)  What is returned to the application or stored in the keystore at key pair generation is only a reference to the private key called a label.  Thus these types of key pairs can take advantage of multiple cryptographic hardware devices as the private key is decrypted by the CCA software layer and the cryptographic request is sent to the next available cryptographic device for processing.
 

Clear hardware key pairs

The hardware can also be used as an accelerator to accelerate the performance of the cryptographic operation.  The lowest level of hardware security is a "CLEAR" key pair, but this provides the fastest throughput.  When the key pair is generated as a CLEAR key pair the private key is stored in a clear text representation.  The key pair is then tokenized, encrypted with the systems master key, and the token is what is returned to the application or stored in the keystore at key pair generation. This tokenized representation of the clear key pair can be used by the application to perform cryptographic operations on any CCA capable hardware cryptographic device the system supports and as there is no overhead of retrieving the private key from the PKDS or requirements for the cryptographic operation to be processed by a specific hardware device it is the fastest of the three types.

Note: The only type of key pairs that are supported by most software cryptography based JCA providers are CLEAR key pairs.  Further it has been our experience, via some initial testing, that the IBMJCA4758 provider using PKDS key pairs (that add a great deal of security to the sensitive private keys) out performs a JCA software cryptography based implementation using CLEAR key pairs by many times. (We have noted performance increases for an RSA sign and verify operation of between 10 and 30+ times, 1000% to over 3000% incremental improvements, depending on the platform and hardware devices available)
 

Key Pair Storage in general


It is important to note that all three types of hardware key pairs supported by this provider can be utilized by any application.  The RETAINED and PKDS key pairs return a label, that is treated by this provider the same as a key, and can be stored by the application in what ever mechanism they choose. The "CLEAR" key pairs return a tokenized representation of the key pair that is also treated by this provider the same as a key and can be stored by the application.  JCA also provides a built in keystore that can be used to store any of these keys.  The JCA keystore provides an added level of security that allows the keys stored in that key store to be encrypted via password(s) before they are stored in a file.  Thus if you choose to use CLEAR key pairs for performance they can be placed in the JCA keystore in their tokenized form and protected by a password for the key entry.  While these password capabilities in the JCA keystore also exist for the other two types of keys they are not as relevant as all that is stored in the actual JCA keystore is a label to the key pair and no sensitive key information.
 
 

Key Generation and storage


Key generation can be accomplished via either a provided application called hwkeytool or via the JCA API's.  The keytool application that is part of the IBMJCA4758 provider is called hwkeytool and allows you to generate key pairs and store them in a keystore file of type JCA4758KS.  The JCA API'S allow you to generate key pairs and then at the discretion of the application also store them in a keystore file of type JCA4758KS.
 
 

RSA Signature and Verification


The IBMJCA4758 provider makes digital signature and verification via the RSA and DSA algorithms available.  This implementation also moves all of the algorithm processing to the actual hardware device and as RSA is a rather compute intensive algorithm this moves a great deal of CPU instructions off of the main platform and onto the cryptographic hardware device.  Further the cryptographic hardware processes this work on a secure card so that it is much harder to capture and compromise the sensitive material and is much faster than the software version.  Also hardware gives you the choice of three levels of security including CLEAR key pairs, PKDS based key pairs and RETAINED key pairs. So by taking advantage of the hardware capabilities you increase the base security of the operation by utilizing the hardware to process the algorithm and data, reduce the load on your main platform, increase the throughput rate of the request and have the option of using more secure key pairs.

The specific way in which the RSA request is handled is dependent on the actual hardware device that is present on your platform.  In the case of OS/390 (z/OS) the system can have one or more of both the IBM 4758 PCI Cryptographic Coprocessor and the Cryptographic Coprocessor (CCF).  In this environment if both types of devices are present than the CCA software will route the RSA signature operations to one of the IBM 4758 devices and the RSA verify operations to one of the CCF devices.  (as a verification is a public key operation that is less secure and is handled faster by the CCF than the IBM 4758) This tends to further enhance the throughput of the operations as multiple hardware devices are utilized for the specific operations they tend to perform most efficiently.  On other platforms that only have an IBM 4758 PCI Cryptographic Coprocessor both the RSA signature and verification are performed on that device.
 

DSA Signature and Verification


DSA signature and verification via hardware cryptographic devices is only available on the OS/390 (z/OS) platform as this is not supported by the IBM 4758 and is only available in hardware via the CCF.  (The CCF hardware device is only supported on OS/390 (z/OS) while the IBM 4758 is supported via CCA on several platforms)

Further it is important to understand that due to the hardware capabilities for DSA in the CCF the only type of key pairs that are available for DSA are PKDS key pairs.  The CCF hardware does not support CLEAR or RETAINED DSA key pairs.

Note, DSA is only available via the hardware on OS/390 and z/OS and is not available in either hardware or software on the other platforms in the IBMJCA4758 provider.  DSA using software cryptography is available on all supported platforms via the IBMJCA provider.
 

MD2, MD5 and SHA-1 hashing algorithms


As the hashing algorithms are not as compute intensive as the RSA and DSA algorithms it is not always advantageous to use hardware devices to perform these operations. (The overhead of using the hardware device can actually outweigh the potential performance gains)  Further the overall security of performing these hashing algorithms on hardware is not substantially better then doing the same hash in software.  (as the hash is then typically used within a more secure RSA or DSA sign/verify)  For these reasons many of today's hardware cryptography devices don't always make these hashing algorithms available and in some cases the CCA software chooses to perform the hashing algorithm in software rather than hardware for performance reasons.

The IBMJCA4758 provider calls the hardware CCA interfaces to perform MD5 and SHA-1 hashing and performs MD2 hashing via software. (IBM CCA in some cases performs the MD5 hash using software)
 

Random Number generation


The IBM CCA capable hardware devices  provide a true random number generator rather than a Pseudo random number generation capability based on salting a random number operation with some random value.  The IBMJCA4758 provider takes advantage of the true random number generation capabilities and makes this available to the application via the SecureRandom class.

Refer to "The SecureRandom Class" for more information.
 

IBMJCA4758 Provider package includes

 

Changes from software JCA to hardware JCA in general

 
It is important to note that in geneal the only things that have changed from a software cryptography implementation of JCA such as IBMJCA to the hardware implementation of JCA (IBMJCA4758) are the key pairs and key representations. All other cryptographic operations have not changed from the previous versions of JCA.  Once the hardware JCA provider (IBMJCA4758) is selected and a key pair is generated  none of the other API's need to be changed to take advantage of the hardware capabilities.  Therefore an existing application can be easily migrated from the software JCA environment (like IBMJCA) into the hardware capable JCA environment (IBMJCA4758).  The migration is simply a matter of generating new key pairs and changing the security provider, via specific calls or the provider list, to point to the new hardware capable JCA (IBMJCA4758).

Even key pair generation has default values available that allow most types of key pair generation as used for a software JCA to be functional in this hardware JCA provider with no changes. In addition the hardware representation of the key (label or internal CCA token) is acceptable to the other JCA API's in IBMJCA4758 that expect a key to be passed with no changes to those API's.

The following section on "Changes to Core Classes and Interfaces" is intended to provide detail for the more advanced application coder.  It may also provide some information on the changes to key pair generation and key representation, but an in depth understanding is probably not required for the typical application developer.


 

Changes to Core Classes and Interfaces

 
This section provides a discussion of the core classes and interfaces that have been changed from the base JCA to the hardware capable IBMJCA4758 provider.

The KeyFactory Class:

The KeyFactory class is an engine class designed to provide opaque cryptographic keys (of type Key) and key specifications (transparent representations of the underlying key material)
DSA
This provider adds a new key type of DSA Private hardware key which is similar to the DSA Private key which is available in a software provider.

The KeyFactory class can be used to generate a DSA Private hardware key from a DSAPrivateKeyHWSpec.  The KeyFactory can also be used to generate a DSA public key from a DSAPublicKeySpec or an X509EncodedKeySpec.

The KeyFactory class can also get a DSAPrivateKeyHWSpec from a DSA Private hardware key or a DSAPublicKeySpec or X509PublicKeySpec from a DSA public key.
 

RSA
This provider adds a new key type of RSA Private hardware key which is similar to the RSA Private key which is available in a software provider

RSA is similar to DSA in that the KeyFactory class can be used to generate a RSA Private hardware key from a RSAPrivateHWKeySpec The KeyFactory can also be used to generate a RSA public key from a RSAPublicKeySpec or a X509EncodedKeySpec. The opposite can also be done to generate a RSAPrivateHWKeySpec from a RSA private hardware key and a RSAPublicKeySpec or X509EncodeKeySpec can be generated from a RSA public key.

Please note that a RSAPrivateKeyHWSpec and a DSAPrivateKeyHWSpec are only valid on the system where the key was originally generated. The private keys are represented in such a way that they can not be moved to another system. This is true as all of the private keys, even clear private keys, are protected and not available outside of this protection.

Note: DSA is only available via the hardware on OS/390 and z/OS and is not available in either hardware or software on the other platforms in the IBMJCA4758 provider.  DSA using software cryptography is available on all supported platforms via the IBMJCA provider

Algorithm Parameters Classes:

The KeyParameterSpec class for DSA hardware (DSAHWKeyParameterSpec):
This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters to use with the DSA hardware algorithm. These include:
 


Please see the java api documentation for the specific methods, default values and restrictions associated with this class.
 

The KeyParameterSpec class for RSA hardware (RSAKeyParameterSpec):
This class implements the AlgorithmParameterSpec interface) specifies the set of parameters to use with the RSA hardware algorithm. These include:


Please see the java api documentation for the specific methods, default values and restrictions associated with this class.


 

The Key Interface Class:

Since this is a hardware implementation the encodings associated with the private keys have no meaning.  These private keys can not be transported to another system for use there. The private keys are all either a key label that points to a token (that is stored in the PKDS or retained on the card)or a token (a CCA internal token representation of the key pair encrypted under the systems master key).  The method to retrieve the representation of the key pair is:
  For DSA this returns the key label, that represents the key stored in the PKDS associated with the hardware.

For RSA if the type of key is clear, the getToken returns an internal CCA token, otherwise it will return a keylabel to the key that is either in the PKDS or stored on the actual card, if the key has a key attribute type of RETAINED.
 

Key Specifications Interfaces and Classes:

The DSAPrivateHWKeySpec Class
This class (which implements the KeySpec Interface) specifies a DSA private hardware key with its associated parameters. It has the following methods: Please see the java api documentation for the specific methods, default values and restrictions associated with this class
 
The RSAPrivateHWKeySpec Class
This class (which implements the KeySpec Interface) specifies a RSA private hardware key with its associated parameters. It has the following methods: Please see the java api documentation for the specific methods, default values and restrictions associated with this class.

The SecureRandom Class:

The SecureRandom class in this provider is a true random number generator and does not need seeding. Therefore, calls to setSeed, getSeed and generateSeed will throw an exception.

     Example of SecureRandom usage
            java.security.SecureRandom random = null;
            random = java.security.SecureRandom.getInstance("IBMSecureRandom");
            byte[] testData = new byte[1024];
            Random.nextBytes(testData);

In this example an instance of the SecureRandom class is obtained, a byte array is instantiated and a random number of the size 1024 is generated.

Please see the java api documentation for the specific methods, default values and restrictions associated with this class
 

Reading Base64-Encoded Certificates

The certificates are read in and written out in ISO8859_1  code page, not the local code page. This was done to make them  compatible with the Base64-Encoded Certificates on other platforms. What this means is the certificate encoding may not be human readable on a platform.
 

The Signature Class:

SHA1 with DSA or RSA, MD2 with RSA and MD5 with RSA are the types of signatures that the IBMJCA4758 provider supports. These are created by first calling the MessageDigest class that is to be associated with the signature and than calling the hardware to create the actual signature from hash and the corresponding private key. These are verified by creating a hash and passing in both the public key and the previously generated signature to the hardware.

Configuring and using hardware cryptographic devices

To use the hardware cryptographic devices the card must be installed and configured according to the specifications that are shipped with the card.On some of the platforms it is also necessary for the user or application to set up the cryptographic environment and provide access control (log into the card)
 

OS/390, z/OS specifics

On the OS/390 and z/OS platforms access to the hardware cryptographic devices is controlled via the Integrated Cryptographic Service Facility (ICSF).  This product provides the CCA interfaces to the actual hardware devices and must be configured and running.  For more information on ICSF please refer to the publications available for this product including:


On the OS/390 and z/OS platforms ICSF handles access control to the actual hardware devices.

 

The hardware keytool application (hwkeytool)

The hwkeytool application for hardware uses the same syntax and commands as the software version provided with JCA (keytool) with the exception of two commands and the default keystore.  The hardware keytool (hwkeytool) provides additional parameters to the genkey and delete commands.  On the genkey command additional parameters of -keylabel (used to allow you to set a specific label for the hardware key), -hardwaretype (used to determine the type of key pair, CLEAR, PKDS or RETAINED) and -hardwareusage (used to set the usage of the key pair being generated, either a signature only key or a signature and key management key). On the delete command an additional parameter of -hardwarekey (to tell the delete command to delete the key pair from the keystore and also delete it from the hardware) is available.  The default keystore was also changed from .keystore to .HWkeystore, but can still be changed with the -keystore parameter.

genkey


delete


As part of the changes the new concept of -hardwareusage gets introduced.  This parameter allows the user to create a key pair and determine the type of authority that key pair will have within the CCA software. The two choices made available via our JCA interfaces are SIGNATURE and KEYMANGEMENT.  SIGNATURE will create a key pair that is valid for signatures (sign and verification) only.  The KEYMANGEMENT option creates a key pair that is valid for signatures and for key management functions.  (The CCA option for key management only keys was not made available as it is not useful within JCA)  The SIGNATURE and KEYMANGEMENT options will not act much differently within the JCA code as both have signature capabilities.  KEYMANGEMENT is needed for later components of Java especially JSSE (Java Secure Sockets Layer).

Another new concept is that of the -keylabel.  As is stated above this option is used to set the label that will be used to identify the hardware key within the hardware storage.  In other words to set a specific label that the CCA software will use to identify the key pair for storage and retrieval.  This label is not really relevant to the JCA application layer, but is made available in the event an advanced user has the need to control the label that the underlying CCA software will be using for the key pair.  The default is to allow the JCA methods to generate a random label that will be used for the key pair.  Again this label will not be needed by the normal JCA application and is only used by the CCA software as a label for a PKDS and/or RETAINED key pairs.

Thus, a sample keytool command to generate and store an RSA key pair under the name Test1 for PKDS based hardware would be:
 

hwkeytool -genkey -alias Test1 -keyalg RSA -storetype JCAKS4758 -dname "cn=Test one, ou=JCA, o=IBM, l=Endicott, st=NY" -keypass test123 -storepass 123test -hardwaretype PKDS  -hardwareusage SIGNATURE


A sample keytool command to delete that entry from the keystore an also delete the keys from the hardware storage would be:
 

hwkeytool -delete -alias Test1 -keypass test123 -storepass 123test -hardwarekey
Keystore Location:
On OS/390 systems, given user id, "user.home" defaults to;  /home/<userid> or if the user id is "U23LPTQ" then the "user.home" is "/home/U23LPTQ".




Copyright © 1996-98 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 2001 IBM Corporation. All Rights Reserved.

Java Software