Java如何基于command調(diào)用openssl生成私鑰證書
在windows環(huán)境下進(jìn)行的測(cè)試,前提條件,windows上需要先安裝openssl。
配置環(huán)境變量,查看版本:

import java.io.*;
import java.util.Properties;
public class OpensslCommand {
private static void runCMD(String[] CMD) {
java.lang.Process process = null;
try {
process = Runtime.getRuntime().exec(CMD);
ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
InputStream processInStream = new BufferedInputStream(process.getInputStream());
int num = 0;
byte[] bs = new byte[1024];
while ((num = errorInStream.read(bs)) != -1) {
resultOutStream.write(bs, 0, num);
}
while ((num = processInStream.read(bs)) != -1) {
resultOutStream.write(bs, 0, num);
}
String result = new String(resultOutStream.toByteArray(), "gbk");
System.out.println(result);
errorInStream.close();
processInStream.close();
resultOutStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (process != null) process.destroy();
}
}
public static void main(String[] args) throws Exception {
//需要指定openssl.exe路徑
//java生成私鑰
String[] cmdPrivateKey = {"cmd", "/C", "C:\\soft\\OpenSSL-Win64\\bin\\openssl.exe genrsa -out ca.key 2048"};
//java生成證書請(qǐng)求
String[] cmdCertificationReq = {"cmd", "/C", "C:\\soft\\OpenSSL-Win64\\bin\\openssl.exe req -new -key ca.key -out ca.csr -subj /C=CN"};
//java生成證書
String[] cmdCertification = {"cmd", "/C", "C:\\soft\\OpenSSL-Win64\\bin\\openssl.exe x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt"};
runCMD(cmdPrivateKey);
runCMD(cmdCertificationReq);
runCMD(cmdCertification);
Properties props=System.getProperties(); //系統(tǒng)屬性
System.out.println("用戶的當(dāng)前工作目錄:"+props.getProperty("user.dir"));
}
}
對(duì)應(yīng)目錄下可以生成:

其中,ca.crt是自簽名證書文件。ca.key是私鑰。ca.csr只是生成證書的中間請(qǐng)求,是用來(lái)指定一些信息,這邊只指定國(guó)家為CN。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring注解驅(qū)動(dòng)開發(fā)實(shí)現(xiàn)屬性賦值
這篇文章主要介紹了Spring注解驅(qū)動(dòng)開發(fā)實(shí)現(xiàn)屬性賦值,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
idea已經(jīng)提交到遠(yuǎn)程分支,但需要本地和遠(yuǎn)程都回退到某一版本問(wèn)題
這篇文章主要介紹了idea已經(jīng)提交到遠(yuǎn)程分支,但需要本地和遠(yuǎn)程都回退到某一版本問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
IntelliJ idea 如何生成動(dòng)態(tài)的JSON字符串(步驟詳解)
這篇文章主要介紹了IntelliJ idea 如何生成動(dòng)態(tài)的JSON字符串,本文分步驟給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
SpringCloud?Feign使用ApacheHttpClient代替默認(rèn)client方式
這篇文章主要介紹了SpringCloud?Feign使用ApacheHttpClient代替默認(rèn)client方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
windows系統(tǒng)使用mvn命令打包并指定jdk路徑方式
這篇文章主要介紹了windows系統(tǒng)使用mvn命令打包并指定jdk路徑方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04

