在没有BouncyCastle的情况下在Java中创建X509证书?
2022-08-31 22:42:23
是否可以在不使用Bouncy Castle类的情况下以Java代码理智地创建X509证书?X509V*CertificateGenerator
是否可以在不使用Bouncy Castle类的情况下以Java代码理智地创建X509证书?X509V*CertificateGenerator
是的,但不适用于公开记录的类。我在本文中记录了该过程。
import sun.security.x509.*;
import java.security.cert.*;
import java.security.*;
import java.math.BigInteger;
import java.util.Date;
import java.io.IOException
/**
* Create a self-signed X.509 Certificate
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
*/
X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
throws GeneralSecurityException, IOException
{
PrivateKey privkey = pair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(dn);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
// Update the algorith, and resign.
algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
return cert;
}
编辑2021 - 不幸的是,这种方法在Java 17下不起作用,因为无法访问层次结构。所以它又回到了BouncyCastle或你自己的ASN.1序列化程序。sun.*
对证书进行签名的功能不是标准 Java 库或扩展的一部分。
自己动手所需的许多代码都是核心的一部分。有一些类可以编码和解码X.500名称,X.509证书扩展,各种算法的公钥,当然还有实际执行数字签名的类。
自己实现这一点并非易事,但它绝对是可行的 - 我第一次为证书签名制作工作原型时,可能花了整整4或5天的时间。这对我来说是一个很棒的学习练习,但是当有可用的库免费可用时,很难证明这笔费用是合理的。