首页 > 解决方案 > 如何使用运行时从 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

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

标签: javaopenssl

解决方案


我了解到您下载了 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", ...

为防止将来出现此问题,您可以使用此处的说明让 Windows 资源管理器显示全openssl.exe名而不是。openssl

另请注意,当您使用C:\\openssl-1.0.2d-fips-2.0.10\\binas时execDir,路径src\\srcData\\openssh1\\privateKey.pem是相对于execDir. 因此,您应该使用以下方法将其转换为绝对路径:

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

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

这同样适用于输出文件。


推荐阅读