This class generates a public/private key pair for a specified cryptographic algorithm. To create a KeyPairGenerator, call one of the static getInstance( ) methods, specifying the name of the algorithm and, optionally, the name or Provider object of the security provider to use. The default “SUN” provider shipped with Java 1.2 supports only the “DSA” algorithm. The “SunJCE” provider of the Java Cryptography Extension (JCE) additionally supports the “DiffieHellman” algorithm.

Once you have created a KeyPairGenerator, initialize it by calling initialize( ). You can perform an algorithm-independent initialization by simply specifying the desired key size in bits. Alternatively, you can do an algorithm-dependent initialization by providing an appropriate AlgorithmParameterSpec object for the key-generation algorithm. In either case, you may optionally provide your own source of randomness in the guise of a SecureRandom object. Once you have created and initialized a KeyPairGenerator, call genKeyPair( ) to create a KeyPair object. Remember that the KeyPair contains a PrivateKey that must be kept private.

For historical reasons, KeyPairGenerator extends KeyPairGeneratorSpi. Applications should not use any methods inherited from that class.

Figure 14-21.

public abstract class KeyPairGenerator extends KeyPairGeneratorSpi {
// Protected ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.