Bootstrap

证书学习(五)Java实现RSA、SM2证书颁发

一、知识回顾

1.1 X.509 证书

我们在之前的文章中介绍过,X.509证书 是一种遵循 X.509(RFC 5280) 的数字证书,是目前 世界上使用最广泛 的数字证书类型,用于验证网络通信中的实体身份。

1.2 X509Certificate 类

在 Java 中,X.509证书 通常使用 java.security.cert.X509Certificate 类表示。该类是 JCA(Java Cryptography Architecture) 的一部分,提供了一些 用于处理数字证书 的方法。

补充: JCA(Java Cryptography Architecture)是平台的重要组成部分,它包含了一个 provider 架构和一系列 API,用途如下所示:

  • 数字签名(digital signatures)、消息摘要(hashes)、证书(certificates )及其 验证( certificate validation)、加密(对称/非对称块/流密码)encryption (symmetric/asymmetric block/stream ciphers)、密钥生成与管理(key generation and management)以及 安全随机数生成(secure random number generation)等。

下面我们就来介绍一下如何用Java实现 RSA 证书的颁发。


二、代码实现

2.1 Maven 依赖

Java 实现证书颁发主要依赖于 Bouncy Castle 的 bcprov-jdk15onbcpkix-jdk15on 两个核心库。

这两个库分别用于不同的功能:

  1. bcprov-jdk15on:
    • 用途: 这个库包含了基本的密码学算法实现,如:对称加密算法(AES、DES等)、非对称加密算法(RSA、ECC)、哈希函数(SHA-256、SHA-512等)、消息摘要算法等。
    • 依赖: 基础库,不依赖于其他库。
  2. bcpkix-jdk15on:
    • 用途: 这个库提供了 X.509 证书和 CMS(Cyptographic Message Syntax)的支持,主要用于证书管理,包括证书的生成、验证、导入导出等操作;同时支持 CMS 格式的封装和解封装,用于加密和签名的消息。
    • 依赖: 依赖于 bcprov-jdk15on,因为证书处理和消息封装需要用到基本的密码学算法。
<!-- Bouncy Castle库 -->
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.70</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpkix-jdk15on</artifactId>
    <version>1.70</version>
</dependency>

补充:

在这里插入图片描述


2.2 RSA 证书颁发

1)PfxGenerateUtil 证书文件生成工具类

PfxGenerateUtil.java

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Random;

/**
 * .pfx/.p12 证书文件生成工具类
 */
@Component
public class PfxGenerateUtil {
   

    private static final Logger LOGGER = LoggerFactory.getLogger(PfxGenerateUtil.class);

    private static final String KEY_STORE_TYPE = "PKCS12";
    private static final String ALGORITHM_TYPE = "RSA";
    private static final int KEY_SIZE = 2048;
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";

    static {
   
        // 系统添加BC加密算法
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 创建个人证书
     */
    public static X509Certificate createPersonPfx(String certPath, String password, String account) throws Exception {
   
        Date notBefore = new Date();
        Date notAfter = DateUtils.addYears(notBefore, 1);
        return createPfx(certPath, password, notBefore, notAfter, account, null);
    }

    /**
     * 创建企业证书
     */
    public static X509Certificate createOrgPfx(String certPath, String password, String account, String orgCode) throws Exception {
   
        Date notBefore = new Date();
        Date notAfter = DateUtils.addYears(notBefore, 1);
        return createPfx(certPath, password, notBefore, notAfter, account, orgCode);
    }

    /**
     * 创建证书
     */
    private static X509Certificate createPfx(String certPath, String password, Date notBefore, Date notAfter, String account, String orgCode) throws Exception {
   
        LOGGER.debug("The cert path is: " + certPath);
        //如果目录不存在创建目录
        File certFilePath = FileUtils.getFile(certPath);
        FileUtils.forceMkdir(certFilePath.getParentFile());
        // 设置颁发者和主题
        // CN (Common Name名字与姓氏)
        // OU (Organization Unit组织单位名称)
        // O(Organization组织名称)
        // L(Locality城市或区域名称)
        // ST(State州或省份名称)
        // C(Country国家名称)
        String issuerString;
        String subjectString;
        if(orgCode == null || "".equals(orgCode.trim())) {
   
            subjectString = "C=CN,CN=" + account;
            issuerString = "C=CN,CN=www.bo.cn CA Individual";
        } else {
   
            subjectString = "C=C,CN=" +
;