Java Code Examples for org.bouncycastle.cert.jcajce.JcaX509CertificateConverter

The following examples show how to use org.bouncycastle.cert.jcajce.JcaX509CertificateConverter. 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: netty-4.1.22   Source File: OcspServerExample.java    License: Apache License 2.0 7 votes vote down vote up
private static X509Certificate[] parseCertificates(Reader reader) throws Exception {

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider());

        List<X509Certificate> dst = new ArrayList<X509Certificate>();

        PEMParser parser = new PEMParser(reader);
        try {
          X509CertificateHolder holder = null;

          while ((holder = (X509CertificateHolder) parser.readObject()) != null) {
            X509Certificate certificate = converter.getCertificate(holder);
            if (certificate == null) {
              continue;
            }

            dst.add(certificate);
          }
        } finally {
            parser.close();
        }

        return dst.toArray(new X509Certificate[0]);
    }
 
Example 2
Source Project: ph-commons   Source File: KeyStoreHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static X509Certificate _createX509V1Certificate (final KeyPair aKeyPair) throws Exception
{
  // generate the certificate
  final PublicKey aPublicKey = aKeyPair.getPublic ();
  final PrivateKey aPrivateKey = aKeyPair.getPrivate ();
  final ContentSigner aContentSigner = new JcaContentSignerBuilder ("SHA256WithRSA").setProvider (PBCProvider.getProvider ())
                                                                                    .build (aPrivateKey);

  final X509CertificateHolder aCertHolder = new JcaX509v1CertificateBuilder (new X500Principal ("CN=Test Certificate"),
                                                                             BigInteger.valueOf (System.currentTimeMillis ()),
                                                                             new Date (System.currentTimeMillis () -
                                                                                       50000),
                                                                             new Date (System.currentTimeMillis () +
                                                                                       50000),
                                                                             new X500Principal ("CN=Test Certificate"),
                                                                             aPublicKey).build (aContentSigner);
  // Convert to JCA X509Certificate
  return new JcaX509CertificateConverter ().getCertificate (aCertHolder);
}
 
Example 3
Source Project: Hands-On-Cryptography-with-Java   Source File: KeyStoreDemo.java    License: MIT License 6 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 4
public List<X509Certificate> getAssociatedCertificates() {
   List<X509Certificate> result = new ArrayList();
   X509CertificateHolder[] arr$ = this.ocsp.getCerts();
   int len$ = arr$.length;

   for(int i$ = 0; i$ < len$; ++i$) {
      X509CertificateHolder certificateHolder = arr$[i$];

      try {
         result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder));
      } catch (CertificateException var7) {
         throw new IllegalArgumentException(var7);
      }
   }

   return result;
}
 
Example 5
public List<X509Certificate> getAssociatedCertificates() {
   List<X509Certificate> result = new ArrayList();
   X509CertificateHolder[] arr$ = this.ocsp.getCerts();
   int len$ = arr$.length;

   for(int i$ = 0; i$ < len$; ++i$) {
      X509CertificateHolder certificateHolder = arr$[i$];

      try {
         result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder));
      } catch (CertificateException var7) {
         throw new IllegalArgumentException(var7);
      }
   }

   return result;
}
 
Example 6
Source Project: ambry   Source File: TestSSLUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
    throws CertificateException {
  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example 7
public List<X509Certificate> getAssociatedCertificates() {
   List<X509Certificate> result = new ArrayList();
   X509CertificateHolder[] arr$ = this.ocsp.getCerts();
   int len$ = arr$.length;

   for(int i$ = 0; i$ < len$; ++i$) {
      X509CertificateHolder certificateHolder = arr$[i$];

      try {
         result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder));
      } catch (CertificateException var7) {
         throw new IllegalArgumentException(var7);
      }
   }

   return result;
}
 
Example 8
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 9
public List<X509Certificate> getAssociatedCertificates() {
   List<X509Certificate> result = new ArrayList();
   X509CertificateHolder[] arr$ = this.ocsp.getCerts();
   int len$ = arr$.length;

   for(int i$ = 0; i$ < len$; ++i$) {
      X509CertificateHolder certificateHolder = arr$[i$];

      try {
         result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder));
      } catch (CertificateException var7) {
         throw new IllegalArgumentException(var7);
      }
   }

   return result;
}
 
Example 10
Source Project: littleca   Source File: CertUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 读取x509 证书
 *
 * @param pemPath
 * @return
 */
public static X509Certificate readX509Cert(String savePath) throws CertException {
    try {
        if (null == savePath) {
            throw new CertException("save path can't be null");
        }
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(savePath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof X509CertificateHolder) {
            X509CertificateHolder holder = (X509CertificateHolder) readObject;
            return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getCertificate(holder);
        }
        pemParser.close();
        throw new CertException(savePath + "file read format failed");
    } catch (Exception e) {
        throw new CertException("read x509 cert failed", e);
    }
}
 
