Generate Public/Private Key Pair in Java

Java example to generate public/private key pairs using KeyPairGenerator class.

In Java generating public private key using RSA algorithm is quite easy as it provides lib to do these tasks. In Java package contains classes to do these operation.


Generating public private key pairs

By using KeyPairGenerator class we can generate public/private key pairs as given below. It’s getInstance method takes algorithm name as input parameter(like “RSA, ”SHA1PRNG“ etc) and returns KeyPairGenerator object of that algorithm.

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair kp = kpg.genKeyPair();
// Get public Key object
Key publicKey = kp.getPublic();
// Get Private Key object
Key privateKey = kp.getPrivate();

Now you can store these keys by generating hex string value or byte string values and distribute public key for decryption.

Generating Hex/Byte string values of keys

You can generate HEX encodes string as given below for your keys.

byte[] publicKeyData = publicKey.getEncoded();
StringBuffer retString = new StringBuffer();
for (int i = 0; i < publicKeyData.length; ++i) {
    retString.append(Integer.toHexString(0x0100 + (publicKeyData[i] & 0x00FF)).substring(1));
//Now you can distribute this public key string

For generating bytes in string you can use following code

byte[] publicKeyData = publicKey.getEncoded();
StringBuffer retString = new StringBuffer();
for (int i = 0; i < publicKeyData.length; ++i) {
    retString.append(", ");
retString = retString.delete(retString.length()-2,retString.length());

Now using these key you can encrypt and decrypt your data.