Java Code Examples for org.bouncycastle.asn1.x509.BasicConstraints

The following examples show how to use org.bouncycastle.asn1.x509.BasicConstraints. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: portecle   Source File: X509Ext.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get Basic Constraints (2.5.29.19) extension value as a string.
 *
 * <pre>
 * BasicConstraints ::= SEQUENCE {
 *     cA                      BOOLEAN DEFAULT FALSE,
 *     pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 */
private String getBasicConstraintsStringValue(byte[] bValue)
{
	BasicConstraints bc = BasicConstraints.getInstance(bValue);
	StringBuilder strBuff = new StringBuilder();

	strBuff.append(RB.getString(bc.isCA() ? "SubjectIsCa" : "SubjectIsNotCa"));
	strBuff.append("<br><br>");

	BigInteger pathLen = bc.getPathLenConstraint();
	if (pathLen != null)
	{
		strBuff.append(MessageFormat.format(RB.getString("PathLengthConstraint"), pathLen));
	}

	return strBuff.toString();
}
 
Example 2
Source Project: qpid-broker-j   Source File: TlsResourceBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static X509Certificate createSelfSignedCertificate(final KeyPair keyPair,
                                                           final String dn,
                                                           final ValidityPeriod period,
                                                           final AlternativeName... alternativeName)
        throws CertificateException
{
    try
    {
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                new X500Name(RFC4519Style.INSTANCE, dn),
                generateSerialNumber(),
                new Date(period.getFrom().toEpochMilli()),
                new Date(period.getTo().toEpochMilli()),
                new X500Name(RFC4519Style.INSTANCE, dn),
                keyPair.getPublic());
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
        builder.addExtension(createKeyUsageExtension());
        builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
        builder.addExtension(createAlternateNamesExtension(alternativeName));
        return buildX509Certificate(builder, keyPair.getPrivate());
    }
    catch (OperatorException | IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example 3
Source Project: qpid-broker-j   Source File: TlsResourceBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static X509Certificate createRootCACertificate(final KeyPair keyPair,
                                                       final String dn,
                                                       final ValidityPeriod validityPeriod)
        throws CertificateException
{
    try
    {
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                new X500Name(RFC4519Style.INSTANCE, dn),
                generateSerialNumber(),
                new Date(validityPeriod.getFrom().toEpochMilli()),
                new Date(validityPeriod.getTo().toEpochMilli()),
                new X500Name(RFC4519Style.INSTANCE, dn),
                keyPair.getPublic());

        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
        builder.addExtension(createAuthorityKeyExtension(keyPair.getPublic()));
        return buildX509Certificate(builder, keyPair.getPrivate());
    }
    catch (OperatorException | IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example 4
Source Project: logback-gelf   Source File: X509Util.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private X509Certificate build() throws NoSuchAlgorithmException,
    CertIOException, OperatorCreationException, CertificateException {

    final X500Principal issuer = new X500Principal("CN=MyCA");
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final Date from = Date.valueOf(LocalDate.now());
    final Date to = Date.valueOf(LocalDate.now().plusYears(1));
    final X509v3CertificateBuilder v3CertGen =
        new JcaX509v3CertificateBuilder(issuer, sn, from, to, issuer, keyPair.getPublic());
    final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
        extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.subjectKeyIdentifier, false,
        extUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.basicConstraints, true,
        new BasicConstraints(0));
    v3CertGen.addExtension(Extension.keyUsage, true,
        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    final ContentSigner signer = new JcaContentSignerBuilder(SIG_ALGORITHM)
        .build(keyPair.getPrivate());
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(v3CertGen.build(signer));
}
 
Example 5
Source Project: nomulus   Source File: SelfSignedCaCertificate.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns a self-signed Certificate Authority (CA) certificate. */
static X509Certificate createCaCert(KeyPair keyPair, String fqdn, Date from, Date to)
    throws Exception {
  X500Name owner = new X500Name("CN=" + fqdn);
  ContentSigner signer =
      new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
  X509v3CertificateBuilder builder =
      new JcaX509v3CertificateBuilder(
          owner, new BigInteger(64, RANDOM), from, to, owner, keyPair.getPublic());

  // Mark cert as CA by adding basicConstraint with cA=true to the builder
  BasicConstraints basicConstraints = new BasicConstraints(true);
  builder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);

  X509CertificateHolder certHolder = builder.build(signer);
  return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
}
 
Example 6
Source Project: credhub   Source File: SignedCertificateGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getSignedByIssuer_generatesACertificateWithTheRightValues() throws Exception {
  final X509Certificate generatedCertificate = subject
    .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters,
      certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate());

  assertThat(generatedCertificate.getIssuerDN().getName(), containsString("CN=ca DN"));
  assertThat(generatedCertificate.getIssuerDN().getName(), containsString("O=credhub"));

  assertThat(generatedCertificate.getSerialNumber(), equalTo(BigInteger.valueOf(1337L)));
  assertThat(generatedCertificate.getNotBefore().toString(), equalTo(Date.from(now).toString()));
  assertThat(generatedCertificate.getNotAfter().toString(), equalTo(Date.from(later).toString()));
  assertThat(generatedCertificate.getSubjectDN().toString(), containsString("CN=my cert name"));
  assertThat(generatedCertificate.getPublicKey(), equalTo(generatedCertificateKeyPair.getPublic()));
  assertThat(generatedCertificate.getSigAlgName(), equalTo("SHA256WITHRSA"));
  generatedCertificate.verify(issuerKey.getPublic());

  final byte[] isCaExtension = generatedCertificate.getExtensionValue(Extension.basicConstraints.getId());
  assertThat(Arrays.copyOfRange(isCaExtension, 2, isCaExtension.length),
    equalTo(new BasicConstraints(true).getEncoded()));
}
 
Example 7
Source Project: DeviceConnect-Android   Source File: AbstractKeyStoreManager.java    License: MIT License 6 votes vote down vote up
private X509Certificate generateX509V3Certificate(final KeyPair keyPair,
                                                  final X500Principal subject,
                                                  final X500Principal issuer,
                                                  final Date notBefore,
                                                  final Date notAfter,
                                                  final BigInteger serialNumber,
                                                  final GeneralNames generalNames,
                                                  final boolean isCA) throws GeneralSecurityException {
    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serialNumber);
    generator.setIssuerDN(issuer);
    generator.setSubjectDN(subject);
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setPublicKey(keyPair.getPublic());
    generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA));
    generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160));
    generator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    if (generalNames != null) {
        generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames);
    }
    return generator.generateX509Certificate(keyPair.getPrivate(), SecurityUtil.getSecurityProvider());
}
 
