【问题标题】:Creating an X509 Certificate in Java without BouncyCastle?在没有 BouncyCastle 的情况下用 Java 创建 X509 证书?
【发布时间】:2010-12-09 14:35:50
【问题描述】:

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

【问题讨论】:

    标签: java x509certificate jce


    【解决方案1】:

    是的,但不是公开记录的课程。我已经记录了这个过程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;
    }   
    

    【讨论】:

    • 一个非常好的提示。使我免于导入可怕的(和心爱的)Bouncycastle 库。膨胀开始了!
    • 有没有不涉及调用 sun.security.x509.* 的方法?鉴于它实际上不是您应该使用的东西。
    • 优秀。为我节省了很多工作。代码很好很干净。我正在编辑代码以确保它不会在博客关闭时消失。
    • 对于 JDK 8,这应该是: info.set(X509CertInfo.SUBJECT, owner); info.set(X509CertInfo.ISSUER, 所有者);
    • @AxelFontaine 提到的更改在此处描述bugs.openjdk.java.net/browse/JDK-7198416
    【解决方案2】:

    签署证书的能力不是标准 Java 库或扩展的一部分。

    很多需要自己做的代码是核心的一部分。有一些类可以编码和解码 X.500 名称、X.509 证书扩展、各种算法的公钥,当然还有实际执行数字签名的类。

    自己实现这一点并非易事,但这绝对是可行的——我第一次制作证书签名的工作原型时可能花了 4 到 5 天。这对我来说是一个很棒的学习练习,但是当有免费可用的可用库时,很难证明这笔费用是合理的。

    【讨论】:

    • 截至 2017 年,这仍然准确吗?
    • 不,截断的代码使用过时的加密技术(Javadoc 中的 MD5withRSA 或 SHA1withRSA)来签署证书。相反,我建议使用 SHA256withRSA、SHA384withRSA、SHA512withRSA 或 SHA256withECDSA、SHA384withECDSA 和 SHA512withECDSA,具体取决于您设计的安全级别。
    • @DanielGartmann 不清楚您在说什么“代码被剪断”。您的“否”是对之前评论者的回复吗?
    • @erickson 是的,我显然在回答 user674669 的问题。我所说的“code sn-p”是指下面前2个答案中显示的代码(在包含源代码的灰色区域中)。
    • @DanielGartmann 评论者问我的答案在 2017 年是否仍然正确。我认为是;您不能开箱即用地签署证书,您必须自己构建它。所以,如果你说那是错误的,你能解释为什么吗?但是您的第二条评论听起来更像是您在说其他答案在应用所提供的 API 的方式上是错误的(我同意这一点)。
    【解决方案3】:
    import sun.security.x509.*;
    
    import java.security.cert.*;
    import java.security.*;
    import java.math.BigInteger;
    import java.security.cert.Certificate;
    import java.util.Date;
    import java.io.IOException;
    
    public class Example {
        /**
         * Create a self-signed X.509 Example
         *
         * @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 Example is valid for
         * @param algorithm the signing algorithm, eg "SHA1withRSA"
         */
        public 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, owner);
            info.set(X509CertInfo.ISSUER, 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;
        }
    
        public static void main (String[] argv) throws Exception {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            Example example = new Example();
            String distinguishedName = "CN=Test, L=London, C=GB";
            Certificate certificate = example.generateCertificateOriginal(distinguishedName, keyPair, 365, "SHA256withRSA");
            System.out.println("it worked!");
        }
    }
    

    我喜欢 vbence 的回答,但我不断收到以下异常:

    java.security.cert.CertificateException:主题类类型无效。

    经过多次尝试找出 是一个有效的主题类后,我发现 X509CerInfo 想要一个 X500Name 的实例。

    1 info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    2 info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    3 info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    4 info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
    

    所以需要将第 2 行和第 3 行更改为

    2 info.set(X509CertInfo.SUBJECT, owner);
    3 info.set(X509CertInfo.ISSUER, owner);
    

    【讨论】:

      【解决方案4】:

      JRE 中提供了制作自签名证书的所有基本组件(签名、X509 编码等)。与 BC 不同,Sun 的 JCE 不提供任何公开调用来签署证书。但是,所有功能都在 Keytool 中可用。您可以简单地从 keytool 复制代码来执行此操作。你需要复制的方法是doSelfCert()

      【讨论】:

      • 不幸的是,Keytool 为此使用了sun.* 类。所以这不适用于每个 JRE。但是这里是source code
      【解决方案5】:

      取决于您到底想做什么(可能还有您对“Sanely”的定义)。正如ZZ Coder所指出的,您可以通过复制keytool直接创建自签名证书。但我不相信您可以使用标准 JCE 创建 PKCS10 证书请求对象,如果您想创建标准 CA 签名的 EEC,您可能需要这样做。

      【讨论】:

      • 嗯,为什么不呢? Keytool 可以将自签名转换为 csr,您只需复制该代码即可。
      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多