How do I generate public and private keys?

The code snippet below show you how to use the JDK Security API to generate public and private keys. A private key can be used to sign a document and the public key is used to verify that the signature of the document is valid.

The API we used to generate the key pairs is in the java.security package. That’s mean we have to import this package into our code. The class for generating the key pairs is KeyPairGenerator. To get an instance of this class we have to call the getInstance() methods by providing two parameters. The first parameter is algorithm and the second parameter is the provider.

After obtaining an instance of the key generator, we have to initialize it. The initialize() method takes two parameters, the key size and a source of randomness. We set the key size to 1024 and pass and instance of SecureRandom.

Finally, to generate the key pairs we call the generateKeyPair() method of the KeyPairGenerator class. This will return a KeyPair object from where we can get the PrivateKey and PublicKey by calling the getPrivate() and getPublic() method.

Let’s see the code snippet below:

package org.kodejava.security;

import java.security.*;
import java.util.Base64;

public class GenerateKeyPairDemo {
    public static void main(String[] args) {
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");

            // Initialize KeyPairGenerator.
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
            keyGen.initialize(1024, random);

            // Generate Key Pairs, a private key and a public key.
            KeyPair keyPair = keyGen.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();

            Base64.Encoder encoder = Base64.getEncoder();
            System.out.println("privateKey: " + encoder.encodeToString(privateKey.getEncoded()));
            System.out.println("publicKey: " + encoder.encodeToString(publicKey.getEncoded()));
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            e.printStackTrace();
        }
    }
}
Wayan

6 Comments

  1. Hi Swarup, the method’s Javadoc says that it will generate a new key pair every time the method is called. So you don’t need to create a new KeyPairGenerator every time you want to create a pair of keys.

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.