Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory getInstance.

Prototype

public static final CertificateFactory getInstance(String type, Provider provider) throws CertificateException 

Source Link

Document

Returns a certificate factory object for the specified certificate type.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPair pair = generateRSAKeyPair();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bOut.write(generateV1Certificate(pair).getEncoded());
    bOut.close();// w  ww.  java 2 s .c  o m
    InputStream in = new ByteArrayInputStream(bOut.toByteArray());
    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in);
    System.out.println("issuer: " + x509Cert.getIssuerX500Principal());
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPair pair = generateRSAKeyPair();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bOut.write(generateV1Certificate(pair).getEncoded());
    bOut.close();//from ww w  .  ja  v a 2s. c om

    InputStream in = new ByteArrayInputStream(bOut.toByteArray());

    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate x509Cert;
    Collection collection = new ArrayList();

    while ((x509Cert = (X509Certificate) fact.generateCertificate(in)) != null) {
        collection.add(x509Cert);
    }

    Iterator it = collection.iterator();
    while (it.hasNext()) {
        System.out.println("version: " + ((X509Certificate) it.next()).getVersion());
    }
}

From source file:Main.java

/**
 * Generate a SSLSocketFactory wich checks the certificate given
 * @param context Context to use// w w w .  j  ava 2s.  c om
 * @param rResource int with url of the resource to read the certificate
 * @parma password String to use with certificate
 * @return SSLSocketFactory generated to validate this certificate
 */
public static SSLSocketFactory newSslSocketFactory(Context context, int rResource, String password)
        throws CertificateException, NoSuchProviderException, KeyStoreException, NoSuchAlgorithmException,
        IOException, UnrecoverableKeyException, KeyManagementException {

    // Get an instance of the Bouncy Castle KeyStore format
    KeyStore trusted = KeyStore.getInstance("BKS");
    // Get the raw resource, which contains the keystore with
    // your trusted certificates (root and any intermediate certs)
    InputStream is = context.getApplicationContext().getResources().openRawResource(rResource);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
    String alias = "alias";//cert.getSubjectX500Principal().getName();

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);
    trustStore.setCertificateEntry(alias, cert);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(trustStore, null);
    KeyManager[] keyManagers = kmf.getKeyManagers();

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    return sslContext.getSocketFactory();

}

From source file:org.globus.gsi.ptls.PureTLSUtil.java

/**
 * Converts PureTLS specific X509 certificate object 
 * into standard Java X509 certificate object
 * (right now it is using BouncyCastle provider to 
 * convert).//from  w  ww .j av a 2 s  . c om
 *
 * @param cert PureTLS X509 certificate object 
 * @return standard Java X509 certificate object
 * @exception GeneralSecurityException if conversion fails.
 */
public static X509Certificate convertCert(X509Cert cert) throws GeneralSecurityException {
    CertificateFactory f = CertificateFactory.getInstance("X.509", "BC");
    ByteArrayInputStream in = new ByteArrayInputStream(cert.getDER());
    return (X509Certificate) f.generateCertificate(in);
}

From source file:be.fedict.trust.crl.OfflineCrlRepository.java

/**
 * Main constructor/*w  w w.j a va 2 s  . co  m*/
 * 
 * @param encodedCrls
 *            the list of encoded CRL's that can be queried.
 * @throws NoSuchProviderException
 * @throws CertificateException
 * @throws CRLException
 */
public OfflineCrlRepository(List<byte[]> encodedCrls)
        throws CertificateException, NoSuchProviderException, CRLException {

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    this.crls = new LinkedList<X509CRL>();
    for (byte[] encodedCrl : encodedCrls) {
        ByteArrayInputStream bais = new ByteArrayInputStream(encodedCrl);
        this.crls.add((X509CRL) certificateFactory.generateCRL(bais));
    }
}

From source file:it.cnr.icar.eric.common.security.X509Parser.java

/**
 * Parses a X509Certificate from a DER formatted input stream. Uses the 
 * BouncyCastle provider if available./*w  w w.j a  va2s.  c o m*/
 *
 * @param inStream The DER InputStream with the certificate.
 * @return X509Certificate parsed from stream.
 * @throws JAXRException in case of IOException or CertificateException
 *  while parsing the stream.
 */
