org.bouncycastle.cert.X509v3CertificateBuilder Java Examples

The following examples show how to use org.bouncycastle.cert.X509v3CertificateBuilder. 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: KeyStoreDemo.java    From Hands-On-Cryptography-with-Java with MIT License 7 votes vote down vote up
/**
 * It's annoying to have to wrap KeyPairs with Certificates, but this is
 * "easier" for you to know who the key belongs to.
 *
 * @param keyPair A KeyPair to wrap
 * @return A wrapped certificate with constant name
 * @throws CertificateException
 * @throws OperatorCreationException
 */
public static Certificate generateCertificate(KeyPair keyPair) throws CertificateException, OperatorCreationException {
    X500Name name = new X500Name("cn=Annoying Wrapper");
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final Date start = new Date();
    final Date until = Date.from(LocalDate.now().plus(365, ChronoUnit.DAYS).atStartOfDay().toInstant(ZoneOffset.UTC));
    final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name,
            new BigInteger(10, new SecureRandom()), //Choose something better for real use
            start,
            until,
            name,
            subPubKeyInfo
    );
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    final X509CertificateHolder holder = builder.build(signer);

    Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);
    return cert;
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: OcspCertificateValidatorTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a certificate with a specific public key signed by the issuer key.
 *
 * @param dn        the subject DN
 * @param publicKey the subject public key
 * @param issuerDn  the issuer DN
 * @param issuerKey the issuer private key
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException,
        CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            new X500Name(issuerDn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

    X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example #10
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 #11
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 #12
Source File: KeyGenerator.java    From chvote-1-0 with GNU Affero General Public License v3.0 6 votes vote down vote up
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException {
    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY));
    nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY));
    nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY));
    nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY));
    X500Name x500Name = nameBuilder.build();

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

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

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

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

    String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY);
    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName));
    return certificateBuilder;
}
 
Example #13
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 #14
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static X509Certificate getX509CertificateFromPgpKeyPair( PGPPublicKey pgpPublicKey,
                                                                PGPSecretKey pgpSecretKey, String secretPwd,
                                                                String issuer, String subject, Date dateOfIssue,
                                                                Date dateOfExpiry, BigInteger serial )
        throws PGPException, CertificateException, IOException
{
    JcaPGPKeyConverter c = new JcaPGPKeyConverter();
    PublicKey publicKey = c.getPublicKey( pgpPublicKey );
    PrivateKey privateKey = c.getPrivateKey( pgpSecretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ) );

    X509v3CertificateBuilder certBuilder =
            new X509v3CertificateBuilder( new X500Name( issuer ), serial, dateOfIssue, dateOfExpiry,
                    new X500Name( subject ), SubjectPublicKeyInfo.getInstance( publicKey.getEncoded() ) );
    byte[] certBytes = certBuilder.build( new JCESigner( privateKey, "SHA256withRSA" ) ).getEncoded();
    CertificateFactory certificateFactory = CertificateFactory.getInstance( "X.509" );

    return ( X509Certificate ) certificateFactory.generateCertificate( new ByteArrayInputStream( certBytes ) );
}
 
Example #15
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public void generateCA() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384k1");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(ecGenSpec, SecurityHelper.newRandom());
    KeyPair pair = generator.generateKeyPair();
    LocalDateTime startDate = LocalDate.now().atStartOfDay();

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, orgName.concat(" CA"));
    subject.addRDN(BCStyle.O, orgName);

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
            subject.build(),
            new BigInteger("0"),
            Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
            Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
            new X500Name("CN=ca"),
            SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    ca = builder.build(signer);
    caKey = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
}
 
Example #16
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException {
    SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    BigInteger serial = BigInteger.valueOf(SecurityHelper.newRandom().nextLong());
    Date startDate = Date.from(Instant.now().minus(minusHours, ChronoUnit.HOURS));
    Date endDate = Date.from(startDate.toInstant().plus(validDays, ChronoUnit.DAYS));

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, subjectName);
    subject.addRDN(BCStyle.O, orgName);
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(ca.getSubject(), serial,
            startDate, endDate, subject.build(), subjectPubKeyInfo);

    AlgorithmIdentifier sigAlgId = ca.getSignatureAlgorithm();
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(caKey);

    return v3CertGen.build(sigGen);
}
 
