java - 如何使用运行时从 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
在这里我无法弄清楚确切的问题,如果有人知道,请告诉我。
解决方案
我了解到您下载了 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\\bin
as时execDir
,路径src\\srcData\\openssh1\\privateKey.pem
是相对于execDir
. 因此,您应该使用以下方法将其转换为绝对路径:
File inputFile = new File("src\\srcData\\openssh1\\privateKey.pem");
String[] execStr = {"openssl.exe ", ..., "-in", inputFile.getCanonicalPath(), ... };
这同样适用于输出文件。
推荐阅读
- java - Spring Kafka、Spring Cloud Stream 和 Avro 兼容性未知的魔法字节
- postgresql - 将除法的其余部分放入下一行
- java - NoSuchMethodError:org.springframework.beans.factory.config.ConfigurableListableBeanFactory
- windows-10 - 安装 Oracle 12c 客户端
- python - 重命名数据框中的列名称,该列名称与旧名称具有相似的字符串
- r - 分配包含 R 中原始名称的标识符值
- gradle-release-plugin - 如何使用 gradle-release-plugin 自动增加次要 - 而不是增量
- c++ - C++ 和共享库中的代码执行点
- ruby-on-rails - 正确地将 json 转义为 Ruby 或 Rails 中的命令行调用
- typescript - TypeScript:基于参数类类型的函数重载