start page | rating of books | rating of authors | reviews | copyrights

Book Home Java Security Search this book

10.2. The KeyPairGenerator Class

Generation of public and private keys is one of the standard engines that can be provided by a Java security provider. This operation is provided by the KeyPairGenerator class (java.security.KeyPairGenerator):

public abstract class KeyPairGenerator

Generate and provide information about public/private key pairs.

In Java 1.1, this class extends only the Object class; in Java 1.2, this class extends the KeyPairGeneratorSpi class (java.security.KeyPairGeneratorSpi). As is usual with this architecture, some of the methods we're going to use are methods of the KeyPairGenerator class in Java 1.1 and methods of the KeyPairGeneratorSpi class in 1.2; for the developer, the end result is the same.

Generating a key pair is a very time-consuming operation. Fortunately, it does not need to be performed often; much of the time, we obtain keys from a key management system rather than generating them. However, when we establish our own key management system in the next chapter, we'll need to use this class; it is often easier to generate your own keys from scratch rather than use a key management system as well.

10.2.1. Using the KeyPairGenerator Class

Like all engine classes, the KeyPairGenerator is an abstract class for which there is no implementation in the core API. However, it is possible to retrieve instances of the KeyPairGenerator class via these methods:

public static KeyPairGenerator getInstance(String algorithm)
public static KeyPairGenerator getInstance(String algorithm, String provider)

Find the implementation of the engine that generates key pairs with the named algorithm. The algorithm should be one of the standard API algorithm names; if an appropriate implementation cannot be found, this method throws a NoSuchAlgorithmException.

The first format of this method searches all available providers according to the rules we outlined in Chapter 8, "Security Providers". The second method searches only the named provider, throwing a NoSuchProviderException if that provider has not been loaded.

These methods search the providers that have been registered with the security provider interface for a key pair generator that supports the named algorithm. In the Sun security provider, this method allows us to retrieve the key pair generator that generates keys using the DSA algorithm.

Once we have the key pair generator, we can invoke any of the following methods on it:

public String getAlgorithm()

Return the name of the algorithm that this key pair generator implements (e.g., DSA).

public void initialize(int strength)
public abstract void initialize(int strength, SecureRandom random)

Initialize the key pair generator to generate keys of the given strength. The idea of strength is common among key pair generator algorithms; typically it means the number of bits that are used as input to the engine to calculate the key pair, but the actual meaning may vary between algorithms.

Most key algorithms restrict on the values that are valid for strength. In the case of DSA, the strength must be between 512 and 1024 and it must be a multiple of 64. If an invalid number is passed for strength, an InvalidParameterException will be thrown.

Key pairs typically require a random number generator to assist them. You may specify a particular random number generator if desired; otherwise, a default random number generator (an instance of the SecureRandom class) is used.

In Java 1.2, the second of these methods is inherited from the KeyPairGeneratorSpi class.

public void initialize(AlgorithmParameterSpec params) figure
public void initialize(AlgorithmParameterSpec params, SecureRandom random) figure

