Windows下使用java呼叫OpenSSL(無需安裝OpenSSL)
阿新 • • 發佈:2019-01-29
直接上程式碼:
將OpenSSL整個目錄複製到C盤根目錄即可
import java.io.BufferedReader; import java.io.InputStreamReader; public class Demo { /** * @author LB win系統下 java 呼叫OpenSSL */ public static String CertName = "CA"; /** 這幾個value為一些證書資訊,不懂的自行百度 */ public static String Cvalue = "CC";// 長度限制,兩個字母 public static String Svalue = "Svalue"; public static String Lvalue = "Svalue"; public static String Ovalue = "Ovalue"; public static String OUvalue = "OUvalue"; public static String CNvalue = "CNvalue"; /** 這幾個value為一些證書資訊,不懂的自行百度 */ public static String pw = "password";// 密碼 public static int yxq = 3650;// 有效期 public static void main(String[] args) { try { Runtime runtime = Runtime.getRuntime(); // 開啟openSSL String cmd0 = "c:/OpenSSL/openssl.exe "; // 執行命令 String cmd1 = "genrsa -out c:/cert/" + CertName + "-key.pem 1024 "; String cmd2 = "req -new -out c:/cert/" + CertName + "-req.csr -key c:/cert/" + CertName + "-key.pem -passin pass:" + pw + " -subj /C=" + Cvalue + "/ST=" + Svalue + "/L=" + Lvalue + "/O=" + Ovalue + "/OU=" + OUvalue + "/CN=" + CNvalue; String cmd3 = "x509 -req -in c:/cert/" + CertName + "-req.csr -out c:/cert/" + CertName + "-cert.pem -signkey c:/cert/" + CertName + "-key.pem -days " + yxq; String cmd4 = "pkcs12 -export -clcerts -in c:/cert/" + CertName + "-cert.pem -inkey c:/cert/" + CertName + "-key.pem -out c:/cert/" + CertName + ".p12 -password pass:" + pw; Process process; int pcode = 0; process = runtime.exec(cmd0 + cmd1); pcode = process.waitFor(); // pcode=0 ,無錯誤,等於1說明有錯誤。 if (pcode == 1) { throw new Exception(getErrorMessage(process)); } process = runtime.exec(cmd0 + cmd2); pcode = process.waitFor(); if (pcode == 1) { throw new Exception(getErrorMessage(process)); } process = runtime.exec(cmd0 + cmd3); pcode = process.waitFor(); if (pcode == 1) { throw new Exception(getErrorMessage(process)); } process = runtime.exec(cmd0 + cmd4); pcode = process.waitFor(); if (pcode == 1) { throw new Exception(getErrorMessage(process)); } } catch (Exception e) { e.printStackTrace(); } } // 得到控制檯輸出的錯誤資訊 private static String getErrorMessage(Process process) { String errMeaage = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); } errMeaage = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return errMeaage; } }