Skip to content

Instantly share code, notes, and snippets.

@manzke
Created July 6, 2011 21:54
Show Gist options
  • Save manzke/1068441 to your computer and use it in GitHub Desktop.
Save manzke/1068441 to your computer and use it in GitHub Desktop.
How to generate the PublicKey from a RSA PrivateKey
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import sun.security.rsa.RSAPrivateCrtKeyImpl;
public class PublicKeyGenerator {
public static void main(String[] args) throws Exception {
//convert pem to der with "openssl pkcs8 -topk8 -nocrypt -in key.pem -inform"
byte[] privateKeyBytes = getPrivateKeyBytes("yourprivatecertificate.der");
PrivateKey privateKey = getPrivate(privateKeyBytes); //get private key
//you need to know the Implementation. the interfaces doesn't have all informations or parse it out of the privateKey.toString()
RSAPrivateCrtKeyImpl rsaPrivateKey = (RSAPrivateCrtKeyImpl)privateKey;
//create a KeySpec and let the Factory due the Rest. You could also create the KeyImpl by your own.
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent()));
System.out.println(publicKey.getEncoded()); //store it - that's it
}
public static byte[] getPrivateKeyBytes(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
return keyBytes;
}
public static PrivateKey getPrivate(byte[] privateKeyBytes)
throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
}
@lgoldstein
Copy link

This code assume no other security providers (only JCE) - e.g., if the private key is generated by Bouncycastle then it does not implement RSAPrivateCrtKeyImpl.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment