0

I have a key created with OpenSSL from a previous app with the commands:

openssl req -nodes -newkey rsa:2048 -keyout root.key \
    -out root.csr -config ./openssl.cnf

I changed it to a PKCS8 key since I need to use that key in Java with:

openssl pkcs8 -topk8 -nocrypt -in pkcs1_key_file -out pkcs8_key.pem

As far as I can tell, this works since I'm able to create a SSLContext with it. I'm having trouble recreating a KeyPair object in order to perform other operations with it. I've tried:

Path privateKeyPath = Paths.get("root.key.pem");
File privateKeyFile = new File( System.getProperty("user.dir") + File.separator + "ue.key.pem");
byte[] bytes = Files.readAllBytes(privateKeyPath);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
BufferedReader br = new BufferedReader(new FileReader(privateKeyPath.toFile()));
PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemParser.readObject(); // ?????

I've seen other code like Read an encrypted private key with bouncycastle/spongycastle, where they do pemParser.readObject, the object is of type PEMEncryptedKeyPair, or they use the converter to getKeyPair(), but when I call readObject, my object is of type PrivateKeyInfo so I cannot call getKeyPair either.

Is there a step somewhere I'm missing in either the changing to PKCS8 key with the OpenSSL command, or in trying to reconstruct the KeyPair?

halfer
  • 19,824
  • 17
  • 99
  • 186
Crystal
  • 28,460
  • 62
  • 219
  • 393
  • 1
    Also see [Load RSA public key from file](https://stackoverflow.com/q/11410770/608639), [How to Load RSA Private Key From File](https://stackoverflow.com/q/3243018/608639), [Load a RSA private key in Java](https://stackoverflow.com/q/15344125/608639), [How to read .pem file to get private and public key](https://stackoverflow.com/q/11787571/608639), [how to load the private key from a .der file into java private key object](https://stackoverflow.com/q/20119874/608639), etc. – jww Jul 09 '17 at 23:28
  • You have two maybe three choices: (1a) read PKCS8 PEM, strip the header and trailer and convert the base64 to DER, use DER in `PKCS8EncodedKeySpec` in standard JCE `KeyFactory` (1b) use `openssl pkcs8` to convert pkcs8 PEM file to DER file, read DER file and continue as in 1a (2) use BC to read and parse PEM file and convert to internal key object (a separate step in recent versions). FYI: `openssl req -newkey` in versions 1.0.0 up (since 2010) already writes PKCS8 either encrypted or not, you didn't need to convert it unless you're on a very old system. – dave_thompson_085 Jul 10 '17 at 00:42
  • "...As far as I can tell, this works since I'm able to create a SSLContext...". I'm skeptical. – President James K. Polk Jul 10 '17 at 01:59

0 Answers0