Install self-signed Java code signing cert


Official code signing certificates can be expensive, especially if you only need them for internal applications. With the cert installation code below, if a user accepts the certificate once, they won’t have to again because it will be added to their CA list fro Java. This code will exec a system command using Java’s keytool to install your certificate as a certificate authority permanently.

        String tmpLocation = System.getProperty("java.io.tmpdir");
        String[] bases = new String[]{"C:\\Program Files (x86)\\Java\\jre7", "C:\\Program Files\\Java\\jre7"};
        for(String base : bases) {
            try {
                String crt = tmpLocation + "cert.crt";
                File crtFile = new File(crt);
                if(!crtFile.exists()) {
                    System.out.println("Creating cert: " + crt);
                    PrintStream out = new PrintStream(crt);
                    out.print(CERT);
                    out.close();
                    Runtime r = Runtime.getRuntime();
                    Process p = r.exec("\"" + base + "\\bin\\keytool\" -import -storepass changeit -trustcacerts -alias certname -file \"" 
                                         + crt + "\" -keystore \"" + base + "\\lib\\security\\cacerts\"");
                    BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    final PrintStream printStream = new PrintStream(p.getOutputStream());
                    printStream.println("yes");
                    printStream.close();
                    String line = "";
                    while ((line = b.readLine()) != null) {
                      System.out.println(line);
                    }
                    b.close();
                } else {
                    System.out.println("Cert exists: " + crt);
                }
                // exit upon first success
                break; 
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s