使用 Java 中的 Bouncy Castle 自签名 X509 证书

时间:2023-01-16
本文介绍了使用 Java 中的 Bouncy Castle 自签名 X509 证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要使用 Java 中的 Bouncy Castle 创建自签名 X509 证书,但我尝试包含的每个类都已弃用.我该如何解决这个问题?是否还有其他课程要包括在内?谢谢

I need to create a self signed X509 Certificate with Bouncy Castle in Java, but every class I try to include is deprecated. How can I solve this? Is there some other class to include? Thanks

推荐答案

使用Bouncycastle最新版本-1.55 1.66

更新@Bewusstsein 的答案.自此答案(2017 年 5 月 11 日)起,最新版本不推荐使用 bouncycastle 类.如果您使用的是 1.55 或更高版本:

Using Bouncycastle latest version - 1.55 1.66

Update to the answer by @Bewusstsein. The bouncycastle classes are deprecated in the latest version as of this answer (5/11/2017). If you are using version 1.55 or later:

public static Certificate selfSign(KeyPair keyPair, String subjectDN) throws OperatorCreationException, CertificateException, IOException
{
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);

    long now = System.currentTimeMillis();
    Date startDate = new Date(now);

    X500Name dnName = new X500Name(subjectDN);
    BigInteger certSerialNumber = new BigInteger(Long.toString(now)); // <-- Using the current timestamp as the certificate serial number

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    calendar.add(Calendar.YEAR, 1); // <-- 1 Yr validity

    Date endDate = calendar.getTime();

    String signatureAlgorithm = "SHA256WithRSA"; // <-- Use appropriate signature algorithm based on your keyPair algorithm.

    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());

    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic());

    // Extensions --------------------------

    // Basic Constraints
    BasicConstraints basicConstraints = new BasicConstraints(true); // <-- true for CA, false for EndEntity

    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); // Basic Constraints is usually marked as critical.

    // -------------------------------------

    return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}

这篇关于使用 Java 中的 Bouncy Castle 自签名 X509 证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何在Android中对字符串进行哈希处理? 下一篇:SHA1 和 RSA 与 java.security.Signature 对比 MessageDigest 和 Ciph

相关文章

最新文章