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?
PKCS8EncodedKeySpecin standard JCEKeyFactory(1b) useopenssl pkcs8to 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 -newkeyin 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.