Generating a Pair of Keys
In this example we will generate a publicprivate key pair for the algorithm named DSA (Digital
Signature Algorithm). We will generate keys with a 1024bit modulus, using a userderived 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, algorithmindependent initialization is sufficient, but in some cases, algorithmspecific initialization is used.
 AlgorithmIndependent Initialization
 All key pair generators share the concepts of a keysize and a source of randomness. A
KeyPairGenerator
classinitialize
method has these two types of arguments. Therefore, to generate keys with a keysize of 1024 and a newSecureRandom
object seeded by theuserSeed
value, you can use the following code:SecureRandom random = SecureRandom.getInstance("IBMSecureRandom", "IBMJCE"); random.setSeed(userSeed); keyGen.initialize(1024, random);
Because no other parameters are specified when you call the algorithmindependent
initialize
method, it is up to the provider to handle the algorithmspecific parameters (if any) that need to be associated with each of the keys. The provider can use precomputed parameter values or can generate new values.  AlgorithmSpecific Initialization
 For situations where a set of algorithmspecific parameters already exists (such as community parameters in DSA), there are two
initialize
methods that have anAlgorithmParameterSpec
argument. Suppose your key pair generator is for the DSA algorithm, and you have a set of DSAspecific parameters,p
,q
, andg
, that you would like to use to generate your key pair. You could execute the following code to initialize your key pair generator (DSAParameterSpec
is an AlgorithmParameterSpec):DSAParameterSpec dsaSpec = new DSAParameterSpec(p, q, g); SecureRandom random = SecureRandom.getInstance("IBMSecureRandom", "IBMJCE"); random.setSeed(userSeed); keyGen.initialize(dsaSpec, random);
Note: The parameter namedp
is a prime number whose length is the modulus length (size). Therefore, 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 you used (algorithmindependent or algorithmspecific), the same code is used to generate the key pair:
KeyPair pair = keyGen.generateKeyPair();