Example #17
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 #18
Source File: JCEUtils.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
public static X509Certificate createSignedCertificate(String issuerName, String subjectName, Date notBefore, Long duration, TimeUnit timeUnit, PublicKey publicKey, PrivateKey privateKey) throws PKIException {
    try {
        X500Name issuer = new X500Name(CN_NAME + issuerName);
        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
        Date notAfter = new Date(notBefore.getTime() + timeUnit.toMillis(duration));
        X500Name subject = new X500Name(CN_NAME + subjectName);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo);
        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(SHA256_RSA);
        ContentSigner signer = jcaContentSignerBuilder.build(privateKey);
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, BC_PROVIDER);
        byte[] certBytes = certBuilder.build(signer).getEncoded();
        return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
    } catch (Exception e) {
        throw new PKIException(e);
    }
}
 
Example #19
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 #20
Source File: AbstractX509CertificateService.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected X509Certificate createCertificate(PrivateKey privateKey, X509v3CertificateBuilder x509v3CertificateBuilder)
    throws OperatorCreationException, CertificateException {
  ContentSigner contentSigner =
      new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(BouncyCastleProvider.PROVIDER_NAME)
          .build(privateKey);
  X509Certificate x509Certificate = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
      .getCertificate(x509v3CertificateBuilder.build(contentSigner));
  return x509Certificate;
}
 
Example #21
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static X509Certificate signCertificate(X509v3CertificateBuilder certificateBuilder,
		PrivateKey signedWithPrivateKey) throws OperatorCreationException, CertificateException {
	ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER_NAME)
			.build(signedWithPrivateKey);
	X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER_NAME)
			.getCertificate(certificateBuilder.build(signer));
	return cert;
}
 
Example #22
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 #23
Source File: CertificateAuthorityClientTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
private X509Certificate createCertificate() throws Exception {
    KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair();

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

    X500Name issuer = new X500NameBuilder()
            .addRDN(BCStyle.CN, "issuer")
            .build();

    X500Name subject = new X500NameBuilder()
            .addRDN(BCStyle.CN, "subject")
            .build();

    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate());

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509CertificateHolder certHolder = new X509v3CertificateBuilder(
            issuer,
            new BigInteger("1000"),
            Date.from(Instant.now()),
            Date.from(Instant.now().plusSeconds(100000)),
            subject,
            subjectPublicKeyInfo
            )
            .build(signer);
    return (X509Certificate) certificateFactory.
            generateCertificate(
                    new ByteArrayInputStream(certHolder.getEncoded()));
}
 
Example #24
Source File: KeyGenerator.java    From chvote-1-0 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generates a certificate corresponding to the given key pair
 *
 * @param keyPair the key pair
 * @return the certificate
 * @throws KeyGenerationRuntimeException  thrown if the x509 structure or certificate cannot be generated
 * @throws PropertyConfigurationException
 */
public X509Certificate generateCertificate(KeyPair keyPair) throws PropertyConfigurationException {
    try {
        X509v3CertificateBuilder certificateBuilder = createCertificateBuilder(keyPair);
        ContentSigner signer = createSigner(keyPair);

        return (X509Certificate) createCertificate(certificateBuilder, signer);
    } catch (OperatorCreationException | CertificateException | IOException e) {
        throw new KeyGenerationRuntimeException("error when generating the x509 certificate", e);
    }
}
 
Example #25
Source File: Certificates.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException,
  CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException,
  SignatureException {
  final String subject = issuer;
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new X500Name(issuer),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(subject),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );

  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

  final X509Certificate certificate = new JcaX509CertificateConverter()
    .getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
Example #26
Source File: ElasticsearchCluster.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static Certificate genSelfSignedCert(KeyPair keyPair, String signAlgo) throws CertificateException {
  X500Name issuer = new X500Name("CN=localhost, OU=test, O=Dremio, L=Mountain View, ST=CA, C=US");
  X500Name subject = issuer; // self signed
  BigInteger serial = BigInteger.valueOf(new Random().nextInt());
  Date notBefore = new Date(System.currentTimeMillis() - (24 * 3600 * 1000));
  Date notAfter = new Date(System.currentTimeMillis() + (24 * 3600 * 1000));
  SubjectPublicKeyInfo pubkeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
  X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, pubkeyInfo);
  ContentSigner signer = newSigner(keyPair.getPrivate(), signAlgo);
  X509CertificateHolder certHolder = certBuilder.build(signer);

  Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
  return cert;
}
 
