The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Security in JDK 1.1
Lesson: Using the Security API to Generate Public and Private Keys

## Step 2: Generate Public and Private Keys

> The first thing we must do in order to be able to create a digital signature is generate a key pair: a private key and a corresponding public key. A key is a number generated by a random-number generator. A private key is required for signing data, and the corresponding public key is required for verifying the signature.

> A key pair is generated using the KeyPairGenerator class.

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

> Generating a key pair is done with the following steps:

> Create a Key Pair Generator

> > The first step is to get a key pair generator object for generating keys for the DSA signature algorithm. Put the following statement after the

> >             try {

> > line in the file created in the previous step, Step 1:

> >                 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");

> Initialize the Key Pair Generator

> > The next step is to initialize the key pair generator. All key pair generators share the concepts of a "strength" and a source of randomness. The KeyPairGenerator class `initialize` method has these two types of arguments.

> > The "strength" for a DSA key generator is the key length (in bits), which we will set to 1024.

> > The source of randomness must be an instance of the SecureRandom class. For simplicity, we will use the empty constructor for SecureRandom. It will automatically generate a "seed" value required for the random number generation.

> >                 keyGen.initialize(1024, new SecureRandom());

> > Note: the SecureRandom default seed generation algorithm has not yet been thoroughly studied or widely deployed. So if we had a specific seed value that we wanted used instead, we would call the SecureRandom constructor that takes a byte array argument. Thus, if `userSeed` was a byte array containing the desired seed, we'd call

> >                 keyGen.initialize(1024, new SecureRandom(userSeed));

> Generate the Pair of Keys

> > The final step is generating the key pair and storing the keys in an instance of the KeyPair class:

> >                 KeyPair pair = keyGen.generateKeyPair();

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.