I had a project in which (RSA) encryption was needed, this is how I restored publicKey given the publicKey byte array, which was just read from a file.
public PublicKey reconstruct_public_key(String algorithm, byte[] pub_key) { PublicKey public_key = null; try { KeyFactory kf = KeyFactory.getInstance(algorithm); EncodedKeySpec pub_key_spec = new X509EncodedKeySpec(pub_key); public_key = kf.generatePublic(pub_key_spec); } catch(NoSuchAlgorithmException e) { System.out.println("Could not reconstruct the public key, the given algorithm oculd not be found."); } catch(InvalidKeySpecException e) { System.out.println("Could not reconstruct the public key"); } return public_key; }
Then you can call a procedure similar to this call, reconstruct_public_key("RSA", readFileBytes("path/to/your/publicKey/file"));
EDIT: I tried to do it myself (write the public key to a file, read this file and restore the key). It works:
public static void main(String args[]) { String path = "./pub_key_test.txt"; // Generate a keypair to write to file KeyPair kp = generate_key(); PublicKey pub_key = kp.getPublic(); File file = new File(path); try { // Write to file file.createNewFile(); FileOutputStream out = new FileOutputStream(path); out.write(pub_key.getEncoded()); // Write public key to the file out.close(); // Read from file FileInputStream in = new FileInputStream(path); byte[] pub_key_arr = new byte[in.available()]; in.read(pub_key_arr, 0, in.available()); in.close(); // Reconstruct public key PublicKey reconstructed_pub_key = reconstruct_public_key("RSA", pub_key_arr); } catch(IOException e) { System.out.println("Could not open the file : " + e.getStackTrace()); } }
And this is the generate_key procedure:
public KeyPair generate_key() { while(true) { // Else the compiler will complain that this procedure does not always return a "KeyPair" try { final KeyPairGenerator key_generator = KeyPairGenerator.getInstance("RSA"); key_generator.initialize(2048); // Keys of 2048 bits (minimum key length for RSA keys) are safe enough (according to the slides 128bit keys > 16 years to brute force it) final KeyPair keys = key_generator.generateKeyPair(); return keys; } catch(NoSuchAlgorithmException e) { System.out.println("The given encryption algorithm (RSA) does not exist. -- generate_key() - Cryptography."); } } }
If you check this, you will see that publicKey been successfully restored.
EDIT: I tried to do this myself using the ssh-keygen tool. This is what I did:
- First I created the RSA private key (
.PEM format) - Output part of the public key in
.DER format .DER that it can be used by Java.
Here's how I made the conversion, which is slightly different from yours:
openssl rsa -in private_key_file.pem -pubout -outform DER -out java_readable_file.der
And I read the file as here , which is not much different from yours. I tested this and Java successfully restored the public key.