Example 8
@Override
public RootCertificate build() {
  signer.addExtension(KeyUsageExtension.create(
      KeyUsage.KEY_CERT_SIGN,
      KeyUsage.CRL_SIGN));

  if (crlUri != null) {
    signer.addExtension(CrlDistPointExtension.create(crlUri));
  }

  // This is a CA
  signer.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));

  final X509Certificate rootCertificate = signer.sign().getX509Certificate();

  return new RootCertificateImpl(rootCertificate, pair.getPrivate());
}
 
Example 9
Source Project: xipki   Source File: CaEmulator.java    License: Apache License 2.0 6 votes vote down vote up
public X509Cert generateCert(SubjectPublicKeyInfo pubKeyInfo, X500Name subjectDn,
    Date notBefore) throws Exception {
  Args.notNull(pubKeyInfo, "pubKeyInfo");
  Args.notNull(subjectDn, "subjectDn");
  Args.notNull(notBefore, "notBefore");

  Date notAfter = new Date(notBefore.getTime() + 730 * DAY_IN_MS);
  BigInteger tmpSerialNumber = BigInteger.valueOf(serialNumber.getAndAdd(1));
  X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(caSubject,
          tmpSerialNumber, notBefore, notAfter, subjectDn, pubKeyInfo);

  X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.dataEncipherment
      | X509KeyUsage.keyAgreement | X509KeyUsage.keyEncipherment);
  certGenerator.addExtension(Extension.keyUsage, true, ku);
  BasicConstraints bc = new BasicConstraints(false);
  certGenerator.addExtension(Extension.basicConstraints, true, bc);

  String signatureAlgorithm = ScepUtil.getSignatureAlgorithm(caKey, HashAlgo.SHA256);
  ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(caKey);
  X509Cert cert = new X509Cert(certGenerator.build(contentSigner));

  serialCertMap.put(tmpSerialNumber, cert);
  reqSubjectCertMap.put(subjectDn, cert);
  return cert;
}
 