Example 11
Source Project: docker-java   Source File: CertificateUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * "cert.pem" from reader
 */
public static List<Certificate> loadCertificates(final Reader reader) throws IOException,
        CertificateException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        List<Certificate> certificates = new ArrayList<>();

        JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME);
        Object certObj;

        while ((certObj = pemParser.readObject()) != null) {
            if (certObj instanceof X509CertificateHolder) {
                X509CertificateHolder certificateHolder = (X509CertificateHolder) certObj;
                certificates.add(certificateConverter.getCertificate(certificateHolder));
            }
        }

        return certificates;
    }
}
 
Example 12
/**
 * 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 13
Source Project: keycloak   Source File: CertificateUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber) {
    try {
        X500Name subjectDN = new X500Name("CN=" + subject);
        Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 10);
        Date validityEndDate = new Date(calendar.getTime().getTime());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded());

        X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate,
                validityEndDate, subjectDN, subPubKeyInfo);
        X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));

        return new JcaX509CertificateConverter().getCertificate(holder);
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v1Certificate.", e);
    }
}
 
Example 14
Source Project: nifi   Source File: OcspCertificateValidatorTest.java    License: 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 15
Source Project: spring-cloud-gcp   Source File: RSAKeyGeneratorUtils.java    License: 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 16
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws CertificateException {

  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example 17
Source Project: signer   Source File: CAdESSigner.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private Collection<X509Certificate> getSignersCertificates(CMSSignedData previewSignerData) {
	Collection<X509Certificate> result = new HashSet<X509Certificate>();
	Store<?> certStore = previewSignerData.getCertificates();
	SignerInformationStore signers = previewSignerData.getSignerInfos();
	Iterator<?> it = signers.getSigners().iterator();
	while (it.hasNext()) {
		SignerInformation signer = (SignerInformation) it.next();
		@SuppressWarnings("unchecked")
		Collection<?> certCollection = certStore.getMatches(signer.getSID());
		Iterator<?> certIt = certCollection.iterator();
		X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
		try {
			result.add(new JcaX509CertificateConverter().getCertificate(certificateHolder));
		} catch (CertificateException error) {
		}
	}
	return result;

}
 
Example 18
Source Project: peer-os   Source File: CertificateTool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert X509 certificate in PEM format to X509Certificate object
 *
 * @param x509InPem X509 certificate in PEM format
 *
 * @return {@code X509Certificate}
 */
public X509Certificate convertX509PemToCert( String x509InPem )
{
    try
    {
        PEMParser pemParser = new PEMParser( new StringReader( x509InPem ) );
        JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter();

        Object o = pemParser.readObject();
        return x509CertificateConverter.getCertificate( ( X509CertificateHolder ) o );
    }
    catch ( Exception e )
    {
        throw new ActionFailedException( "Failed to convert PEM to certificate", e );
    }
}
 
Example 19
Source Project: vertx-tcp-eventbus-bridge   Source File: SSLKeyPairCerts.java    License: Apache License 2.0 6 votes vote down vote up
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception {
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new org.bouncycastle.asn1.x500.X500Name(certSub),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(certSub),
    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 20
Source Project: docker-java   Source File: CertificateUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * "ca.pem" from Reader
 */
public static KeyStore createTrustStore(final Reader certReader) throws IOException, CertificateException,
        KeyStoreException, NoSuchAlgorithmException {
    try (PEMParser pemParser = new PEMParser(certReader)) {

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);

        int index = 1;
        Object pemCert;

        while ((pemCert = pemParser.readObject()) != null) {
            Certificate caCertificate = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getCertificate((X509CertificateHolder) pemCert);
            trustStore.setCertificateEntry("ca-" + index, caCertificate);
            index++;
        }

        return trustStore;
    }
}
 
Example 21
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 22
Source Project: nomulus   Source File: SslInitializerTestUtils.java    License: 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 23
Source Project: cloudbreak   Source File: KeystoreUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Certificate loadCertificate(final String cert) throws IOException, CertificateException {
    StringReader reader = new StringReader(cert);

    try (PEMParser pemParser = new PEMParser(reader)) {
        X509CertificateHolder certificateHolder = (X509CertificateHolder) pemParser.readObject();
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    }
}
 
Example 24
Source Project: PowerTunnel   Source File: CertificateHelper.java    License: MIT License 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);
    return new JcaX509CertificateConverter().setProvider(
            PROVIDER_NAME).getCertificate(certificateBuilder.build(signer));
}
 
