Java如何基于command调用openssl生成私钥证书

2025-05-29 0 104

在windows环境下进行的测试,前提条件,windows上需要先安装openssl。

配置环境变量,查看版本:

Java如何基于command调用openssl生成私钥证书

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45
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(); //系统属性

System.out.println("用户的当前工作目录:"+props.getProperty("user.dir"));

}

}

对应目录下可以生成:

Java如何基于command调用openssl生成私钥证书

其中,ca.crt是自签名证书文件。ca.key是私钥。ca.csr只是生成证书的中间请求,是用来指定一些信息,这边只指定国家为CN。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/chenmz1995/p/13401450.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java如何基于command调用openssl生成私钥证书 https://www.kuaiidc.com/118791.html

相关文章

猜你喜欢
发表评论
暂无评论