Code, JavaEE

PKI: Derive Public Key From Private Key

Note: This private key is not used anywhere and is only for demo purposes.
Create private key:

openssl genrsa  -out privkey.pem 2048

The following private key exists in a directory /home/davidking/Projects/Keys/privkey.pem.

—–BEGIN RSA PRIVATE KEY—–
MIIEogIBAAKCAQEAqfgAhtgnIcshay1lS7abeSRnY9CW0E5PMtrlGFSGpEXtrz0Q
58NmsGPFZhYir9O1yVkxvQj0Xmlg3MHL/6Xvmk1+Nm0A9n6M/VexabUwQjRVs/qe
QxddIv6uY4x0abdOcCesuL8TM3tTvZIFwF7YFi73GtgGijKtmRQr4KSvAFGPTNhP
MVpQ9ICCMamLtbyHPHM91Z9yrFDIdu2PFdofW1jaPmYoFQ/yVYzoo6/kkedfHIEI
xKbd+W+jKrwnacaVXEiuwcstJC8gLXZlbagRxKh+/TnV6vzV7lF4BAOi2SyMO7gR
OT/ZcvF0VbSnWvT88S0yWtBQYvwL/2woTfXkuQIDAQABAoIBAAF7Gq4SFg0yUuE3
LQnC1onwqkHxYE8CT6hWxeY3XlDyFwcO1iXeyvdAd0jTaovzoULW1xsZh9+GtYRW
3+sjS/ohMLdSrc53/cx7Rh1wqbH5+MEvrs9Q1cvnQie14pHFOha6EcQuTgGF0o31
Rr2NVf6jfB2swinUFTUfOt6jMK8lAyADbR9eMv3VvrU8f+wxd9EsXoFGuiXgLZT7
D6FQf5Re0hN5rbT7zzgzmKfsnQWunS68wEdz7GYBdltwp1IJPX8gIXEbL1Wd2+AQ
ZHirG7GhfnZzjPuirXpaqF5AwDRHcT+kQaeEma+YSKImn8PYBlAk2A5s2/SOe6++
v7CLX4ECgYEA4j4n8TI7xCNEqRuLwB+OPnUlNIw26VDxUCHKMq+szmdxvMq1TxhD
RMYsTiy05XCYWYvDCTuAQZ5HxXtIu17jS8fBrJ7i/unCA5ah7Wy73JnYmidoyEyf
ZFus8WBIfwBWvjCQKIGUT1xGufvmsf4wr8C8jhbmlNsQbYe8i1VBiKkCgYEAwFMJ
hnBnd7rvYy6uiV7cO/AFGgi+bUowo006ZoriCxI10nJ0sFchxVEkJFGl1jL094Js
14raddS3noOCUxMnpOB2nSeOw5z5OGurbhzodWV1vIJriNPeg331WdiU05TYtOYq
d2O3jZZ000NFs7ILhEJNlOayaqTdnJJkGQd4tZECgYBmO0v1M4vKL12hRK87m4a9
NlYfjpRpjYfde8dQbA2cHyZH9xlCqmYLN7lhgdYkL2LIY9032Mk13X31AKZ29IOl
BJjBlfJg2eQvluuIy6+AGYzE67XvfKAxyzM0xxs7OD36JxudEiCgU8Qp2mf+WixJ
3r/VPQfoj6y2sbVDCL1aMQKBgH7/Vi7cUraRTjpkPQShCzTZDcVfOL/aWbu753CH
DTTaVYgd5Ef9gWNWbVM+Rw/mnjRCf7TlD9T3HjkiBhDteSQ6xJiJ4o/xO/CxyIXx
uN6snM5aIMA9h5W0uysVBVGh3Ge4BRrJUg/A5mwK5CAA1fIEBk7o96/MJjqZwFd2
w5LBAoGAJUsg3Vk7eX3rQG6W/uCwqvaEjlSRS7a/zb3A9i8JeNYgKRr35dF7OvtM
gwavxRY+AoMMsKYA4lL6lVUN3z6RzLaj+eOdTgeV+Ahx8G+XgJVH5I8C3qfPKNHo
Yi1vagtk5yF1FwIasP48cyXb70SAlGX6A0zz7/xM7XLhftDtLwQ=
—–END RSA PRIVATE KEY—–

The following Unit Test reads the private key and derives the public key from it, then converts the public key retrieved into the PEM format using Bouncy Castle’s PEMWriter class. This code was derived from various posts on stackoverflow.com for reference and was very helpful, considering my newness to doing this in code.


package concepts;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.openssl.PEMWriter;
import org.junit.Test;

import java.io.*;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;

/**
 * PublicKeyTest
 *
 * @author David King
 */
public class PublicKeyTest {

@Test
 public void testExtractPublicKey() throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
 java.security.Security.addProvider(
 new org.bouncycastle.jce.provider.BouncyCastleProvider()
 );
 String privateKeyFile = "/home/davidking/Projects/Keys/privkey.pem";
 PrivateKey myPrivateKey = readPemRsaPrivateKey(privateKeyFile);
 RSAPrivateCrtKey privk = (RSAPrivateCrtKey)myPrivateKey;

RSAPublicKeySpec publicKeySpec =
 new java.security.spec.RSAPublicKeySpec(
 privk.getPublicExponent(), privk.getModulus());

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
 PublicKey myPublicKey = keyFactory.generatePublic(publicKeySpec);
 System.out.printf("PUBLIC KEY IS: %s%n", myPublicKey.toString());

System.out.printf("PEM PUBLIC KEY IS: %s%n", toPem(myPublicKey));
 }

public String toPem(PublicKey publicKey) {
 Writer writer = new StringWriter();
 PEMWriter pemWriter = new PEMWriter(writer);
 try {
 pemWriter.writeObject(publicKey);
 } catch (IOException e) {
 e.printStackTrace();
 } finally {
 try {
 pemWriter.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 return writer.toString();
 }

public PrivateKey readPemRsaPrivateKey(String pemFilename) throws
 java.io.IOException,
 java.security.NoSuchAlgorithmException,
 java.security.spec.InvalidKeySpecException
 {
 String pemString = convertFileToString(pemFilename);

pemString = pemString.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
 pemString = pemString.replace("-----END RSA PRIVATE KEY-----", "");

byte[] decoded = Base64.decodeBase64(pemString);

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
 KeyFactory kf = KeyFactory.getInstance("RSA");

return kf.generatePrivate(keySpec);
 }

private String convertFileToString(String fileName) throws
 java.io.FileNotFoundException, java.io.IOException
 {
 File file = new File(fileName);

char[] buffer = null;

BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

buffer = new char[(int)file.length()];

int i = 0;
 int c = bufferedReader.read();

while (c != -1) {
 buffer[i++] = (char)c;
 c = bufferedReader.read();
 }
 return new String(buffer);
 }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s