如何使用运行时从JAVA运行openssl命令?

时间:2020-04-06 18:55:47

标签: java openssl

我想阅读使用PuttyGen生成的私钥和公钥,因为我使用openssl将它们转换为DER格式。

String[] execStr = {"openssl","pkcs8", "-topk8", "-inform", "PEM", "-outform","DER", "-in", "src\\srcData\\openssh1\\privateKey.pem","-out", "src\\srcData\\openssh1\\privateKey.der" };

File execDir = new File("C:\\openssl-1.0.2d-fips-2.0.10\\bin");

Runtime.getRuntime().exec(execStr,null,execDir);

但是我收到此错误:

Exception in thread "main" java.io.IOException: Cannot run program "openssl" (in directory "C:\openssl-1.0.2d-fips-2.0.10\bin"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1059)
    at java.lang.Runtime.exec(Runtime.java:631)
    at PrivateKeyReader.get(PrivateKeyReader.java:21)
    at Test1.main(Test1.java:50)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:455)
    at java.lang.ProcessImpl.start(ProcessImpl.java:151)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1040)
    ... 3 more

在这里我无法找出确切的问题,如果有人知道,请告诉我。

1 个答案:

答案 0 :(得分:0)

我了解您下载了Windows版本的openssl-1.0.2d-fips-2.0.10。 bin文件夹中包含的可执行文件称为openssl.exe,而不是openssl。因此,您将收到错误The system cannot find the file specified。因此,您的execStr应该是String[] execStr = {"openssl.exe", ...

为防止将来出现此问题,您可以按照说明here使Windows资源管理器显示完整的openssl.exe而不是openssl的名称。

还要注意,当您将C:\\openssl-1.0.2d-fips-2.0.10\\bin用作execDir时,路径src\\srcData\\openssh1\\privateKey.pem是相对于execDir的。因此,您应该使用以下命令将其转换为绝对路径:

File inputFile = new File("src\\srcData\\openssh1\\privateKey.pem");

String[] execStr = {"openssl.exe ", ..., "-in", inputFile.getCanonicalPath(), ... };

输出文件也是如此。