Example 10
Source Project: xipki   Source File: ExtensionsChecker.java    License: Apache License 2.0 6 votes vote down vote up
private void checkExtnBasicConstraints(StringBuilder failureMsg, byte[] extensionValue) {
  BasicConstraints bc = BasicConstraints.getInstance(extensionValue);
  CertLevel certLevel = certprofile.getCertLevel();
  boolean ca = (CertLevel.RootCA == certLevel) || (CertLevel.SubCA == certLevel);
  if (ca != bc.isCA()) {
    addViolation(failureMsg, "ca", bc.isCA(), ca);
  }

  if (!bc.isCA()) {
    return;
  }

  BigInteger tmpPathLen = bc.getPathLenConstraint();
  Integer pathLen = certprofile.getPathLen();
  if (pathLen == null) {
    if (tmpPathLen != null) {
      addViolation(failureMsg, "pathLen", tmpPathLen, "absent");
    }
  } else {
    if (tmpPathLen == null) {
      addViolation(failureMsg, "pathLen", "null", pathLen);
    } else if (!BigInteger.valueOf(pathLen).equals(tmpPathLen)) {
      addViolation(failureMsg, "pathLen", tmpPathLen, pathLen);
    }
  }
}
 
Example 11
Source Project: Spark   Source File: IdentityController.java    License: Apache License 2.0 6 votes vote down vote up
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException {

        long serial = System.currentTimeMillis();
        SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        X500Name name = new X500Name(createX500NameString());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, 
                                                                            BigInteger.valueOf(serial), 
                                                                            new Date(System.currentTimeMillis() - 1000000000), 
                                                                            new Date(System.currentTimeMillis() + 1000000000),
                                                                            name, 
                                                                            keyInfo
                                                                            );
        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); 
        certBuilder.addExtension(Extension.keyUsage,         true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
        ContentSigner signer = csBuilder.build(keyPair.getPrivate());
        X509CertificateHolder certHolder = certBuilder.build(signer);
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
        
        return cert;
    }
 
Example 12
Source Project: besu   Source File: SelfSignedP12Certificate.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("JdkObsolete") // JcaX509v3CertificateBuilder requires java.util.Date.
private static Certificate generateSelfSignedCertificate(final KeyPair keyPair)
    throws CertIOException, GeneralSecurityException, OperatorCreationException {
  final X500Name issuer = new X500Name(distinguishedName);
  final X500Name subject = new X500Name(distinguishedName);
  final BigInteger serialNumber = new BigInteger(String.valueOf(Instant.now().toEpochMilli()));
  final X509v3CertificateBuilder v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(
          issuer,
          serialNumber,
          Date.from(Instant.now()),
          Date.from(Instant.now().plus(Period.ofDays(90))),
          subject,
          keyPair.getPublic());

  // extensions
  v3CertificateBuilder.addExtension(
      Extension.basicConstraints, true, new BasicConstraints(IS_CA));
  v3CertificateBuilder.addExtension(
      Extension.subjectAlternativeName, false, getSubjectAlternativeNames());

  final ContentSigner contentSigner =
      new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());

  return new JcaX509CertificateConverter()
      .setProvider(BOUNCY_CASTLE_PROVIDER)
      .getCertificate(v3CertificateBuilder.build(contentSigner));
}
 
Example 13
Source Project: NetBare   Source File: CertificateGenerator.java    License: MIT License 5 votes vote down vote up
/**
 * Generate a root keystore by a given {@link JKS}.
 *
 * @param jks A java keystore object.
 * @return A root {@link KeyStore}.
 */
