當前位置: 首頁>>代碼示例>>Java>>正文


Java X509v3CertificateBuilder.addExtension方法代碼示例

本文整理匯總了Java中org.bouncycastle.cert.X509v3CertificateBuilder.addExtension方法的典型用法代碼示例。如果您正苦於以下問題:Java X509v3CertificateBuilder.addExtension方法的具體用法?Java X509v3CertificateBuilder.addExtension怎麽用?Java X509v3CertificateBuilder.addExtension使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.bouncycastle.cert.X509v3CertificateBuilder的用法示例。


在下文中一共展示了X509v3CertificateBuilder.addExtension方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: generate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
public X509Certificate generate(String dn, KeyPair keyPair) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);

        if (subjectAltName != null)
            v3CertGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
        X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
 
開發者ID:YMCoding,項目名稱:kafka-0.11.0.0-src-with-comment,代碼行數:25,代碼來源:TestSslUtils.java

示例2: addExtensions

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
private static void addExtensions(X509v3CertificateBuilder certBuilder,
        IdentifiedX509Certprofile profile, X500Name requestedSubject, X500Name grantedSubject,
        Extensions extensions, SubjectPublicKeyInfo requestedPublicKeyInfo,
        PublicCaInfo publicCaInfo, Date notBefore, Date notAfter)
        throws CertprofileException, IOException, BadCertTemplateException {
    ExtensionValues extensionTuples = profile.getExtensions(requestedSubject, grantedSubject,
            extensions, requestedPublicKeyInfo, publicCaInfo, null, notBefore, notAfter);
    if (extensionTuples == null) {
        return;
    }

    for (ASN1ObjectIdentifier extType : extensionTuples.extensionTypes()) {
        ExtensionValue extValue = extensionTuples.getExtensionValue(extType);
        certBuilder.addExtension(extType, extValue.isCritical(), extValue.value());
    }
}
 
開發者ID:xipki,項目名稱:xipki,代碼行數:17,代碼來源:X509SelfSignedCertBuilder.java

示例3: generateServerCertificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
public static X500PrivateCredential generateServerCertificate(KeyPair caKeyPair) throws NoSuchAlgorithmException, CertificateException, OperatorCreationException, CertIOException {
    X500Name issuerName = new X500Name("CN=bouncrca");
    X500Name subjectName = new X500Name("CN=bouncr");
    BigInteger serial = BigInteger.valueOf(2);
    long t1 = System.currentTimeMillis();
    KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
    rsa.initialize(2048, SecureRandom.getInstance("NativePRNGNonBlocking"));
    KeyPair kp = rsa.generateKeyPair();
    System.out.println(System.currentTimeMillis() - t1);

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, kp.getPublic());
    DERSequence subjectAlternativeNames = new DERSequence(new ASN1Encodable[] {
            new GeneralName(GeneralName.dNSName, "localhost"),
            new GeneralName(GeneralName.dNSName, "127.0.0.1")
    });
    builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames);
    X509Certificate cert = signCertificate(builder, caKeyPair.getPrivate());

    return new X500PrivateCredential(cert, kp.getPrivate());
}
 
開發者ID:kawasima,項目名稱:bouncr,代碼行數:21,代碼來源:Certificate.java

示例4: makeCertificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
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);
}
 
開發者ID:ttt43ttt,項目名稱:gwt-crypto,代碼行數:27,代碼來源:CMSTestUtil.java

示例5: createCertificateBuilder

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException {
    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY));
    nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY));
    nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY));
    nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY));
    X500Name x500Name = nameBuilder.build();

    BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG());

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());

    Date startDate = new Date();
    Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS));

    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo);

    String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY);
    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName));
    return certificateBuilder;
}
 
開發者ID:republique-et-canton-de-geneve,項目名稱:chvote-1-0,代碼行數:22,代碼來源:KeyGenerator.java

示例6: generateCertificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
public static X509Certificate generateCertificate(Credential credential, String entityId) throws Exception {
    X500Name issuer = new X500Name("o=keymanager, ou=oiosaml-sp");
    BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
    Date notBefore = new Date();
    Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60L * 60L * 24L * 365L * 10L);
    X500Name subject = new X500Name("cn=" + entityId + ", ou=oiosaml-sp");

    ByteArrayInputStream bIn = new ByteArrayInputStream(credential.getPublicKey().getEncoded());
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream(bIn).readObject());

    X509v3CertificateBuilder gen = new X509v3CertificateBuilder(issuer, serialNumber, notBefore, notAfter, subject, publicKeyInfo);

	gen.addExtension(X509Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(credential.getPublicKey()));
	gen.addExtension(X509Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(credential.getPublicKey()));

    ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(credential.getPrivateKey());
    X509CertificateHolder certificateHolder = gen.build(sigGen);

    X509Certificate x509Certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
	return x509Certificate;
}
 
開發者ID:amagdenko,項目名稱:oiosaml.java,代碼行數:22,代碼來源:SecurityHelper.java

