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 use to sign a document and the public key is use to verify that the signature of the document is valid.

The API we use 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.example.security;

import java.security.*;

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();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }
}

Wayan Saryada

A programmer, a slow runner, a recreational open water diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

2 Comments

Leave a Reply