Example #27
Source File: Certificates.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a Master certificate for ICure.
 */
public static X509Certificate createMasterCertificateV3(PublicKey publicKey, PrivateKey privateKey) throws Exception {
	X500Name 	issuer = new X500Name("C=BE, O=Taktik, OU=ICureCloud, CN=ICureCloud");
	X500Name 	subject = new X500Name("C=BE, O=Taktik, OU=ICureCloud, CN=ICureCloud"); // self signed
	BigInteger 	serial = BigInteger.valueOf(RSAKeysUtils.random.nextLong());
	Date 		notBefore = new Date(System.currentTimeMillis() - 10000);
	Date		notAfter = new Date(System.currentTimeMillis() + 24L * 3600 * 1000);
	
	SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
	
	X509v3CertificateBuilder x509v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, spki);
	x509v3CertBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true)); // icure is CA

	// Create a content signer
	AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);
	AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(privateKey.getEncoded());
	ContentSigner contentSigner =  new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(akp);

	X509CertificateHolder holder = x509v3CertBuilder.build(contentSigner);
	Certificate certificateStructure = holder.toASN1Structure();
	X509Certificate certificate = convertToJavaCertificate(certificateStructure);
	
	certificate.verify(publicKey);

	return certificate;
}
 
Example #28
Source File: TestUtil.java    From fabric-chaincode-java with Apache License 2.0 5 votes vote down vote up
/**
 * Function to create a certificate with dummy attributes
 *
 * @param attributeValue {String} value to be written to the identity attributes
 *                       section of the certificate
 * @return encodedCert {String} encoded certificate with re-written attributes
 */
public static String createCertWithIdentityAttributes(final String attributeValue) throws Exception {

    // Use existing certificate with attributes
    final byte[] decodedCert = Base64.getDecoder().decode(CERT_MULTIPLE_ATTRIBUTES);
    // Create a certificate holder and builder
    final X509CertificateHolder certHolder = new X509CertificateHolder(decodedCert);
    final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(certHolder);

    // special OID used by Fabric to save attributes in x.509 certificates
    final String fabricCertOid = "1.2.3.4.5.6.7.8.1";
    // Write the new attribute value
    final byte[] extDataToWrite = attributeValue.getBytes();
    certBuilder.replaceExtension(new ASN1ObjectIdentifier(fabricCertOid), true, extDataToWrite);

    // Create a privateKey
    final KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(384);
    final KeyPair keyPair = generator.generateKeyPair();

    // Create and build the Content Signer
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256withECDSA");
    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());
    // Build the Certificate from the certificate builder
    final X509CertificateHolder builtCert = certBuilder.build(contentSigner);
    final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X509")
            .generateCertificate(new ByteArrayInputStream(builtCert.getEncoded()));
    final String encodedCert = Base64.getEncoder().encodeToString(certificate.getEncoded());
    return encodedCert;
}
 
Example #29
Source File: Certificate.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
public static X509Certificate signCertificate(X509v3CertificateBuilder certificateBuilder, PrivateKey caPrivateKey) throws OperatorCreationException, CertificateException {
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME)
            .build(caPrivateKey);
    return new JcaX509CertificateConverter()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME)
            .getCertificate(certificateBuilder.build(signer));
}
 
Example #30
Source File: CertUtil.java    From nitmproxy with MIT License 5 votes vote down vote up
public static Certificate newCert(String parentCertFile, String keyFile, String host) {
    try {
        Date before = Date.from(Instant.now());
        Date after = Date.from(Year.now().plus(3, ChronoUnit.YEARS).atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());

        X509CertificateHolder parent = readPemFromFile(parentCertFile);
        PEMKeyPair pemKeyPair = readPemFromFile(keyFile);
        KeyPair keyPair = new JcaPEMKeyConverter()
                .setProvider(PROVIDER)
                .getKeyPair(pemKeyPair);

        X509v3CertificateBuilder x509 = new JcaX509v3CertificateBuilder(
                parent.getSubject(),
                new BigInteger(64, new SecureRandom()),
                before,
                after,
                new X500Name("CN=" + host),
                keyPair.getPublic());

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

        JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter()
                .setProvider(PROVIDER);

        return new Certificate(
                keyPair,
                x509CertificateConverter.getCertificate(x509.build(signer)),
                x509CertificateConverter.getCertificate(parent));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}