示例7: generateTspCertificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
/**
 * Generate a CertificateToken suitable for a TSA
 *
 * @param algorithm
 * @param keyPair
 * @param issuer
 * @param subject
 * @param notBefore
 * @param notAfter
 * @return
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws IOException
 */
private CertificateToken generateTspCertificate(final SignatureAlgorithm algorithm, KeyPair keyPair, X500Name issuer, X500Name subject,
		final Date notBefore, final Date notAfter) throws 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);
}
 
開發者ID:esig,項目名稱:dss,代碼行數:33,代碼來源:CertificateService.java

示例8: generateRootCertificateWithCrl

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
private 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);
}
 
開發者ID:esig,項目名稱:dss,代碼行數:21,代碼來源:CertificateService.java

示例9: generateRootCertificateWithoutCrl

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
private CertificateToken generateRootCertificateWithoutCrl(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));

	// 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);
}
 
開發者ID:esig,項目名稱:dss,代碼行數:21,代碼來源:CertificateService.java

示例10: makeCertificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
/**
 * 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)));
}
 
開發者ID:mkl-public,項目名稱:testarea-itext5,代碼行數:29,代碼來源:RsaSsaPss.java

示例11: setInhabitAnyPolicyExtension

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
static void setInhabitAnyPolicyExtension(X509v3CertificateBuilder certificateBuilder,
                                         Boolean isCritical, boolean inhabitAnyPolicy, String skipCerts)
        throws IOException {
    if (inhabitAnyPolicy) {
        ASN1Integer skipCertsInteger = new ASN1Integer(new BigInteger(skipCerts));
        certificateBuilder.addExtension(Extension.inhibitAnyPolicy, isCritical, skipCertsInteger);
    }
}
 
開發者ID:stevanmilic,項目名稱:X509-certificate-manager,代碼行數:9,代碼來源:CertificateHelper.java

示例12: setCertificatePoliciesExtension

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
static void setCertificatePoliciesExtension(X509v3CertificateBuilder certificateBuilder, boolean isCritical,
                                            boolean anyPolicy, String cpsURI) throws IOException {
    if (anyPolicy) {
        PolicyQualifierInfo policyQualifierInfo = new PolicyQualifierInfo(cpsURI);
        PolicyInformation policyInformation = new PolicyInformation(PolicyQualifierId.id_qt_cps,
                new DERSequence(policyQualifierInfo));
        CertificatePolicies certificatePolicies = new CertificatePolicies(policyInformation);
        certificateBuilder.addExtension(Extension.certificatePolicies, isCritical, certificatePolicies);
    }
}
 
開發者ID:stevanmilic,項目名稱:X509-certificate-manager,代碼行數:11,代碼來源:CertificateHelper.java

示例13: addSignedCertificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
public void addSignedCertificate(final XTFKeyStore signerKeyStore, final String signerAlias, final String signerPassword, final String dn, final String certificateAlias, final String password) {
	try {
		final X509Certificate caCert = (X509Certificate) signerKeyStore.keystore.getCertificate(signerAlias);
		final PrivateKey caKey = (PrivateKey) signerKeyStore.keystore.getKey(signerAlias, signerPassword.toCharArray());
		final Calendar start = Calendar.getInstance();
		final Calendar expiry = Calendar.getInstance();
		expiry.add(Calendar.YEAR, 1);
		final KeyPair keyPair = generateKeyPair();
		final X500Name certName = new X500Name(dn);
		final X500Name issuerName = new X500Name(caCert.getSubjectDN().getName());
		X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
				issuerName,
				BigInteger.valueOf(System.nanoTime()),
				start.getTime(),
				expiry.getTime(),
				certName,
				SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
		final JcaX509ExtensionUtils u = new JcaX509ExtensionUtils();
		certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
				u.createAuthorityKeyIdentifier(caCert));
		certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
				u.createSubjectKeyIdentifier(keyPair.getPublic()));
		ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(caKey);
		X509CertificateHolder holder = certificateBuilder.build(signer);
		Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);

		Entry entry = new PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] {cert, caCert});
		keystore.setEntry(certificateAlias, entry, new PasswordProtection(password.toCharArray()));
	} catch (GeneralSecurityException | OperatorCreationException | CertIOException ex) {
		throw new RuntimeException("Unable to generate signed certificate", ex);
	}
}
 
開發者ID:xtf-cz,項目名稱:xtf,代碼行數:33,代碼來源:XTFKeyStore.java

示例14: generateSelfSignedX509Certificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(dn)),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth}));

        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
 
開發者ID:apache,項目名稱:nifi-registry,代碼行數:47,代碼來源:CertificateUtils.java

示例15: generateIssuedCertificate

import org.bouncycastle.cert.X509v3CertificateBuilder; //導入方法依賴的package包/類
/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 */
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth}));

        // (3) subjectAlternativeName
        if(extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }

        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
 
開發者ID:apache,項目名稱:nifi-registry,代碼行數:53,代碼來源:CertificateUtils.java


注:本文中的org.bouncycastle.cert.X509v3CertificateBuilder.addExtension方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。