Key Generators

How are keys created? A special class, called a key generator, is used to create new, random keys. Three steps are involved in creating cryptographic keys:

  1. Obtain a key generator object for the algorithm you want to use.

  2. Initialize the key generator.

  3. Ask the key generator to generate a key or key pair.

There are two varieties of key generators. The first generates key pairs for use with asymmetric ciphers and signatures. The second kind generates a single key for use with a symmetric cipher.

KeyPairGenerator

The java.security.KeyPairGenerator class creates a matched public and private key and returns them as a KeyPair. You can create a KeyPairGenerator using one of the getInstance() factory methods, as described in Chapter 3. For example, to generate a key pair for ElGamal signing, you obtain a KeyPairGenerator as follows:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("ElGamal");

Like any other getInstance() method, this one may throw a NoSuchAlgorithmException if the given algorithm is not found.

Next, the generator needs to be initialized. There are two methods for this:

public abstract void initialize(int strength, SecureRandom random)

When keys are generated, they will be created for the given strength using the supplied source of random bits. Although the strength of a key almost always refers to its bit length, the interpretation of the strength parameter is algorithm dependent.

public void initialize(int strength)

This method is the same as the last one, except ...

Get Java Cryptography 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.