public static X509Certificate parseX509Certificate(InputStream inStream) throws JAXRException {
    try {
        //possible options
        // - der x509 generated by keytool -export
        // - der x509 generated by openssh x509 (might require BC provider)

        // Get the CertificateFactory to parse the stream
        // if BouncyCastle provider available, use it
        CertificateFactory cf;
        try {
            Class<?> clazz = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
            Constructor<?> constructor = clazz.getConstructor(new Class[] {});
            Provider bcProvider = (Provider) constructor.newInstance(new Object[] {});
            Security.addProvider(bcProvider);
            cf = CertificateFactory.getInstance("X.509", "BC");
        } catch (Exception e) {
            // log error if bc present but failed to instanciate/add provider
            if (!(e instanceof ClassNotFoundException)) {
                log.error(CommonResourceBundle.getInstance()
                        .getString("message.FailedToInstantiateBouncyCastleProvider"));
            }
            // fall back to default provider
            cf = CertificateFactory.getInstance("X.509");
        }

        // Read the stream to a local variable
        DataInputStream dis = new DataInputStream(inStream);
        byte[] bytes = new byte[dis.available()];
        dis.readFully(bytes);
        ByteArrayInputStream certStream = new ByteArrayInputStream(bytes);

        // Parse the cert stream
        int i = 0;
        Collection<? extends Certificate> c = cf.generateCertificates(certStream);
        X509Certificate[] certs = new X509Certificate[c.toArray().length];
        for (Iterator<? extends Certificate> it = c.iterator(); it.hasNext();) {
            certs[i++] = (X509Certificate) it.next();
        }

        // Some logging..
        if (log.isDebugEnabled()) {
            if (c.size() == 1) {
                log.debug("One certificate, no chain.");
            } else {
                log.debug("Certificate chain length: " + c.size());
            }
            log.debug("Subject DN: " + certs[0].getSubjectDN().getName());
            log.debug("Issuer DN: " + certs[0].getIssuerDN().getName());
        }

        // Do we need to return the chain?
        // do we need to verify if cert is self signed / valid?
        return certs[0];
    } catch (CertificateException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } catch (IOException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            inStream = null;
        }
    }
}

From source file:eu.musesproject.client.connectionmanager.TLSManager.java

/**
 * Convert local certificate to BKS//  w  w w.j av  a2 s. c o  m
 * @param cerStream
 * @param alias
 *    
 * @param password
 * @return keyStore
 */
private KeyStore convertCerToBKS(InputStream cerStream, String alias, char[] password) {
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance("BKS", "BC");
        CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
        Certificate certificate = factory.generateCertificate(cerStream);
        keyStore.load(null, password);
        keyStore.setCertificateEntry(alias, certificate);
    } catch (Exception e) {
        Log.d(TAG, e.getLocalizedMessage());
    }
    return keyStore;
}

From source file:org.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/* w  w  w  .  ja v a 2s  .  c  o  m*/
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

        // perform validation
        CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.debug("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on "
                + "certificate number " + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}

From source file:org.kse.crypto.x509.X509CertUtil.java

/**
 * Load one or more certificates from the specified stream.
 *
 * @param is// w  w w  . j a v a 2  s .c  o  m
 *            Stream to load certificates from
 * @return The certificates
 * @throws CryptoException
 *             Problem encountered while loading the certificate(s)
 */
public static X509Certificate[] loadCertificates(InputStream is) throws CryptoException {
    byte[] certsBytes = null;

    try {
        certsBytes = ReadUtil.readFully(is);

        // fix common input certificate problems by converting PEM/B64 to DER
        certsBytes = fixCommonInputCertProblems(certsBytes);

        is = new ByteArrayInputStream(certsBytes);

        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());

        Collection<? extends Certificate> certs = cf.generateCertificates(is);

        ArrayList<X509Certificate> loadedCerts = new ArrayList<X509Certificate>();

        for (Iterator<? extends Certificate> itr = certs.iterator(); itr.hasNext();) {
            X509Certificate cert = (X509Certificate) itr.next();

            if (cert != null) {
                loadedCerts.add(cert);
            }
        }

        return loadedCerts.toArray(new X509Certificate[loadedCerts.size()]);
    } catch (IOException | NoSuchProviderException ex) {
        throw new CryptoException(res.getString("NoLoadCertificate.exception.message"), ex);
    } catch (CertificateException ex) {
        // Failed to load certificates, may be pki path encoded - try loading as that
        try {
            return loadCertificatesPkiPath(new ByteArrayInputStream(certsBytes));
        } catch (CryptoException ex2) {
            throw new CryptoException(res.getString("NoLoadCertificate.exception.message"), ex);
        }
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.apache.synapse.transport.certificatevalidation.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/*from   w  w  w.  j av a  2  s.c o  m*/
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

        // perform validation
        CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.info("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on certificate number "
                + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}