I have a .pem file that contains the private key in this format:
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA3wVu5KhHVJjc9ri5mWKNDW5xXe08smNeu2GSAdBwEaGBHaWj
...
xqDDtaoYKUvwhuKHboTJMs9CtQyrVNk+TDSdfaEdTEWTNeu2UwaP4QBhA==
-----END RSA PRIVATE KEY-----
If I want to convert it manually using OpenSSL I would use this command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in secret.pem -nocrypt secret.key
However, I want to do that programmatically using java but I couldn't figure out how. Any help is much appreciated
The OpenSSL statement converts the PEM encoded private key in PKCS#1 format into a DER encoded key in PKCS#8 format.
In Java, importing the PEM encoded PKCS#1 private key can be done with e.g. BouncyCastle's PEMParser
and JcaPEMKeyConverter
(using the bcprov und bcpkix jars). The export can be accomplished with PrivateKey#getEncoded()
which returns the DER encoded PKCS#8 private key:
import java.io.FileOutputStream;
import java.io.FileReader;
import java.security.KeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
...
String inputFile = "<path to PKCS#1 PEM key>";
String outputFile = "<path to PKCS#8 DER key>";
try (FileReader fileReader = new FileReader(inputFile);
PEMParser pemParser = new PEMParser(fileReader);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
// Import PEM encoded PKCS#1 private key
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
KeyPair keyPair = converter.getKeyPair((PEMKeyPair)pemParser.readObject());
// Export DER encoded PKCS#8 private key
byte[] privateKey = keyPair.getPrivate().getEncoded();
outputStream.write(privateKey, 0, privateKey.length);
}