Java org.bouncycastle.cert.X509v3CertificateBuilder 代码实例

・34 分钟阅读

以下是展示如何使用org.bouncycastle.cert.X509v3CertificateBuilder的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * 
 * @param intKey
 * @param caKey
 * @param caCert
 * @return
 * @throws Exception
 */
public static X509CertificateHolder buildIntermediateCert(X500Name subject,
                AsymmetricKeyParameter intKey, AsymmetricKeyParameter caKey, 
                X509CertificateHolder caCert) throws Exception
 {
        SubjectPublicKeyInfo intKeyInfo = SubjectPublicKeyInfoFactory.
                        createSubjectPublicKeyInfo(intKey);
        if(subject==null)
                subject = new X500Name("CN = BETaaS Instance CA Certificate");
        X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(
                        caCert.getSubject(),
                        BigInteger.valueOf(1),
              new Date(System.currentTimeMillis()),
       new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
       subject,
       intKeyInfo);
        X509ExtensionUtils extUtils = new X509ExtensionUtils(
                        new SHA1DigestCalculator());
   certBldr.addExtension(Extension.authorityKeyIdentifier, false, 
                extUtils.createAuthorityKeyIdentifier(caCert))
   .addExtension(Extension.subjectKeyIdentifier, false, 
                extUtils.createSubjectKeyIdentifier(intKeyInfo))
   .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
   .addExtension(Extension.keyUsage, true, new 
                KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | 
                                KeyUsage.cRLSign));
   AlgorithmIdentifier sigAlg = algFinder.find(ALG_NAME);
   AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().
                find(sigAlg);
   ContentSigner signer = new BcECDSAContentSignerBuilder(sigAlg, digAlg).
                build(caKey);
   return certBldr.build(signer);
 }
 

实例 2


/**
 * create a basic X509 certificate from the given keys
 */
static X509Certificate makeCertificate(
    KeyPair subKP,
    String  subDN,
    KeyPair issKP,
    String  issDN)
    throws GeneralSecurityException, IOException, OperatorCreationException
{
    PublicKey  subPub  = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey  issPub  = issKP.getPublic();
    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name(issDN), BigInteger.valueOf(serialNo++), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(subDN), subPub);
    v3CertGen.addExtension(
        X509Extension.subjectKeyIdentifier,
        false,
        createSubjectKeyId(subPub));
    v3CertGen.addExtension(
        X509Extension.authorityKeyIdentifier,
        false,
        createAuthorityKeyId(issPub));
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(issPriv)));
}
 

实例 3


public void fillInto(X509v3CertificateBuilder certGen)
        throws CertIOException {
    if (!sans.isEmpty()) {
        ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans
                .size()]);
        certGen.addExtension(Extension.subjectAlternativeName, false,
                new DERSequence(encodables));
    }
}
 

实例 4


/**
 * create a basic X509 certificate from the given keys
 */
static X509Certificate makeCertificate(
    KeyPair subKP,
    String  subDN,
    KeyPair issKP,
    String  issDN)
    throws GeneralSecurityException, IOException, OperatorCreationException
{
    PublicKey  subPub  = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey  issPub  = issKP.getPublic();
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name(issDN), BigInteger.valueOf(serialNo++), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(subDN), subPub);
    v3CertGen.addExtension(
        X509Extension.subjectKeyIdentifier,
        false,
        extUtils.createSubjectKeyIdentifier(subPub));
    v3CertGen.addExtension(
        X509Extension.authorityKeyIdentifier,
        false,
        extUtils.createAuthorityKeyIdentifier(issPub));
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(issPriv)));
}
 

实例 5


static String[] generate(String fqdn, KeyPair keypair, SecureRandom random) throws Exception {
    PrivateKey key = keypair.getPrivate();
    // Prepare the information required for generating an X.509 certificate.
    X500Name owner = new X500Name("CN=" + fqdn);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            owner, new BigInteger(64, random), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic());
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(key);
    X509CertificateHolder certHolder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
    cert.verify(keypair.getPublic());
    return newSelfSignedCertificate(fqdn, key, cert);
}
 

实例 6


/**
 * 
 * @param entityKey - public key of the requesting GW
 * @param caKey
 * @param caCert
 * @return
 * @throws Exception
 */
public static X509CertificateHolder buildEndEntityCert(X500Name subject,
                AsymmetricKeyParameter entityKey, AsymmetricKeyParameter caKey, 
                X509CertificateHolder caCert, String ufn) throws Exception
{
        SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.
                        createSubjectPublicKeyInfo(entityKey);
        if(subject==null)
                subject = new X500Name("CN = BETaaS Gateway Certificate");
        X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(
                        caCert.getSubject(),
       BigInteger.valueOf(1),
       new Date(System.currentTimeMillis()),
       new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
       subject,
       entityKeyInfo);
        X509ExtensionUtils extUtils = new X509ExtensionUtils(
                        new SHA1DigestCalculator());
   certBldr.addExtension(Extension.authorityKeyIdentifier, false, 
                extUtils.createAuthorityKeyIdentifier(caCert))
        .addExtension(Extension.subjectKeyIdentifier, false, 
                        extUtils.createSubjectKeyIdentifier(entityKeyInfo))
     .addExtension(Extension.basicConstraints, true, 
                new BasicConstraints(false))
     .addExtension(Extension.keyUsage, true, new KeyUsage(
                KeyUsage.digitalSignature | KeyUsage.keyEncipherment))
     .addExtension(Extension.subjectAlternativeName, false, new GeneralNames(
                new GeneralName(GeneralName.rfc822Name, ufn)));
   AlgorithmIdentifier sigAlg = algFinder.find(ALG_NAME);
   AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);
   ContentSigner signer = new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(caKey);
   return certBldr.build(signer);
}
 

实例 7


/**
 * Create a new X509 certificate for a given KeyPair
 * @param keyPair the {@link KeyPair} used to create the certificate,
 *       RSAPublicKey and RSAPrivateKey are mandatory on keyPair, IllegalArgumentExeption will be thrown otherwise.
 * @param issuerName The issuer name to be used on the certificate
 * @param ownerName  The owner name to be used on the certificate
 * @param expireDate The expire date
 * @return The {@link X509Certificate}
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 */
public static X509Certificate createX509Certificate(KeyPair keyPair,
        CertificateDetailsInfo certDetails) throws IOException, OperatorCreationException,
        CertificateException
{
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey))
    {
        throw new IllegalArgumentException(
                CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected);
    }
    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
    //Transform the PublicKey into the BouncyCastle expected format
    ASN1InputStream asn1InputStream = null;
    X509Certificate x509Certificate = null;
    try
    {
        asn1InputStream =
                new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded()));
        SubjectPublicKeyInfo pubKey =
                new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject());
        X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle());
        addField(BCStyle.C, certDetails.getCountry(), nameBuilder);
        addField(BCStyle.ST, certDetails.getState(), nameBuilder);
        addField(BCStyle.L, certDetails.getLocality(), nameBuilder);
        addField(BCStyle.O, certDetails.getOrganization(), nameBuilder);
        addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder);
        addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder);
        X500Name subjectName = nameBuilder.build();
        X500Name issuerName = subjectName;
        X509v3CertificateBuilder certBuilder =
                new X509v3CertificateBuilder(issuerName, BigInteger.valueOf(new SecureRandom()
                        .nextInt()), GregorianCalendar.getInstance().getTime(),
                        certDetails.getExpirationDate(), subjectName, pubKey);
        AlgorithmIdentifier sigAlgId =
                new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$
        AlgorithmIdentifier digAlgId =
                new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
        //Create RSAKeyParameters, the private key format expected by Bouncy Castle
        RSAKeyParameters keyParams =
                new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(),
                        rsaPrivateKey.getModulus());
        ContentSigner contentSigner = sigGen.build(keyParams);
        X509CertificateHolder certificateHolder = certBuilder.build(contentSigner);
        //Convert the X509Certificate from BouncyCastle format to the java.security format
        JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter();
        x509Certificate = certConverter.getCertificate(certificateHolder);
    }
    finally
    {
        if (asn1InputStream != null)
        {
            try
            {
                asn1InputStream.close();
            }
            catch (IOException e)
            {
                StudioLogger.error("Could not close stream while creating X509 certificate. "
                        + e.getMessage());
            }
        }
    }
    return x509Certificate;
}
 

实例 8


