0

I am trying to read data from password protected PEM file to generate public and private key from those data. I have the password and I need to pass that password during opening the file. But I haven't any option in java to do that.

Need emergency assistance on this. It would have been much better if I could get a code example for this.

EDITED:

My current code is -

public void readPrivateKey(String filePath)

{
  File fp = new File(filePath);

  FileInputStream fis = new FileInputStream(fp);

 DataInputStrean dis = new DataInputStream(fis);
byte [] keyBytes = new byte [(int) fp.length()];
dis.readFully(keyBytes);
dis.close();
String temp = new String(keyBytes);
String privateKeyPem = removeUnnecessaryTags(temp); //this function returns a string after removing String like this "BEGIN......."
byte[] decoded = Base64.decode(privateKeyPem);
ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence.fromByteArray(decoded);
Enumeration <?> e = primitive.getObjects();

BigInteger bigInt = ((DERInteger)e.NextElement()).getValue();
int version = bigInt.intValue();
BigInteger modulus = ((DERInteger)e.NextElement()).getValue();
BigInteger publicExp = ((DERInteger)e.NextElement()).getValue();
//... all the values has been retrieved in this way
}
Naseef Chowdhury
  • 2,357
  • 3
  • 28
  • 52
  • Did you check `new JcePEMDecryptorProviderBuilder().build(password);` (see http://stackoverflow.com/questions/14919048/bouncy-castle-pemreader-pemparser) – m0skit0 Feb 05 '15 at 11:09

1 Answers1

0

I believe you are taking about RSA key-pair.

You can do it without using Java like this,

openssl rsa -in MYFILE.pem -pubout > MYFILE.pub
ssh-keygen -f MYFILE.pub -i -m PKCS8

If you need to do this in Java, refer to link given by @m0skit0 in comments.


sarveshseri
  • 13,738
  • 28
  • 47