Java如何基于command調(diào)用openssl生成私鑰證書
在windows環(huán)境下進(jìn)行的測試,前提條件,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生成證書請求
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"));
}
}
對應(yīng)目錄下可以生成:

其中,ca.crt是自簽名證書文件。ca.key是私鑰。ca.csr只是生成證書的中間請求,是用來指定一些信息,這邊只指定國家為CN。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java.lang.AbstractMethodError: org.apache.xerces.dom.Documen
這篇文章主要介紹了java.lang.AbstractMethodError: org.apache.xerces.dom.DocumentImpl.setXmlVersion問題解決方法,導(dǎo)致本文問題的原因是缺少一個(gè)xerces.jar jar包,需要的朋友可以參考下2015-03-03
Maven導(dǎo)入依賴時(shí)報(bào)錯(cuò)如何解決
這篇文章主要介紹了Maven導(dǎo)入依賴時(shí)報(bào)錯(cuò)如何解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12
Java基礎(chǔ)學(xué)習(xí)之關(guān)鍵字和變量數(shù)據(jù)類型的那些事
變量就是系統(tǒng)為程序分配的一塊內(nèi)存單元,用來存儲各種類型的數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)學(xué)習(xí)之關(guān)鍵字和變量數(shù)據(jù)類型的那些事,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
可視化Swing中JTable控件綁定SQL數(shù)據(jù)源的兩種方法深入解析
以下是對可視化Swing中JTable控件綁定SQL數(shù)據(jù)源的兩種方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考一下2013-07-07
SpringBoot應(yīng)用啟動失敗:端口占用導(dǎo)致Tomcat啟動失敗的問題分析與解決方法
在開發(fā)和運(yùn)維過程中,應(yīng)用程序啟動失敗是我們經(jīng)常遇到的一個(gè)問題,尤其是在 Web 應(yīng)用程序中,涉及到 Web 服務(wù)器的配置時(shí),今天我們將探討一個(gè)常見的啟動錯(cuò)誤,尤其是在使用 Spring Boot 和內(nèi)嵌 Tomcat 服務(wù)器時(shí),需要的朋友可以參考下2024-11-11