public KeyStore generateRoot(JKS jks)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, OperatorCreationException {
    KeyPair keyPair = generateKeyPair(ROOT_KEY_SIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, jks.commonName());
    nameBuilder.addRDN(BCStyle.O, jks.organization());
    nameBuilder.addRDN(BCStyle.OU, jks.organizationalUnitName());
    X500Name issuer = nameBuilder.build();

    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, BigInteger.valueOf(randomSerial()), NOT_BEFORE, NOT_AFTER, issuer, pubKey);
    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature |
            KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore.getInstance(KEY_STORE_TYPE);
    result.load(null, null);
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(),
            new Certificate[] { cert });
    return result;
}
 
Example 14
Source Project: NetBare   Source File: CertificateGenerator.java    License: MIT License 5 votes vote down vote up
public KeyStore generateServer(String commonName, JKS jks,
                                      Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(SERVER_KEY_SIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
    BigInteger serial = BigInteger.valueOf(randomSerial());
    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, jks.certOrganisation());
    name.addRDN(BCStyle.OU, jks.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());
    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));
    builder.addExtension(Extension.subjectAlternativeName, false,
            new DERSequence(new GeneralName(GeneralName.dNSName, commonName)));

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType());
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(), chain);
    return result;
}
 
Example 15
private static AttestationCertificatePath generateCertPath(KeyPair pair, String signAlg) {

        try {
            Provider bcProvider = new BouncyCastleProvider();
            //Security.addProvider(bcProvider);

            long now = System.currentTimeMillis();
            Date from = new Date(now);
            Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(1));

            X500Name dnName = new X500Name("C=ORG, O=Dummy Org, OU=Authenticator Attestation, CN=Dummy");
            BigInteger certSerialNumber = BigInteger.ZERO;

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(from);
            calendar.add(Calendar.YEAR, 1);

            ContentSigner contentSigner = new JcaContentSignerBuilder(signAlg).build(pair.getPrivate());
            JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, from, to, dnName, pair.getPublic());

            BasicConstraints basicConstraints = new BasicConstraints(false);
            certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);

            X509Certificate certificate = new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
            return new AttestationCertificatePath(Collections.singletonList(certificate));
        } catch (OperatorCreationException | CertificateException | CertIOException e) {
            throw new UnexpectedCheckedException(e);
        }
    }
 
Example 16
Source Project: localization_nifi   Source File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 17
Source Project: localization_nifi   Source File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 18
Source Project: proxyee   Source File: CertUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 生成CA服务器证书
 */
public static X509Certificate genCACert(String subject, Date caNotBefore, Date caNotAfter,
                                        KeyPair keyPair) throws Exception {
    JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(subject),
            BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000),
            caNotBefore,
            caNotAfter,
            new X500Name(subject),
            keyPair.getPublic());
    jv3Builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .build(keyPair.getPrivate());
    return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer));
}
 
Example 19
Source Project: calcite-avatica   Source File: HttpBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
private X509Certificate generateCert(String keyName, KeyPair kp, boolean isCertAuthority,
                                     PublicKey signerPublicKey, PrivateKey signerPrivateKey)
    throws IOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {
  Calendar startDate = DateTimeUtils.calendar();
  Calendar endDate = DateTimeUtils.calendar();
  endDate.add(Calendar.YEAR, 100);

  BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis());
  X500Name issuer = new X500Name(
      IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE));
  JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer,
      serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic());
  JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
  certGen.addExtension(Extension.subjectKeyIdentifier, false,
      extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
  certGen.addExtension(Extension.basicConstraints, false,
      new BasicConstraints(isCertAuthority));
  certGen.addExtension(Extension.authorityKeyIdentifier, false,
      extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
  if (isCertAuthority) {
    certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
  }
  X509CertificateHolder certificateHolder = certGen.build(
      new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey));
  return new JcaX509CertificateConverter().getCertificate(certificateHolder);
}
 
Example 20
Source Project: nifi-registry   Source File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 21
Source Project: nifi-registry   Source File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 22
Source Project: qpid-broker-j   Source File: TlsResourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static X509Certificate generateIntermediateCertificate(final KeyPair keyPair,
                                                               final KeyCertificatePair rootCA,
                                                               final String dn,
                                                               final ValidityPeriod validityPeriod,
                                                               final String crlUri)
        throws CertificateException
{
    try
    {
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                rootCA.getCertificate(),
                generateSerialNumber(),
                new Date(validityPeriod.getFrom().toEpochMilli()),
                new Date(validityPeriod.getTo().toEpochMilli()),
                new X500Name(RFC4519Style.INSTANCE, dn),
                keyPair.getPublic());
        //builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
        builder.addExtension(createAuthorityKeyExtension(rootCA.getCertificate().getPublicKey()));
        if (crlUri != null)
        {
            builder.addExtension(createDistributionPointExtension(crlUri));
        }

        return buildX509Certificate(builder, rootCA.getPrivateKey());
    }
    catch (OperatorException | IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example 23
private X509Certificate generateCertificate(String dn, KeyPair keyPair, int validity, String sigAlgName) throws GeneralSecurityException, IOException, OperatorCreationException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);

    // Use appropriate signature algorithm based on your keyPair algorithm.
    String signatureAlgorithm = sigAlgName;

    X500Name dnName = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + validity * 1000L * 24L * 60L * 60L);

    // Using the current timestamp as the certificate serial number
    BigInteger certSerialNumber = new BigInteger(Long.toString(from.getTime()));


    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
            dnName, certSerialNumber, from, to, dnName, keyPair.getPublic());

    // true for CA, false for EndEntity
    BasicConstraints basicConstraints = new BasicConstraints(true);

    // Basic Constraints is usually marked as critical.
    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);

    return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}
 
Example 24
public static KeyStore createRootCertificate(Authority authority, String keyStoreType)
		throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException,
		OperatorCreationException, CertificateException, KeyStoreException {

	KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

	X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
	nameBuilder.addRDN(BCStyle.CN, authority.commonName());
	nameBuilder.addRDN(BCStyle.O, authority.organization());
	nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

	X500Name issuer = nameBuilder.build();
	BigInteger serial = BigInteger.valueOf(initRandomSerial());
	X500Name subject = issuer;
	PublicKey pubKey = keyPair.getPublic();

	X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
			subject, pubKey);

	generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey));
	generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

	KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
			| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
	generator.addExtension(Extension.keyUsage, false, usage);

	ASN1EncodableVector purposes = new ASN1EncodableVector();
	purposes.add(KeyPurposeId.id_kp_serverAuth);
	purposes.add(KeyPurposeId.id_kp_clientAuth);
	purposes.add(KeyPurposeId.anyExtendedKeyUsage);
	generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

	X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

	KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */);
	result.load(null, null);
	result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert });
	return result;
}
 
Example 25
public static KeyStore createServerCertificate(String commonName,
		SubjectAlternativeNameHolder subjectAlternativeNames, Authority authority, Certificate caCert,
		PrivateKey caPrivKey)
		throws NoSuchAlgorithmException, NoSuchProviderException, IOException, OperatorCreationException,
		CertificateException, InvalidKeyException, SignatureException, KeyStoreException {

	KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);

	X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
	BigInteger serial = BigInteger.valueOf(initRandomSerial());

	X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
	name.addRDN(BCStyle.CN, commonName);
	name.addRDN(BCStyle.O, authority.certOrganisation());
	name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
	X500Name subject = name.build();

	X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
			subject, keyPair.getPublic());

	builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(keyPair.getPublic()));
	builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

	subjectAlternativeNames.fillInto(builder);

	X509Certificate cert = signCertificate(builder, caPrivKey);

	cert.checkValidity(new Date());
	cert.verify(caCert.getPublicKey());

	KeyStore result = KeyStore.getInstance("PKCS12"
	/* , PROVIDER_NAME */);
	result.load(null, null);
	Certificate[] chain = { cert, caCert };
	result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), chain);

	return result;
}
 
