是否可以在不使用 Bouncy Castle X509V*CertificateGenerator
类的情况下在 Java 代码中明智地创建 X509 证书?
原文由 Yuliy 发布,翻译遵循 CC BY-SA 4.0 许可协议
是否可以在不使用 Bouncy Castle X509V*CertificateGenerator
类的情况下在 Java 代码中明智地创建 X509 证书?
原文由 Yuliy 发布,翻译遵循 CC BY-SA 4.0 许可协议
是的,但不是公开记录的课程。我已 在本文中 记录了该过程。
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 下不起作用,因为无法访问 sun.*
层次结构。所以它又回到了 BouncyCastle 或你自己的 ASN.1 序列化程序。
原文由 Mike B 发布,翻译遵循 CC BY-SA 4.0 许可协议
15 回答8.2k 阅读
8 回答5.9k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
1 回答2.2k 阅读✓ 已解决
签署证书的能力不是标准 Java 库或扩展的一部分。
很多需要自己做的代码都是核心的一部分。有一些类可以编码和解码 X.500 名称、X.509 证书扩展、各种算法的公钥,当然还有用于实际执行数字签名的类。
自己实现这个并不简单,但绝对可行——我第一次制作证书签名的工作原型时可能花了整整 4 到 5 天。这对我来说是一个 很棒 的学习练习,但是当有可用的免费图书馆可用时,很难证明这笔费用是合理的。