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();
}
}
}
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Do you use NetBeans or Eclipse?
Hi, I use IntelliJ IDEA most of the time.
Hi, I want to generate more than 10 pairs of keys. How to do that? do I have to use new
KeyPairGenerator
each time?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.Hi. It worked. Thanks a lot.
I get the same key every time. How do i fix this?