org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder Java Examples

The following examples show how to use org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder. 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 File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 7 votes vote down vote up
public static X509Certificate generateCert(PublicKey rqPubKey, BigInteger serialNr, Credential cred) throws TechnicalConnectorException {
   try {
      X509Certificate cert = cred.getCertificate();
      X500Principal principal = cert.getSubjectX500Principal();
      Date notBefore = cert.getNotBefore();
      Date notAfter = cert.getNotAfter();
      X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, serialNr, notBefore, notAfter, principal, rqPubKey);
      int keyUsageDetails = 16 + 32;
      builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails));
      ContentSigner signer = (new JcaContentSignerBuilder(cert.getSigAlgName())).build(cred.getPrivateKey());
      X509CertificateHolder holder = builder.build(signer);
      return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder);
   } catch (OperatorCreationException | IOException | CertificateException ex) {
      throw new IllegalArgumentException(ex);
   }
}
 
Example #2
Source File: TlsResourceBuilder.java    From qpid-broker-j with 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 #3
Source File: TLSCertificateBuilder.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private X509v3CertificateBuilder createCertBuilder(KeyPair keyPair) {
    X500Name subject = new X500NameBuilder(BCStyle.INSTANCE)
            .addRDN(BCStyle.CN, commonName)
            .build();

    Calendar notBefore = new GregorianCalendar();
    notBefore.add(Calendar.DAY_OF_MONTH, -1);
    Calendar notAfter = new GregorianCalendar();
    notAfter.add(Calendar.YEAR, 10);

    return new JcaX509v3CertificateBuilder(
            subject,
            new BigInteger(160, rand),
            notBefore.getTime(),
            notAfter.getTime(),
            subject,
            keyPair.getPublic());
}
 
Example #4
Source File: X509Util.java    From logback-gelf with 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 File: CertificateGeneratorTest.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void constructCert() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    ((Logger)LoggerFactory.getLogger(CertificateGenerator.class)).setLevel(Level.DEBUG);
    File file = new File("/tmp/dm-agent.jks");//Files.createTempFile("dm-agent", ".jks");

    KeyPair keypair = createKeypair();
    JcaX509v3CertificateBuilder cb = createRootCert(keypair);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keypair.getPrivate());
    X509CertificateHolder rootCert = cb.build(signer);
    KeystoreConfig cert = CertificateGenerator.constructCert(rootCert,
      keypair.getPrivate(),
      file,
      ImmutableSet.of("test1", "test2"));
    assertNotNull(cert);
}
 
Example #6
Source File: BouncyCastleSelfSignedCertGenerator.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
static String[] generate(String fqdn, KeyPair keypair, SecureRandom random, Date notBefore, Date notAfter)
        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), notBefore, notAfter, 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);
}
 
Example #7
Source File: IdentityCertificateService.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Create a certificate using key pair and signing certificate with CA certificate, common name and a list of subjective alternate name
 *
 * @return signed sever identity certificate
 * */
@Override
public X509Certificate createSignedCertificate(PublicKey publicKey, PrivateKey privateKey, String commonName,
    List<ASN1Encodable> sans)
    throws CertificateException, IOException, OperatorCreationException, NoSuchProviderException,
           NoSuchAlgorithmException, InvalidKeyException, SignatureException {
  X500Name issuer = new X509CertificateHolder(_issuerCertificate.getEncoded()).getSubject();
  BigInteger serial = getSerial();
  X500Name subject = getSubject(commonName);

  X509v3CertificateBuilder x509v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(issuer, serial, getValidDateFrom(), getValidDateTo(), subject, publicKey);
  buildExtensions(x509v3CertificateBuilder, publicKey);

  fillSans(sans, x509v3CertificateBuilder);

  X509Certificate signedCertificate = createCertificate(_issuerPrivateKey, x509v3CertificateBuilder);

  signedCertificate.checkValidity();
  signedCertificate.verify(_issuerCertificate.getPublicKey());

  return signedCertificate;
}
 
Example #8
Source File: SelfSignedCaCertificate.java    From nomulus with 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 #9
Source File: SslInitializerTestUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Signs the given key pair with the given self signed certificate to generate a certificate with
 * the given validity range.
 *
 * @return signed public key (of the key pair) certificate
 */
public static X509Certificate signKeyPair(
    SelfSignedCaCertificate ssc, KeyPair keyPair, String hostname, Date from, Date to)
    throws Exception {
  X500Name subjectDnName = new X500Name("CN=" + hostname);
  BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
  X500Name issuerDnName = new X500Name(ssc.cert().getIssuerDN().getName());
  ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(ssc.key());
  X509v3CertificateBuilder v3CertGen =
      new JcaX509v3CertificateBuilder(
          issuerDnName, serialNumber, from, to, subjectDnName, keyPair.getPublic());

  X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
  return new JcaX509CertificateConverter()
      .setProvider(PROVIDER)
      .getCertificate(certificateHolder);
}
 
Example #10
Source File: TlsResourceBuilder.java    From qpid-broker-j with 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 #11
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>no other identifiers than its CommonName</li>
 * </ul>
 */
@Test
public void testServerIdentitiesCommonNameOnly() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertEquals( subjectCommonName, serverIdentities.get( 0 ) );
}
 
Example #12
Source File: RsaSsaPss.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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)));
}
 
