Java Code Examples for org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder#build()

The following examples show how to use org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder#build() . 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: 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 2
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 3
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);
}
 
Example 4
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 5
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Generate a self-signed X509 certificate for the supplied key pair and signature algorithm.
 *
 * @return The generated certificate
 * @param sCommonName Common name certificate attribute
 * @param sOrganisationUnit Organization Unit certificate attribute
 * @param sOrganisation Organization certificate attribute
 * @param sLocality Locality certificate
 * @param sState State certificate attribute
 * @param sEmailAddress Email Address certificate attribute
 * @param sCountryCode Country Code certificate attribute
 * @param iValidity Validity period of certificate in days
 * @param sans Subject alternative names certificate extension value
 * @param publicKey Public part of key pair
 * @param privateKey Private part of key pair
 * @param signatureType Signature Type
 * @throws CryptoException If there was a problem generating the certificate
 */
public static X509Certificate generateCert(String sCommonName, String sOrganisationUnit, String sOrganisation,
    String sLocality, String sState, String sCountryCode, String sEmailAddress, int iValidity,
    Collection<GeneralName> sans, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType)
    throws CryptoException
{
	X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
	if (sEmailAddress != null)
	{
		nameBuilder.addRDN(BCStyle.E, sEmailAddress);
	}
	if (sCountryCode != null)
	{
		nameBuilder.addRDN(BCStyle.C, sCountryCode);
	}
	if (sState != null)
	{
		nameBuilder.addRDN(BCStyle.ST, sState);
	}
	if (sLocality != null)
	{
		nameBuilder.addRDN(BCStyle.L, sLocality);
	}
	if (sOrganisation != null)
	{
		nameBuilder.addRDN(BCStyle.O, sOrganisation);
	}
	if (sOrganisationUnit != null)
	{
		nameBuilder.addRDN(BCStyle.OU, sOrganisationUnit);
	}
	if (sCommonName != null)
	{
		nameBuilder.addRDN(BCStyle.CN, sCommonName);
	}

	BigInteger serial = generateX509SerialNumber();

	Date notBefore = new Date(System.currentTimeMillis());
	Date notAfter = new Date(notBefore.getTime() + ((long) iValidity * 24 * 60 * 60 * 1000));

	JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serial,
	    notBefore, notAfter, nameBuilder.build(), publicKey);

	try
	{
		if (sans != null && !sans.isEmpty())
		{
			certBuilder.addExtension(Extension.subjectAlternativeName, false,
			    new GeneralNames(sans.toArray(new GeneralName[sans.size()])));
		}

		ContentSigner signer = new JcaContentSignerBuilder(signatureType.name()).build(privateKey);
		X509CertificateHolder certHolder = certBuilder.build(signer);

		return new JcaX509CertificateConverter().getCertificate(certHolder);
	}
	catch (CertificateException | IOException | OperatorCreationException ex)
	{
		throw new CryptoException(RB.getString("CertificateGenFailed.exception.message"), ex);
	}
}
 
Example 6
Source File: CertificateManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder,
        X500NameBuilder subjectBuilder, String domain, String signAlgoritm, Set<String> sanDnsNames ) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();

    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();

    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();

    // builder
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( //
            issuerDN, //
            serial, //
            new Date(), //
            new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
            subjectDN, //
            pubKey //
            );

    // add subjectAlternativeName extension that includes all relevant names.
    final GeneralNames subjectAlternativeNames = getSubjectAlternativeNames( sanDnsNames );

    final boolean critical = subjectDN.getRDNs().length == 0;
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAlternativeNames);

    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));

    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);

        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }

        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }

        return new JcaX509CertificateConverter().getCertificate(cert);

    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}