become who you want to|

张三Blog

园龄:3年4个月粉丝:3关注:0

使用Java编写生成证书可以通过SSL证书请求检测 带公钥秘钥还在解析JDK官方文档缺少备注

这里使用的Java原生的security和bouncycastle 这几个包
1.Maven坐标

		 <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcmail-jdk16 -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcmail-jdk16</artifactId>
            <version>1.46</version>
        </dependency>
    

> 注意这里千万要注意版本问题 这两个jar版本一定要统一 否则会出现很多莫名其妙的错误


2.直接上工具类 CSRUtils.class

package com.xinchacha.security.utils;

import java.io.*;
import java.security.*;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import sun.security.pkcs10.PKCS10;
import sun.security.rsa.RSAPrivateCrtKeyImpl;
import sun.security.x509.X500Name;



/**
 * @ClassName CSRUtils
 * @Description TODO
 * @Author XuWenXiao
 * @Date 2020/5/13 10:00
 * @Version 1.0
 **/
public class CSRUtils {
    public KeyPair kp = null;
    private static final String SHA_256WITHRSA="SHA256withRSA";
    private static final String ENCRYPTION_RSA="RSA";
    private static final Integer KEY_SIZE2048=2048;
    private static final Integer KEY_SIZE4096=4096;
    private static final String DV_SSL = "^([A-Z]|[a-z]|[0-9]|[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()――+|{}【】‘;:”“'。,、?]){6,20}$";
    /**
     * TODO 根据相关信息生成证书签发请求
     *
     * @param alg 加密算法 <p>这里使用SHA256withRSA(SHA256)</p>
     * @param size 密钥长度
     * @param commonName_oid 域名CN 验证非法域名
     * @param orgUnitName_oid  部门/单位
     * @param orgName_oid 公司/组织
     * @param localityName_oid 国家/地区
     * @param stateName_oid 省份
     * @param countryName_oid 城市
     * @return String <p>返回证书签名请求字符串</p>
     * @Author xuwenxiao
     */
    public String generateCSR(String alg,int size,String commonName_oid,String orgUnitName_oid,String orgName_oid,String localityName_oid,String stateName_oid,String countryName_oid) {
        Security.addProvider(new BouncyCastleProvider());
        String strCSR = "";
        String sigAlg;
        try {
            if (alg == null || alg.length() <= 0) {
                sigAlg = SHA_256WITHRSA;
            } else {
                sigAlg = alg;
                int algSize = KEY_SIZE2048;
                if (size != 0) {
                    algSize = size;
                }
                /** 加密算法 **/
                KeyPairGenerator kpg = KeyPairGenerator.getInstance(ENCRYPTION_RSA);
                /** 指定密钥长度 **/
                kpg.initialize(algSize, new SecureRandom());
                kp = kpg.generateKeyPair();
                PublicKey publicKey = kp.getPublic();
                String s = encodePublicKey(publicKey);
                System.out.println("公钥"+s);
                PrivateKey privateKey = kp.getPrivate();
                RSAPrivateCrtKeyImpl rsaPrivateCrtKey= (RSAPrivateCrtKeyImpl) privateKey;
                System.out.println(rsaPrivateCrtKey.toString());

				//这里要注意 因为秘钥还在研究中 所以需要进行再次开发
                /**getPrivateExponent**/
                System.out.println(rsaPrivateCrtKey.getPrivateExponent().toString());
                /**getCrtCoefficient**/
                System.out.println(rsaPrivateCrtKey.getCrtCoefficient().toString());
                /**getModulus**/
                System.out.println(rsaPrivateCrtKey.getModulus().toString());
                /**getPrimeExponentP**/
                System.out.println(rsaPrivateCrtKey.getPrimeExponentP().toString());
                /**getPrimeExponentQ**/
                System.out.println(rsaPrivateCrtKey.getPrimeExponentQ().toString());
                /**getPrimeP**/
                System.out.println(rsaPrivateCrtKey.getPrimeP().toString());
                /**getPrimeQ**/
                System.out.println(rsaPrivateCrtKey.getPrimeQ().toString());
                /**getPublicExponent**/
                System.out.println(rsaPrivateCrtKey.getPublicExponent().toString());
//                System.out.println(rsaPrivateCrtKey.getCrtCoefficient()+
//                rsaPrivateCrtKey.getModulus()+
//                rsaPrivateCrtKey.getPrimeExponentP()+
//                rsaPrivateCrtKey.getPrimeExponentQ()+
//                rsaPrivateCrtKey.getPrimeP()+
//                rsaPrivateCrtKey.getPrimeQ()+
//                rsaPrivateCrtKey.getPrivateExponent()+
//                rsaPrivateCrtKey.getPublicExponent());
//                String s1 = encoded.toString();
//                System.out.println("私钥"+s1);
                PKCS10 pkcs10 = new PKCS10(publicKey);
                Signature signature = Signature.getInstance(sigAlg);
                signature.initSign(privateKey);
                /**设置域名**/
                if (!commonName_oid.matches(DV_SSL)){
                    throw new RuntimeException("请检查您输入的域名是否合法核对后重新输入");
                }

                String commonName = whetherNull(commonName_oid);
                /**设置组织机构**/
                String orgUnitName = whetherNull(orgUnitName_oid);
                /**设置部门单位**/
                String orgName=whetherNull(orgName_oid);
                /**设置国家地区**/
                String localityName=whetherNull(localityName_oid);
                /**设置省份信息**/
                String stateName=whetherNull(stateName_oid);
                /**设置城市信息**/
                String countryName=whetherNull(countryName_oid);
                X500Name x500Name = new X500Name(commonName,orgUnitName,orgName,localityName,stateName,countryName);
                pkcs10.encodeAndSign(x500Name, signature);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(baos);
                pkcs10.print(ps);
                String strPEMCSR = baos.toString();
                /** 对生成CSR密钥进行替换 将begin 和 end 的内容去除**/
                strCSR = strPEMCSR.replaceAll("\r|\n", "");
                //strCSR = strCSR.replaceAll("-----BEGIN NEW CERTIFICATE REQUEST-----", "");
                //strCSR = strCSR.replaceAll("-----END NEW CERTIFICATE REQUEST-----", "");
                return strCSR;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return strCSR;
    }
    public static String encodePublicKey(PublicKey publicKey) {
        return StringUtils.newStringUtf8(Base64.encode(publicKey.getEncoded()));
    }
    /**
     * 验证非空
     * @param ar
     */
    public String whetherNull(String ar){
        String whether="";
        if (!org.apache.commons.lang3.StringUtils.isBlank(ar)){
            whether=ar;
        }else{
            whether="";
        }
        return whether;
    }

3.Main函数调用 查看结果 请求参数在工具类中已经标明 可以参考

 CSRUtils csrUtils= new CSRUtils();
        String s = csrUtils.generateCSR("SHA256withRSA", 2048, "www.zhangsan.com", "百度", "张三", "中国", "北京", "昌平");
        System.out.println(s);

本文作者:张三Blog

本文链接:https://www.cnblogs.com/zhangsan-plus/p/16503329.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   张三Blog  阅读(56)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起