Initialize the key pair generator using the specified parameter set (which we'll discuss a little later). By default, the first method simply calls the second method with a default instance of the SecureRandom class; the second method, by default, will throw an UnsupportedOperationException. The second of these methods is inherited from the KeyPairGeneratorSpi class.

public abstract KeyPair generateKeyPair()
public final KeyPair genKeyPair() figure

Generate a key pair, using the initialization parameters previously specified. A KeyPairGenerator object can repeatedly generate key pairs by calling one of these methods; each new call generates a new key pair. The genKeyPair() method simply calls the generateKeyPair() method.

In Java 1.2, the generateKeyPair() method is inherited from the SPI.

Using these methods, generating a pair of keys is very straightforward:

Class Definition

KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();

According to the Java documentation, you are allowed to generate a key pair without initializing the generator; in this situation, a default strength and random number generator are to be used. However, this feature does not work with the Sun security provider in 1.1: a NullPointerException is thrown from within the generateKeyPair() method. Since it is possible that third-party providers may behave similarly, it is always best to initialize the key pair generator.

We'll show what to do with these keys in the next chapter, when we discuss the topic of key management.

10.2.2. Generating DSA Keys

The abstraction provided by the key pair generator is usually all we need to generate keys. However, sometimes the particular algorithm needs additional information to generate a key pair. When a DSA key pair is generated, default values for p, q, and g are used; in the Sun security provider, these values are pre-computed to support strength values of 512 and 1024. Precomputing these values greatly reduces the time required to calculate a DSA key. Third-party DSA providers may provide precomputed values for additional strength values.

It is possible to ask the key generator to use different values for p, q, and g if the key pair generator supports the DSAKeyPairGenerator interface (java. security.interfaces.DSAKeyPairGenerator):

public interface DSAKeyPairGenerator

Provide a mechanism by which the DSA-specific parameters of the key pair engine can be manipulated.

There are two methods in this interface:

public void initialize(int modlen, boolean genParams, SecureRandom random)

Initialize the DSA key pair generator. The modulus length is the number of bits used to calculate the parameters; this must be any multiple of 8 between 512 and 1024. If genParams is true, then the p, q, and g parameters will be generated for this new modulus length; otherwise, a precomputed value will be used (but precomputed values in the Sun security provider are available only for modlen values of 512 and 1024). If the modulus length is invalid, this method throws an InvalidParameterException.

public void initialize(DSAParams params, SecureRandom random)

Initialize the DSA key pair generator. The p, q, and g parameters are set from the values passed in params. If the parameters are not correct, an InvalidParameterException is generated.

As with the DSAKey interface, a DSA key pair generator implements the DSAKeyPairGenerator interface for two purposes: for type identification, and to allow the programmer to initialize the key pair generator with the desired algorithm-specific parameters:

Class Definition

KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
if (kpg instanceof DSAKeyPairGenerator) {
	DSAKeyPairGenerator dkpg = (DSAKeyPairGenerator) kpg;
	dkpg.initialize(512, true, new SecureRandom());
}
else kpg.initialize(512);

In sum, this interface allows us to use the generic key pair generator interface while providing an escape clause that allows us to perform DSA-specific operations.

10.2.3. Implementing a Key Pair Generator

If you want to implement your own key pair generator--either using a new algorithm or, more typically, a new implementation of a standard algorithm--you need to create a concrete subclass of the KeyPairGenerator class. In Java 1.2, you may create a subclass of the KeyPairGeneratorSpi class instead; in this case, the SPI is the superclass of the engine class.

To construct a key pair generator, there is a single protected method at your disposal:

protected KeyPairGenerator(String name)

Construct a key pair generator that implements the given algorithm.

As with the other engines in the security API, there is no default constructor available within the engine class. When the key pair generator is constructed, it must pass the name of the algorithm that it implements to its superclass so that the algorithm name may be correctly registered with the Security class.

There are two abstract public methods of the key pair generator (or its SPI) that we must implement in our key pair generator: the initialize() method and the generateKeyPair() method. For this example, we'll generate a simple key pair that could be used for a simple rotation-based encryption scheme. In this scheme, the key serves as an offset that we add to each ASCII character--hence, if the key is 1, an encryption based on this key converts the letter a to the letter b, and so on (the addition is performed with a modulus such that z will map to a). To support this encryption, then, we need to generate a public key that is simply a number between 1 and 25; the private key is simply the negative value of the public key.

We must also define a class to represent keys we're implementing.[2] We can do that with this class:

[2]This is true even if you're implementing the DSA algorithm--the classes the Sun security provider uses to represent keys are not in the java package, so they are unavailable to us. So even if you're implementing DSA, you must still define classes that implement all the DSA interfaces we looked at earlier.

Class Definition

public class XYZKey implements Key, PublicKey, PrivateKey {
	int rotValue;

	public String getAlgorithm() {
		return "XYZ";
	}

	public String getFormat() {
		return "XYZ Special Format";
	}

	public byte[] getEncoded() {
		byte b[] = new byte[4];
		b[3] = (byte) ((rotValue << 24) & 0xff);
		b[2] = (byte) ((rotValue << 16) & 0xff);
		b[1] = (byte) ((rotValue <<  8) & 0xff);
		b[0] = (byte) ((rotValue <<  0) & 0xff);
		return b;
	}
}

The only data value our key class cares about is the value to be used as the index; for simplicity, we've made it a simple instance variable accessible only by classes in our package. Because this example is simple, we can use the same class as the interface for the public and the private key; normally, of course, public and private keys are not symmetric like this.

With these pieces in place, we're ready to define our key pair generation class:

Class Definition

public class XYZKeyPairGenerator extends KeyPairGenerator {
	SecureRandom random;

	public XYZKeyPairGenerator() {
		super("XYZ");
	}

	public void initialize(int strength, SecureRandom sr) {
		random = sr;
	}

	public KeyPair generateKeyPair() {
		int rotValue = random.nextInt() % 25;
		XYZKey pub = new XYZKey();
		XYZKey priv = new XYZKey();
		pub.rotValue = rotValue;
		priv.rotValue = -rotValue;
		KeyPair kp = new KeyPair(pub, priv);
		return kp;
	}
}

As a last step, we must install this class using the security provider architecture that we examined in Chapter 8, "Security Providers". Now obtaining a new key pair for the XYZ algorithm is as simple as substituting the string XYZ for the algorithm name in the example we gave earlier for DSA key pair generation.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.