Generate Public/Private Key Pair in Java

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

c4c-3

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");
kpg.initialize(1024);
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
System.out.println(retString);

For generating bytes in string you can use following code

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

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