Generate public key and private key using KeyPairGenerator class in Java

The RSA encryption algorithm uses a pair of public key and private key to implementing the security mechanism. Public key is used to encrypt information and private key is used to decrypt the information and vice versa. Java provides us with several classes to work with the RSA algorithm in java.security package. In this tutorial, I show you how to use Java Security’s KeyPairGenerator class to generate a public key and private key pair for your use!

I will create a main class as an example as follows:

First, you need to initialize the KeyPairGenerator object using the static getInstance() method with the RSA algorithm and the size 1024 or 2048 as follows:

Using the generateKeyPair() method of the KeyPairGenerator object, you will generate a pair of public key and private key, the information contained in the KeyPair object:

From this KeyPair object, you can get the object containing the public key and private key as follows:

You can get the format information of the public key and private key as follows:

My results when running are as follows:

Generate public key and private key using KeyPairGenerator class in Java

As you can see, the default format of the public key is X.509 and the private key is PKCS#8. You can learn more about these formats on the internet!

To save this public key and private key to a file, you can use the following method:

My entire example code is as follows:

Please replace the path to the output file to your liking.

Run the example and check the results!

3/5 - (1 vote)

Add Comment