直接上代码:
代码所需要的配置文件下载地址 http://download.csdn.net/download/learning_lb/9951635
将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;
}
}