Example #13
Source File: Certificate.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #14
Source File: RSAKeyGeneratorUtils.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
public RSAKeyGeneratorUtils() throws Exception {
	KeyStore keyStore = KeyStore.getInstance("JKS");
	keyStore.load(null, null);
	KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
	kpGenerator.initialize(2048);
	KeyPair keyPair = kpGenerator.generateKeyPair();

	X500Name issuerName = new X500Name("OU=spring-cloud-gcp,CN=firebase-auth-integration-test");
	this.privateKey =  keyPair.getPrivate();

	JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
			issuerName,
			BigInteger.valueOf(System.currentTimeMillis()),
			Date.from(Instant.now()), Date.from(Instant.now().plusMillis(1096 * 24 * 60 * 60)),
			issuerName, keyPair.getPublic());
	ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
	X509CertificateHolder certHolder = builder.build(signer);
	this.certificate = new JcaX509CertificateConverter().getCertificate(certHolder);
	this.publicKey = this.certificate.getPublicKey();
}
 
Example #15
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddr() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.otherName, otherName ) );
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameXmppAddr ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #16
Source File: BouncyCastleSelfSignedCertGenerator.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #17
Source File: CertificateGeneratorTest.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private static JcaX509v3CertificateBuilder createRootCert(KeyPair keypair) throws Exception {
    X500NameBuilder ib = new X500NameBuilder(RFC4519Style.INSTANCE);
    ib.addRDN(RFC4519Style.c, "AQ");
    ib.addRDN(RFC4519Style.o, "Test");
    ib.addRDN(RFC4519Style.l, "Vostok Station");
    ib.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "[email protected]");
    X500Name issuer = ib.build();
    return createCert(keypair, issuer, issuer);
}
 
Example #18
Source File: CACertificateService.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public X509Certificate createSignedCertificate(PublicKey publicKey, PrivateKey privateKey, String commonName,
    List<ASN1Encodable> sans)
    throws CertificateException, IOException, OperatorCreationException, NoSuchProviderException,
           NoSuchAlgorithmException, InvalidKeyException, SignatureException {
  BigInteger serial = getSerial();
  X500Name subject = getSubject(commonName);
  X500Name issuer = subject;

  X509v3CertificateBuilder x509v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(issuer, serial, getValidDateFrom(), getValidDateTo(), subject, publicKey);
  buildExtensions(x509v3CertificateBuilder, publicKey);
  return createCertificate(privateKey, x509v3CertificateBuilder);
}
 
Example #19
Source File: TLSArtifactsGeneratorTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
private X509Certificate createCertificate() throws  Exception {
    BigInteger serial = new BigInteger(100, SecureRandom.getInstanceStrong());
    X500Name self = new X500Name("cn=localhost");
    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
            self,
            serial,
            Date.from(Instant.now()),
            Date.from(Instant.now().plusSeconds(100000)),
            self,
            KEYPAIR.getPublic());
    X509CertificateHolder certHolder = certificateBuilder
            .build(new JcaContentSignerBuilder("SHA256WithRSA").build(KEYPAIR.getPrivate()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
 
Example #20
Source File: OxAuthCryptoProvider.java    From oxAuth with MIT License 5 votes vote down vote up
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Signers name
    X500Name issuerName = new X500Name(issuer);

    // Subjects name - the same as we are self signed.
    X500Name subjectName = new X500Name(issuer);

    // Serial
    BigInteger serial = new BigInteger(256, new SecureRandom());

    // Not before
    Date notBefore = new Date(System.currentTimeMillis() - 10000);
    Date notAfter = new Date(expirationTime);

    // Create the certificate - version 3
    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);

    ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern();
    builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes));

    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey);
    X509CertificateHolder holder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);

    return cert;
}
 
Example #21
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #22
Source File: CertificateGenerator.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
static JcaX509v3CertificateBuilder createCert(KeyPair keyPair,
                                                X500Name issuer,
                                                X500Name subject) {
    Calendar calendar = Calendar.getInstance();
    Date fromTime = calendar.getTime();
    calendar.add(Calendar.YEAR, 5);
    return new JcaX509v3CertificateBuilder(
        issuer,
        BigInteger.valueOf(System.currentTimeMillis()),
        fromTime,
        calendar.getTime(),
        subject,
        keyPair.getPublic()
    );
}
 
Example #23
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'DNS SRV' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-dnsSRV"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesDnsSrv() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDnsSrv = "MySubjectAltNameXmppAddr";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] {DNS_SRV_OID, new DERUTF8String( "_xmpp-server."+subjectAltNameDnsSrv ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.otherName, otherName ) );
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameDnsSrv ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #24
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 * </ul>
 */
@Test
public void testServerIdentitiesDNS() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final GeneralNames generalNames = new GeneralNames(new GeneralName(GeneralName.dNSName, subjectAltNameDNS));

    builder.addExtension( Extension.subjectAlternativeName, false, generalNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameDNS ) );
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #25
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddrAndDNS() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName[] {
            new GeneralName( GeneralName.otherName, otherName ),
            new GeneralName( GeneralName.dNSName, subjectAltNameDNS )
    });
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 2, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameXmppAddr ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #26
Source File: DeviceCertificateManager.java    From enmasse with 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 #27
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #28
Source File: CertificateServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
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 #29
Source File: TlsResourceBuilder.java    From qpid-broker-j with 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 #30
Source File: HttpBaseTest.java    From calcite-avatica with 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);
}