Home > OS >  Convert RSA Private Key to DER Format in Java
Convert RSA Private Key to DER Format in Java

Time:07-01

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

CodePudding user response:

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);
}

CodePudding user response:

You can run the task in a console in the background. Therefor you can use a ProcessBuilder.

//split the command every space and create a process builder
String[] commands = "your command written above...".split(" ");
ProcessBuilder pb = new ProcessBuilder(commands);
// starting the process
Process process = pb.start();

If you need to read the console output (instead of an output file) you can use an input stream:

// for reading the output from stream
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
            process.getInputStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

I haven't tested this code in particular. If you need more info feel free to ask or visit this website: Process Builder

  • Related