Generating a Pair of Keys
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 modulus, using a user-derived 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, algorithm-independent initialization is sufficient, but in some cases, algorithm-specific initialization is used.
- Algorithm-Independent Initialization
- All key pair generators share the concepts of a keysize and a source of randomness. A
KeyPairGeneratorclassinitializemethod has these two types of arguments. Therefore, to generate keys with a keysize of 1024 and a newSecureRandomobject seeded by theuserSeedvalue, 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 algorithm-independent
initializemethod, it is up to the provider to handle the algorithm-specific 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. - Algorithm-Specific Initialization
- For situations where a set of algorithm-specific parameters already exists (such as community parameters in DSA), there are two
initializemethods that have anAlgorithmParameterSpecargument. Suppose your key pair generator is for the DSA algorithm, and you have a set of DSA-specific 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 (DSAParameterSpecis 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 namedpis 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 (algorithm-independent or algorithm-specific), the same code is used to generate the key pair:
KeyPair pair = keyGen.generateKeyPair();