原创

使用 Bouncy Castle 的 bcpkix-jdk15on 进行证书生成和验证

Bouncy Castle 是一个广泛使用的开源加密库,支持多种加密算法和协议。bcpkix-jdk15on 是其专注于 PKIX 操作的模块,适用于 Java 15 及以上版本。本文将介绍如何使用该库生成和验证 X.509 证书。

准备工作

首先,确保你已经在项目中添加了 Bouncy Castle 的依赖。对于 Maven 项目,可以在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpkix-jdk15on</artifactId>
    <version>1.70</version>
</dependency>

生成自签名证书

下面的代码示例展示了如何生成一个自签名的 X.509 证书:

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;

import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;

public class CertificateGenerator {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws Exception {
        X500Name issuer = new X500Name("CN=Test Certificate");
        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
        Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24);
        Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 365);

        JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                issuer, serial, notBefore, notAfter, issuer, keyPair.getPublic());

        ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .setProvider("BC").build(keyPair.getPrivate());

        X509CertificateHolder certHolder = certBuilder.build(signer);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
    }

    public static void main(String[] args) {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            X509Certificate certificate = generateSelfSignedCertificate(keyPair);
            System.out.println("Generated Certificate: " + certificate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

验证证书

生成的证书可以通过以下代码进行验证:

import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.io.ByteArrayInputStream;

public class CertificateVerifier {

    public static boolean verifyCertificate(X509Certificate certificate) {
        try {
            certificate.checkValidity();
            certificate.verify(certificate.getPublicKey());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // 假设我们已经生成了一个证书
            X509Certificate certificate = CertificateGenerator.generateSelfSignedCertificate(
                    KeyPairGenerator.getInstance("RSA").generateKeyPair());

            boolean isValid = verifyCertificate(certificate);
            System.out.println("Certificate is valid: " + isValid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

总结

通过以上代码示例,我们可以看到如何使用 Bouncy Castle 的 bcpkix-jdk15on 库生成和验证 X.509 证书。这只是该库功能的一小部分,Bouncy Castle 还支持许多其他加密操作,如加密、解密、签名和验证等。希望这篇文章对你有所帮助!

正文到此结束
Loading...