在Java中运行'openssl req'命令?

时间:2015-06-01 01:40:35

标签: java openssl

似乎x509证书请求只能由Openssl生成,而Java无法控制它。所以我决定在Java中调用Openssl命令;我的系统是Windows7-64bit,JDK 1.7,Openssl 1.02二进制分发。

通过直接Openssl命令生成CSR请求很好,但在Java中调用相同的命令会报告错误。

Openssl命令:

openssl req -new -key bob.pem -out bob.csr -subj /C=CN

Java代码:

Process p;
String command="openssl req -new -key bob.pem -out bob.csr -subj /C=CN";
Runtime r=Runtime.getRuntime();
p=r.exec(command);

错误讯息:

unable to load Private Key
8016:error:0906D06C:PEM routines:PEM_read_bio:no start line:.\crypto\pem\pem_lib.c:701:Expecting: ANY PRIVATE KEY

.pem确实是openssl生成的私钥。请帮我。感谢。

bob.pem通过以下命令生成:

openssl genrsa -out bob.pem

-----BEGIN RSA PRIVATE KEY-----
MIIEpgIBAAKCAQEA25I5wAAGJIBvQtLXghdCjwDuNTbIQX9ISx4ZRDL5CQl8WU7U
vxEnGxJHiJBPE1aJOXSL12LGgzgsnw7G5MIMsJoGI929H8VaiM+iU96+eA6TE6xu
5DheApLiUwq62fybHg1bnXZlHhXUSIQYhTT2dvYMVXnhKO99siLIcKG8LK3H1JUE
KGKShO+0skiA0f70J8hFSGgeB2VCClMkEgoGslYkYnlKNNP38rEWaQdlQdVZGu4q
8okkRcsHsG0vJRx5G7uateoo8uWwqMhVF1tLEcYAYJhOOInofo6MVyqdZ55i8DTb
IPv80kMqx4tmxDN4Q+yjN6PpgijWIG0fA0GlcQIDAQABAoIBAQDNlxkjweH+g5Oq
Ciln0ceshr6EbQsM6NUUINafmOq9n3gjV0C0tqbbHj6EjDq+bKSIe6wEvKQLcam2
NOvefiPLqCxfoNvYx72BpIjl5waI+3yTSz15y52a41WvU7ipK3FCrlc+FQGRLfda
/vTGpVSxBql9z2UYI0aaaR8s9wNvAHzBbfbGTE0JpmTbviyZipj0y18Dykqt5eUO
Wj1Ox0+0hkub7vbVjRIRBUDdsxvLcPZMwPQwdWOsuTH/3wxe/bqczVPVlbDBDok/
xmwd03pqh0+78I6BP/r9eyxwwwe2L94lf+zsojsIu17WlzH9fGhAxfkixTA8TM8l
L/Y1LAgBAoGBAO4gBAaY4VCcoYcGoDbzOXbRBHgN/gvmtVuakidpwA+RSiO2cqgz
bik0d5sSWLqbbxXta+aQdUwX9ngeWUm2dugZP3umkjUfCvrsic6QxiX7up0M5OYF
ukFMaUL0ukr8g7VIA2JaXheia9gEIMnDTbjebA+J/qIUujqfdOACIQ1RAoGBAOwN
qk3kZajPV/Ja3Ij7mAGa5dPwomFTKfBUwbj8cMDDNK+LsR2SpPh8aaIsoWCUwgCB
O3E3TSXql/DvxcgrvRJ52XNm8hERpoCcJ+ol3VmPL+g2C9btjGb6HglON0hiXKAN
F78cSv59OhBbOqbLzhx06XtlKbaxNigWBkQW3I4hAoGBAJnK9a6pGIRu1OgXQGyd
BBUYA9Hh/50CIUmLeC+aXh/vzzlngX/ez5wvNbxiygmjj8hSseiUjh1aMKX9u98e
yIc4n0amGzHR3c6X7J0L5d3sSedax49ETboUtrs2wgbiNdJkM0NXaAPNs+ctK1wE
FnN6u8IBdwKJbomkKODwnxYxAoGBAK2yzIvuskPK91tWMwv1nwAnXFFdtA9L5AN+
SuL1l36w5fb7IwSw4QYcfpqgnst0C2HVtsjzuahZ/R6FQZOvY7zRvwplSWD4DP58
af6piD0b2VPVWVb5jCRGjo2oaZOxFZmMqNmvVxv3SB+7Eeik9fEIsrpjUZOmyUQs
GMZH0FohAoGBANHXkYWRQKSJp02kmwJ1GZ/6905KnDOY9pjFEXTb657yYXvPb1tp
B8pVBwtsrXb6XT827Dpn3Rf/bitqwWwJuWwSc37C/6AavUHQGo1lm8+m86Imy4XJ
xOOhZIpmJocMSF9TBBYFLvJV+s3/1aXrnFPuc5rrh3A1jWtT/zN+lUON
-----END RSA PRIVATE KEY-----

2 个答案:

答案 0 :(得分:1)

使用exec(String[])而不是exec(String)来调用Openssl命令。一种安全的方法是在单独的字符串中列出每个参数

答案 1 :(得分:0)

您总是可以将openssl命令放在bash脚本中,然后像这样从程序启动bash脚本

Process bash_script = Runtime.getRuntime().exec("/your/directory/openssl_script.sh");