Example 25
Source Project: docker-maven-plugin   Source File: HttpsHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static Certificate loadCertificate(final String certPath) throws IOException, CertificateException {
    Path cert = Paths.get(certPath, "cert.pem");
    BufferedReader reader = Files.newBufferedReader(cert, Charset.defaultCharset());
    PEMParser parser = new PEMParser(reader);

    X509CertificateHolder object = (X509CertificateHolder) parser.readObject();
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(object);
}
 
Example 26
/**
 * Converts a Bouncy Castle X509CertificateHolder into a JCA X590Certificate.
 *
 * @param bouncyCastleCertificate BC X509CertificateHolder
 * @return JCA X509Certificate
 */
private static X509Certificate convertToJcaCertificate(X509CertificateHolder bouncyCastleCertificate) {
    try {
        return new JcaX509CertificateConverter()
                .getCertificate(bouncyCastleCertificate);
    } catch (CertificateException e) {
        throw new CertificateCreationException("Unable to convert X590CertificateHolder to JCA X590Certificate", e);
    }
}
 
Example 27
Source Project: ranger   Source File: AzureKeyVaultClientAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
private KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException {
	Security.addProvider(new BouncyCastleProvider());
	PEMParser pemParser = new PEMParser(new FileReader(new File(path)));
	PrivateKey privateKey = null;
	X509Certificate cert = null;
	Object object = pemParser.readObject();
	
	while (object != null) {
		JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
		if (object instanceof X509CertificateHolder) {
			cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
		}
		if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
			PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object;
			InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
			PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider);
			privateKey = converter.getPrivateKey(info);
		} 
		if (object instanceof PrivateKeyInfo) {
			privateKey = converter.getPrivateKey((PrivateKeyInfo) object);
		}
		object = pemParser.readObject();
	}
	KeyCert keycert = new KeyCert();
	keycert.setCertificate(cert);
	keycert.setKey(privateKey);
	pemParser.close();
	return keycert;
}
 
Example 28
Source Project: CapturePacket   Source File: BouncyCastleSecurityProviderTool.java    License: MIT License 5 votes vote down vote up
/**
 * Converts a Bouncy Castle X509CertificateHolder into a JCA X590Certificate.
 *
 * @param bouncyCastleCertificate BC X509CertificateHolder
 * @return JCA X509Certificate
 */
private static X509Certificate convertToJcaCertificate(X509CertificateHolder bouncyCastleCertificate) {
    try {
        return new JcaX509CertificateConverter()
                .getCertificate(bouncyCastleCertificate);
    } catch (CertificateException e) {
        throw new CertificateCreationException("Unable to convert X590CertificateHolder to JCA X590Certificate", e);
    }
}
 
Example 29
Source Project: docker-maven-plugin   Source File: HttpsHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static KeyStore createTrustStore(final String certPath)
        throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    Path caPath = Paths.get(certPath, "ca.pem");
    BufferedReader reader = Files.newBufferedReader(caPath, Charset.defaultCharset());

    PEMParser parser = new PEMParser(reader);
    X509CertificateHolder object = (X509CertificateHolder) parser.readObject();
    Certificate caCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(object);

    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(null);
    trustStore.setCertificateEntry("ca", caCert);
    return trustStore;
}
 
Example 30
Source Project: littleca   Source File: CertUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建一个自签名的证书
 *
 * @param publicKey
 * @param privateKey
 * @param userDN
 * @param notBefore
 * @param notAfter
 * @param serialNumber
 * @param signAlg
 * @return
 * @throws CertException
 */
public static X509Certificate makeUserSelfSignCert(PublicKey publicKey, PrivateKey privateKey, String userDN,
                                                   Date notBefore, Date notAfter, BigInteger serialNumber, String signAlg) throws CertException {
    try {
        if (null == signAlg) {
            throw new CertException(signAlg + " can't be null");
        }
        X500Name issuer = new X500Name(userDN);
        //1. 创建签名
        ContentSigner signer = new JcaContentSignerBuilder(signAlg)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privateKey);
        //2. 创建证书请求
        PKCS10CertificationRequestBuilder pkcs10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(issuer, publicKey);
        PKCS10CertificationRequest pkcs10CertificationRequest = pkcs10CertificationRequestBuilder.build(signer);

        //3. 创建证书
        //SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serialNumber,
                notBefore, notAfter, pkcs10CertificationRequest.getSubject(), pkcs10CertificationRequest.getSubjectPublicKeyInfo());

        //添加扩展信息 见 X509CertExtensions
        X509CertExtensions.buildAllExtensions(certBuilder, publicKey, publicKey);
        X509CertificateHolder holder = certBuilder.build(signer);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(holder);

    } catch (Exception e) {
        throw new CertException("makeUserSelfSignCert failed", e);
    }
}