使用openssl和-subj参数

时间:2016-05-11 06:01:31

标签: java process openssl

我在java中使用.key.csr生成私有opensslRuntime.getRuntime().exec(),然后生成证书。我在-subj命令中给出了.csr参数,使其不具有交互性,以下是我的代码

public void generate(String name) {
    String[] cmds = new String[4];

    String subject = "-subj /C=PK/ST=Sindh/L=Karachi/O=Company Pvt Ltd/OU=IT Department/CN=Developer";
    String configFile = "conf.cnf";

    cmds[0] = String.format("openssl genrsa -out %s.key 2048", path+name);
    cmds[1] = String.format("openssl req -new -key %s.key -out %s.csr %s", path+name, path+name, subject);
    cmds[2] = String.format("openssl x509 -req -in %s.csr -CA %s.pem -CAkey %s.key -CAcreateserial -out %s.crt -days 365 -sha512 -extensions mysection -extfile %s", path+name, path+rootName, path+rootName, path+name, path+configFile);
    cmds[3] = String.format("openssl pkcs12 -export -out %s.pfx -inkey %s.key -in %s.crt", path+name, path+name, path+name);

    try {

        Process p1 = Runtime.getRuntime().exec(cmds[0]);

        // exhaust input stream
        exhaustInputStream(p1);
        p1.waitFor();

        Process p2 = Runtime.getRuntime().exec(cmds[1]);            

        // exhaust input stream
        exhaustInputStream(p2);
        p2.waitFor();

        Process p3 = Runtime.getRuntime().exec(cmds[2]);            

        // exhaust input stream
        exhaustInputStream(p3);
        p3.waitFor();

    } catch (IOException | InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

问题是当上面.csr命令执行时会导致错误

  

未知选项Pvt

这是因为Company Pvt Ltd

中有空格

我用

尝试了同样的命令
String subject = "-subj /C=PK/ST=Sindh/L=Karachi/O=Company%20Pvt%20Ltd/OU=IT%20Department/CN=Riksof";

它会生成证书,但不会将%20转换为空格,还会生成已损坏的.csr

1 个答案:

答案 0 :(得分:2)

您需要使用带有exec()参数的String[]重载,这反过来意味着您还需要将格式定义为String[]

<强>更新

以下是代码

String[] csrCmd = {
    "openssl",
    "req",
    "-new",
    "-key",
    path+name + ".key",
    "-out",
    path+name + ".csr",
    "-subj",
    "/C=PK/ST=Sindh/L=Karachi/O=Company Pvt Ltd/OU=IT Department/CN=Developer"
};

Process p2 = Runtime.getRuntime().exec(csrCmd);