使用 openssl 和 -subj 参数在 Java 中生成 CSR

Generate CSR in Java using openssl and -subj parameter

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

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 命令执行时会导致错误

unknown option Pvt

这是因为 space 在这里 Company Pvt Ltd

我用

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

它生成证书但不将 %20 转换为 space,并且还生成损坏的 .csr

您需要使用带有 String[] 参数的 exec() 重载,这反过来意味着您也需要将格式定义为 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);