private static X509CertificateHolder makeV3Certificate(KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
    throws GeneralSecurityException, IOException, OperatorCreationException, CertException
{
    PublicKey subPub  = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey  issPub  = issKP.getPublic();
    X509v3CertificateBuilder v1CertGen = new JcaX509v3CertificateBuilder(
        new X500Name(_issDN),
        BigInteger.valueOf(System.currentTimeMillis()),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        subPub);
    ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(issPriv);
    X509CertificateHolder certHolder = v1CertGen.build(signer);
    ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().setProvider(BC).build(issPub);
    assertTrue(certHolder.isSignatureValid(verifier));
    return certHolder;
}
 

实例 9


public static X509CertificateHolder makeCertificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN, boolean _ca)
    throws IOException, OperatorCreationException
{
    RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic();
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
        new X500Name(_issDN),
        allocateSerialNumber(),
        new Date(System.currentTimeMillis()),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
        new X500Name(_subDN),
        new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent()))
    );
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate());
    v3CertGen.addExtension(
        X509Extension.basicConstraints,
        false,
        new BasicConstraints(_ca));
    return v3CertGen.build(sigGen);
}
 

实例 10


/**
 * Generate a CertificateToken suitable for a TSA
 *
 * @param algorithm
 * @param keyPair
 * @param issuer
 * @param subject
 * @param notBefore
 * @param notAfter
 * @return
 * @throws CertIOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws IOException
 */
public CertificateToken generateTspCertificate(final SignatureAlgorithm algorithm, KeyPair keyPair, X500Name issuer, X500Name subject, final Date notBefore, final Date notAfter)
                throws CertIOException, OperatorCreationException, CertificateException, IOException {
        final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, new BigInteger("" + new Random().nextInt(10) + System.currentTimeMillis()), notBefore,
                        notAfter, subject, keyInfo);
        certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
        final ContentSigner signer = new JcaContentSignerBuilder(algorithm.getJCEId()).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        final X509CertificateHolder holder = certBuilder.build(signer);
        final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(holder.getEncoded()));
        return new CertificateToken(cert);
}
 

实例 11


public CertificateToken generateRootCertificateWithCrl(SignatureAlgorithm algorithm, X500Name subject, X500Name issuer, PrivateKey issuerPrivateKey, PublicKey publicKey, Date notBefore,
                Date notAfter) throws Exception {
        // generate certificate
        final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, new BigInteger("" + new Random().nextInt(10) + System.currentTimeMillis()), notBefore,
                        notAfter, subject, keyInfo);
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
        // Sign the new certificate with the private key of the trusted third
        final ContentSigner signer = new JcaContentSignerBuilder(algorithm.getJCEId()).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerPrivateKey);
        final X509CertificateHolder holder = certBuilder.build(signer);
        final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(holder.getEncoded()));
        return new CertificateToken(cert);
}
 

实例 12


/**
 * Generates version 3 {@link java.security.cert.X509Certificate}.
 *
 * @param keyPair the key pair
 * @param caPrivateKey the CA private key
 * @param caCert the CA certificate
 * @param subject the subject name
 * 
 * @return the x509 certificate
 * 
 * @throws Exception the exception
 */
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert,
        String subject) throws Exception {
    try {
        X500Name subjectDN = new X500Name("CN=" + subject);
        // Serial Number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));
        // Validity
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);
        // SubjectPublicKeyInfo
        SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic()
                .getEncoded()));
        X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()),
                serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo);
        DigestCalculator digCalc = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
        // Subject Key Identifier
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));
        // Authority Key Identifier
        certGen.addExtension(Extension.authorityKeyIdentifier, false,
                x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));
        // Key Usage
        certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign
                | KeyUsage.cRLSign));
        // Extended Key Usage
        KeyPurposeId[] EKU = new KeyPurposeId[2];
        EKU[0] = KeyPurposeId.id_kp_emailProtection;
        EKU[1] = KeyPurposeId.id_kp_serverAuth;
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));
        // Basic Constraints
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
        // Content Signer
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey);
        // Certificate
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v3Certificate.", e);
    }
}
 

实例 13


/**
 * Create a server certificate for the given domain and subject alternative names, signed by the given Certificate Authority.
 */
