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



我在java中使用opensslRuntime.getRuntime().exec()生成私有.key.csr,然后生成证书。我在.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命令执行时,会导致错误

未知选项Pvt

这是因为Company Pvt Ltd 中有空格

我用尝试了同样的命令

String subject = "-subj /C=PK/ST=Sindh/L=Karachi/O=Company%20Pvt%20Ltd/OU=IT%20Department/CN=Riksof";

它生成证书,但不使用空间转换%20,还生成损坏的.csr

您需要使用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); 

最新更新