zoukankan      html  css  js  c++  java
  • java通过command调用openssl生成私钥和证书

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

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

    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"));
        }
    }

    对应目录下可以生成:

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

  • 相关阅读:
    Linux查看SSL证书是否过期
    docker安装Elasticsearch:7.6.0启动失败,ERROR: [1] bootstrap checks failed
    patroni启动,提示waiting for leader to bootstrap
    pg_buffercache
    使用oid2name列出数据库和对应的oid
    Centos7下安装ORACLE 11g,弹窗不显示
    CentOS 7.5 安装Oracle 11gR2 86%报错:Error in invoking target 'agent nmhs' of makefile
    pg中与超时设置有关的参数
    JDBC驱动程序注册 JDBC简介(二)
    JDBC设计理念浅析 JDBC简介(一)
  • 原文地址:https://www.cnblogs.com/chenmz1995/p/13401450.html
Copyright © 2011-2022 走看看