public X509Certificate createClientCert(PublicKey publicKey, X509Certificate certificateAuthorityCert, PrivateKey certificateAuthorityPrivateKey, PublicKey certificateAuthorityPublicKey, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {
    //
    // signers name
    //
    X500Name issuer = new X509CertificateHolder(certificateAuthorityCert.getEncoded()).getSubject();
    //
    // subjects name - the same as we are self signed.
    //
    X500Name subject = new X500Name("CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK");
    //
    // serial
    //
    BigInteger serial = BigInteger.valueOf(new Random().nextInt());
    //
    // create the certificate - version 3
    //
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, publicKey);
    builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    //
    // subject alternative name
    //
    List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
    if (subjectAlternativeNameDomains != null) {
        subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, domain));
        for (String subjectAlternativeNameDomain : subjectAlternativeNameDomains) {
            subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, subjectAlternativeNameDomain));
        }
    }
    if (subjectAlternativeNameIps != null) {
        for (String subjectAlternativeNameIp : subjectAlternativeNameIps) {
            if (IPAddress.isValidIPv6WithNetmask(subjectAlternativeNameIp)
                    || IPAddress.isValidIPv6(subjectAlternativeNameIp)
                    || IPAddress.isValidIPv4WithNetmask(subjectAlternativeNameIp)
                    || IPAddress.isValidIPv4(subjectAlternativeNameIp)) {
                subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, subjectAlternativeNameIp));
            }
        }
    }
    if (subjectAlternativeNames.size() > 0) {
        DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
        builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);
    }
    X509Certificate cert = signCertificate(builder, certificateAuthorityPrivateKey);
    cert.checkValidity(new Date());
    cert.verify(certificateAuthorityPublicKey);
    return cert;
}
 

实例 14


public X509CertificateHolder generate(String cn, String[] sans) {
        try {
                /* basic certificate structure */
                //serial = serial.add(BigInteger.ONE);
                // TODO: temporary workaround as reusing serial numbers makes Firefox complain
                serial = new BigInteger(Long.toString(System.currentTimeMillis()));
                Calendar notBefore = new GregorianCalendar(UTC);
                notBefore.add(Calendar.HOUR, -1);
                Calendar notAfter = new GregorianCalendar(UTC);
                notAfter.add(Calendar.HOUR, 24);
                X500Name subject = new X500NameBuilder().addRDN(BCStyle.CN, cn).build();
                BcX509ExtensionUtils utils = new BcX509ExtensionUtils();
                X509v3CertificateBuilder builder = new BcX509v3CertificateBuilder(ca.getCertificate(), serial, notBefore.getTime(), notAfter.getTime(), subject, keyPair.getPublic());
                /* subjectAlernativeName extension */
                if (sans.length > 0) {
                        GeneralName[] names = new GeneralName[sans.length];
                        for (int i = 0; i < names.length; i++) {
                                names[i] = new GeneralName(GeneralName.dNSName, sans[i]);
                        }
                        builder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(names));
                }
                /* basicConstraints extension */
                builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
                /* subjectKeyIdentifier extension */
                builder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(keyPair.getPublic()));
                /* authorityKeyIdentifier extension */
                builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(ca.getPublicKey()));
                /* keyUsage extension */
                int usage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyAgreement;
                builder.addExtension(Extension.keyUsage, true, new KeyUsage(usage));
                /* extendedKeyUsage extension */
                KeyPurposeId[] usages = { KeyPurposeId.id_kp_serverAuth };
                builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(usages));
                /* create the signer */
                AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
                AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithm);
                ContentSigner signer = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm).build(ca.getPrivateKey());
                /* build and sign the certificate */
                return builder.build(signer);
        } catch (IOException | OperatorCreationException ex) {
                throw new CertificateGenerationException(ex);
        }
}
 

实例 15


@Override
public KeyStore createCertForHost(String hostname) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
        if (hostname == null) {
                throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!");
        }
        if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
                throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
        }
       final KeyPair mykp = this.createKeyPair();
       final PrivateKey privKey = mykp.getPrivate();
       final PublicKey pubKey = mykp.getPublic();
        X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); 
        namebld.addRDN(BCStyle.CN, hostname);
        namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
        namebld.addRDN(BCStyle.O, "OWASP");
        namebld.addRDN(BCStyle.C, "xx");
        namebld.addRDN(BCStyle.EmailAddress, "[email protected]");
        X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder (
                        new X509CertificateHolder(caCert.getEncoded()).getSubject(),
                        BigInteger.valueOf(serial.getAndIncrement()),
                        new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
                        new Date(System.currentTimeMillis() + 100*(1000L * 60 * 60 * 24 * 30)),
                        namebld.build(),
                        pubKey
                );
        certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
        ContentSigner sigGen;
        try {
                sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
        } catch (OperatorCreationException e) {
                throw new CertificateException(e);
        }
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
       cert.checkValidity(new Date());
       cert.verify(caPubKey);
       final KeyStore ks = KeyStore.getInstance("JKS");
       ks.load(null, null);
       final Certificate[] chain = new Certificate[2];
       chain[1] = this.caCert;
       chain[0] = cert;
       ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
       return ks;
   }
 
讨论
淘淘あ西西 profile image