java - 在没有 BouncyCaSTLe 的情况下用 Java 创建 X509 证书?

标签 java x509certificate jce

是否可以在不使用 Bouncy CaSTLe X509V*CertificateGenerator 类的情况下用 Java 代码创建 X509 证书?

最佳答案

是的,但不是公开记录的类(class)。我已经记录了该过程 in this article .

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;
}   

Edit 2021 - 不幸的是,这种方法在 Java 17 下不起作用,因为无法访问 sun.* 层次结构。所以它回到了 BouncyCaSTLe 或滚动你自己的 ASN.1 序列化程序。

关于java - 在没有 BouncyCaSTLe 的情况下用 Java 创建 X509 证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1615871/

相关文章:

java - 绑定(bind)情况复杂

java - 无法以 PEM 文件格式写入使用 org.bouncycaSTLe.asn1.pkcs.CertificationRequest 生成的 CSR

java - 用于 java 的 AES CS2Padding

java - 如何使用 JCA/JCE 和 HSM 派生 key

java - 如何签署自定义 JCE 安全提供程序

java - 为什么这会根据变量的最终结果给出不同的结果

java - 读取 txt 文件并操作 readLine 字符串

java - Android - 来自服务器的 JSON 为空

wcf - C# WCF 客户端错误 "The private key is not present in the X.509 certificate"

c - 如何在 C 中验证 X509 证书