Example 26
Source Project: fabric-sdk-java   Source File: TLSCertificateBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private X509Certificate createSelfSignedCertificate(CertType certType, KeyPair keyPair, String san) throws Exception {
    X509v3CertificateBuilder certBuilder = createCertBuilder(keyPair);

    // Basic constraints
    BasicConstraints constraints = new BasicConstraints(false);
    certBuilder.addExtension(
            Extension.basicConstraints,
            true,
            constraints.getEncoded());
    // Key usage
    KeyUsage usage = new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature);
    certBuilder.addExtension(Extension.keyUsage, false, usage.getEncoded());
    // Extended key usage
    certBuilder.addExtension(
            Extension.extendedKeyUsage,
            false,
            certType.keyUsage().getEncoded());

    if (san != null) {
        addSAN(certBuilder, san);
    }

    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm)
            .build(keyPair.getPrivate());
    X509CertificateHolder holder = certBuilder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    converter.setProvider(new BouncyCastleProvider());
    return converter.getCertificate(holder);
}
 
Example 27
Source Project: enmasse   Source File: DeviceCertificateManager.java    License: Apache License 2.0 5 votes vote down vote up
public DeviceCertificateManager(final Mode mode, final X500Principal baseName) throws Exception {

        this.mode = mode;
        this.baseName = baseName;
        this.keyPairGenerator = KeyPairGenerator.getInstance(mode.getGeneratorAlgorithm());
        this.keyPairGenerator.initialize(mode.getSpec());
        this.keyPair = keyPairGenerator.generateKeyPair();

        final Instant now = Instant.now();

        final ContentSigner contentSigner = new JcaContentSignerBuilder(mode.getSignatureAlgorithm())
                .build(this.keyPair.getPrivate());

        final X509CertificateHolder certificate = new JcaX509v3CertificateBuilder(
                baseName,
                BigInteger.valueOf(this.serialNumber.getAndIncrement()),
                Date.from(now),
                Date.from(now.plus(Duration.ofDays(365))),
                baseName,
                this.keyPair.getPublic())
                        .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(this.keyPair.getPublic()))
                        .addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(this.keyPair.getPublic()))
                        .addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                        .build(contentSigner);

        this.certificate = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider())
                .getCertificate(certificate);

    }
 
Example 28
Source Project: credhub   Source File: CertificateReader.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isCa() {
  final Extensions extensions = certificateHolder.getExtensions();
  BasicConstraints basicConstraints = null;

  if (extensions != null) {
    basicConstraints = BasicConstraints
      .fromExtensions(Extensions.getInstance(extensions));
  }

  return basicConstraints != null && basicConstraints.isCA();
}
 
Example 29
Source Project: credhub   Source File: CertificateGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
private X509CertificateHolder makeCert(final KeyPair certKeyPair,
                                       final PrivateKey caPrivateKey,
                                       final X500Name caDn,
                                       final X500Name subjectDn,
                                       final boolean isCa) throws OperatorCreationException, NoSuchAlgorithmException, CertIOException {
  final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certKeyPair.getPublic()
    .getEncoded());
  final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA")
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .build(caPrivateKey);

  final CurrentTimeProvider currentTimeProvider = new CurrentTimeProvider();

  final Instant now = Instant.from(currentTimeProvider.getInstant());

  final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
    caDn,
    BigInteger.TEN,
    Date.from(now),
    Date.from(now.plus(Duration.ofDays(365))),
    subjectDn,
    publicKeyInfo
  );
  x509v3CertificateBuilder
    .addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa));
  return x509v3CertificateBuilder.build(contentSigner);
}
 
Example 30
Source Project: development   Source File: CertificateHandler.java    License: Apache License 2.0 5 votes vote down vote up
private X509Certificate generateSignedCertificate(
        PKCS10CertificationRequest csr) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException,
        CertificateParsingException, CertificateEncodingException,
        SignatureException {

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    Calendar c = Calendar.getInstance();
    certGen.setNotBefore(c.getTime());
    c.add(Calendar.YEAR, 1);
    certGen.setNotAfter(c.getTime());
    certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(csr.getPublicKey("BC"));
    certGen.setSignatureAlgorithm(ALGORITHM_SHA256_RSA);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert.getPublicKey()));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
    certGen.addExtension(X509Extensions.BasicConstraints, true,
            new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    X509Certificate issuedCert = certGen.generate(rootPrivateKeyEntry
            .getPrivateKey());
    return issuedCert;
}