简体   繁体   中英

Generate CSR in Java using openssl and -subj parameter

I'm generating private .key and .csr and then the certificate using openssl and Runtime.getRuntime().exec() in java. I have given -subj parameter in .csr command to make it non interactive, following is my code

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();
    }

}

the issue is when above .csr command executes it results in an error

unknown option Pvt

this is because of spaces in here Company Pvt Ltd

I tried the same command with

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

It generates the certificate but doesn't convert the %20 with space, and also generate the corrupted .csr

You need to use the overload of exec() that takes a String[] argument, which in turn means you need to define your formats as String[] as well.

Update:

following is the code

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM