Example usage for java.security.cert CertificateFactory generateCertificates

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

Introduction

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

Prototype

public final Collection<? extends Certificate> generateCertificates(InputStream inStream)
        throws CertificateException 

Source Link

Document

Returns a (possibly empty) collection view of the certificates read from the given input stream inStream .

Usage

From source file:org.bankinterface.util.KeyStoreUtil.java

public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass,
        byte[] certChain)
        throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    // load the private key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey pk = kf.generatePrivate(keysp);

    // load the cert chain
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);

    Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
    Certificate[] certs = new Certificate[certCol.toArray().length];
    if (certCol.size() == 1) {
        logger.info("Single certificate; no chain");
        bais = new ByteArrayInputStream(certChain);
        Certificate cert = cf.generateCertificate(bais);
        certs[0] = cert;//from  ww w  . ja va  2 s  .c om
    } else {
        logger.info("Certificate chain length : " + certCol.size());
        certs = certCol.toArray(new Certificate[certCol.size()]);
    }

    ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Retrieves the certificate from the specified URL and confirms that the certificate is valid.
 *
 * @param signingCertificateChainUrl/*from   ww  w.j a  v a2  s . co m*/
 *            the URL to retrieve the certificate chain from
 * @return the certificate at the specified URL, if the certificate is valid
 * @throws CertificateException
 *             if the certificate cannot be retrieve or is invalid
 */
public static X509Certificate retrieveAndVerifyCertificateChain(final String signingCertificateChainUrl)
        throws CertificateException {
    try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openStream()) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(Sdk.SIGNATURE_CERTIFICATE_TYPE);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory
                .generateCertificates(in);
        /*
         * check the before/after dates on the certificate date to confirm that it is valid on
         * the current date
         */
        X509Certificate signingCertificate = certificateChain.iterator().next();
        signingCertificate.checkValidity();

        // check the certificate chain
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
            }
        }

        if (x509TrustManager == null) {
            throw new IllegalStateException(
                    "No X509 TrustManager available. Unable to check certificate chain");
        } else {
            x509TrustManager.checkServerTrusted(
                    certificateChain.toArray(new X509Certificate[certificateChain.size()]),
                    Sdk.SIGNATURE_KEY_TYPE);
        }

        /*
         * verify Echo API's hostname is specified as one of subject alternative names on the
         * signing certificate
         */
        if (!subjectAlernativeNameListContainsEchoSdkDomainName(
                signingCertificate.getSubjectAlternativeNames())) {
            throw new CertificateException("The provided certificate is not valid for the Echo SDK");
        }

        return signingCertificate;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) {
        throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl,
                ex);
    }
}

From source file:com.vmware.bdd.manager.SoftwareManagerCollector.java

/**
 * TODO this method has to be reverted:/* w  ww  .j  a  va  2  s .c o m*/
 * because if the target path is not accessible, it will load cert from the default keystore in java home,
 * but still try to write it to the non accessible path.
 * @param certificate
 * @param keyStorePath
 */
protected static void saveSslCertificate(String certificate, String keyStorePath) {
    Certificate[] certs;
    //parse certificates
    try {
        if (CommonUtil.isBlank(certificate)) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        }

        byte[] certBytes = Base64.decodeBase64(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "")
                .replaceAll("-----END CERTIFICATE-----", "").getBytes());

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection c = cf.generateCertificates(new ByteArrayInputStream(certBytes));
        certs = new Certificate[c.toArray().length];

        if (c.size() == 0) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        } else if (c.size() == 1) {
            certs[0] = cf.generateCertificate(new ByteArrayInputStream(certBytes));
        } else {
            certs = (Certificate[]) c.toArray(certs);
        }
    } catch (CertificateException e) {
        throw SoftwareManagerCollectorException.BAD_CERT(e);
    }

    //load & save keystore
    OutputStream out = null;
    try {
        KeyStore keyStore = CommonUtil.loadAppMgrKeyStore(keyStorePath);
        if (keyStore == null) {
            logger.error(Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
            throw new SWMgrCollectorInternalException(
                    Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
        }

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String md5Fingerprint = "";
        for (Certificate cert : certs) {
            md5.update(cert.getEncoded());
            md5Fingerprint = CommonUtil.toHexString(md5.digest());
            logger.debug("md5 finger print: " + md5Fingerprint);
            logger.debug("added cert: " + cert);
            keyStore.setCertificateEntry(md5Fingerprint, cert);
        }
        out = new FileOutputStream(keyStorePath + Constants.APPMANAGER_KEYSTORE_FILE);
        keyStore.store(new BufferedOutputStream(out), Constants.APPMANAGER_KEYSTORE_PASSWORD);
    } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) {
        logger.error(Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"), e);
        throw new SWMgrCollectorInternalException(e, Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"));
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.warn("Output stream of appmanagers.jks close failed.");
            }
        }
    }
}

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

/**
 * Load one or more certificates from the specified stream.
 *
 * @param is//from w w  w.ja  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:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * Load one or more certificates from the specified stream.
 *
 * @param is//from  w ww. ja  v a2  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, "GNU-PKI");

        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 ex) {
        throw new CryptoException(res.getString("NoLoadCertificate.exception.message"), ex);
    } catch (NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoLoadCertificate.exception.message"), e);
    } 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.eclipse.che.ide.ext.datasource.server.ssl.TrustStoreObject.java

public void addNewServerCACert(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    Certificate[] certs = null;/*from ww  w . j  av  a2s. co m*/
    while (uploadedFilesIterator.hasNext()) {
        FileItem fileItem = uploadedFilesIterator.next();
        if (!fileItem.isFormField()) {
            if ("certFile".equals(fileItem.getFieldName())) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
            }
        }
    }

    if (certs == null) {
        throw new WebApplicationException(
                Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setCertificateEntry(alias, certs[0]);
    save();
}

From source file:com.axway.ebxml.CertificateChain.java

/**
 * Constructor//from  w  ww  . ja  v  a2  s .  c o  m
 * @param certificatePath path to a p7b or DER encoded file
 * @return Array of X509Certificate
 * @throws java.io.FileNotFoundException
 * @throws java.security.cert.CertificateException
 */
public CertificateChain(String certificatePath) throws CertificateException, IOException {
    if (certificatePath == null)
        throw new IllegalArgumentException("certificatePath expected");

    logger.debug("Loading certificate from: " + certificatePath);

    LinkedList<X509Certificate> returnList = new LinkedList<X509Certificate>();
    FileInputStream fis = new FileInputStream(certificatePath);
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection certificates = cf.generateCertificates(fis);
        for (Object cert : certificates) {
            returnList.add((X509Certificate) cert);
            logger.debug("Certificate: " + cert);
        }
    } finally {
        fis.close();
    }

    chain = returnList.toArray(new X509Certificate[returnList.size()]);
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void importMetaData(KeyStore ks, EntityDescriptor ed, IDPSSODescriptor idp,
        AuthMechType currentMechanism, HashMap<String, ParamType> params)
        throws Base64DecodingException, CertificateException, KeyStoreException {
    setProperty("entityID", ed.getEntityID(), params, currentMechanism);
    setProperty("entityID", ed.getEntityID(), params, currentMechanism);

    for (SingleSignOnService sso : idp.getSingleSignOnServices()) {
        if (sso.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) {
            setProperty("idpURL", sso.getLocation(), params, currentMechanism);

        } else if (sso.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")) {

            setProperty("idpRedirURL", sso.getLocation(), params, currentMechanism);
        }/*from   w w w. ja v a  2  s  . c om*/
    }

    for (SingleLogoutService slo : idp.getSingleLogoutServices()) {
        if (slo.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")) {

            setProperty("idpRedirLogoutURL", slo.getLocation(), params, currentMechanism);
        }
    }

    for (KeyDescriptor kd : idp.getKeyDescriptors()) {

        if (kd.getUse().equals(UsageType.SIGNING)) {
            String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
            String name = "verify-" + ed.getEntityID() + "-idp-sig";

            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> c = cf.generateCertificates(bais);

            if (c.size() > 1) {
                int j = 0;
                Iterator<? extends Certificate> i = c.iterator();
                while (i.hasNext()) {
                    Certificate certificate = (Certificate) i.next();
                    ks.setCertificateEntry(name + "-" + j, certificate);
                }
            } else {
                ks.setCertificateEntry(name, c.iterator().next());
            }

            setProperty("idpSigKeyName", name, params, currentMechanism);

        }

    }
}

From source file:net.sf.taverna.cagrid.activity.CaGridActivity.java

/**
 * Load the trusted caGrid CAs' certificates and store them in 
 * the Truststore and in a special folder (inside Taverna's security 
 * conf folder) so that globus can look them up as well.
 *//*from w  ww  .jav  a 2  s  .co  m*/
private static void loadCaGridCAsCertificates() {

    // If not already done, import the caGrid Trusted CAs' certificates into Taverna's truststore
    // Get the location of Taverna's security configuration directory
    File secConfigDirectory = CMUtil.getSecurityConfigurationDirectory();
    File caGridSecConfigDirectory = new File(secConfigDirectory, "cagrid");
    caGridSecConfigDirectory.mkdirs();
    // Tructes CAs folder
    File trustedCertsDirectory = new File(caGridSecConfigDirectory, "trusted-certificates");
    trustedCertsDirectory.mkdirs();

    // Set the system property read by Globus to determine the location 
    // of the folder containing the caGrid trusted CAs' certificates 
    System.setProperty("X509_CERT_DIR", trustedCertsDirectory.getAbsolutePath());

    // Get the file which existence implies that caGrid trusted CAs have been loaded
    File caCertsLoadedFile = new File(caGridSecConfigDirectory, "trustedCAsLoaded.txt");

    if (!caCertsLoadedFile.exists() || System.getenv("TWS_USER_PROXY") != null) {
        logger.info("caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager.");

        if (System.getenv("TWS_USER_PROXY") == null) {
            JOptionPane.showMessageDialog(null,
                    "caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager.",
                    "CaGrid plugin message", JOptionPane.INFORMATION_MESSAGE);
        }
        List<String> certificateResources = new ArrayList<String>();
        certificateResources.add("1c3f2ca8.0");
        certificateResources.add("62f4fd66.0");
        certificateResources.add("68907d53.0");
        certificateResources.add("8e3e7e54.0");
        certificateResources.add("d1b603c3.0");
        certificateResources.add("ed524cf5.0");
        certificateResources.add("0ad31d10.0");
        certificateResources.add("17e36bb5.0");
        certificateResources.add("f3b3491b.0");
        certificateResources.add("d0b62510.0");//to be replaced by its CA cert

        CredentialManager cm = null;
        try {
            //TODO something wrong here, needs correction
            cm = CredentialManager.getInstance();

        } catch (CMException cmex) {
            // We are in deep trouble here - something's wrong with Credential Manager
            String exMessage = "Failed to instantiate Credential Manager - cannot load caGrid CAs' certificates.";
            JOptionPane.showMessageDialog(null, exMessage, "CaGrid plugin message", JOptionPane.ERROR_MESSAGE);
            cmex.printStackTrace();
            logger.error(exMessage);
            return;
        }

        for (String certificate : certificateResources) {
            InputStream certStream = null;
            try {
                String certificateResourcePath = "/trusted-certificates/" + certificate;
                certStream = CaGridActivity.class.getResourceAsStream(certificateResourcePath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                // The following should be able to load PKCS #7 certificate chain files
                // as well as ASN.1 DER or PEM-encoded (sequences of) certificates
                Collection<? extends Certificate> chain = cf.generateCertificates(certStream);
                certStream.close();
                // Use only the first cert in the chain - we know there will be only one inside 
                X509Certificate cert = (X509Certificate) chain.iterator().next();
                // Save to Credential Manager's Truststore
                cm.saveTrustedCertificate(cert);
                // Save to the trusted-certificates directory inside cagrid security conf directory
                File certificateFile = new File(trustedCertsDirectory, certificate);
                InputStream certStreamNew = null;
                BufferedOutputStream fOut = null;
                try {
                    // Reload the certificate resource
                    certStreamNew = CaGridActivity.class.getResourceAsStream(certificateResourcePath);
                    fOut = new BufferedOutputStream(new FileOutputStream(certificateFile));
                    IOUtils.copy(certStreamNew, fOut);
                } catch (Exception ex) {
                    String exMessage = "Failed to save caGrid CA's certificate " + certificate
                            + " to cagrid security folder " + certificateFile + " for globus.";
                    logger.error(exMessage, ex);
                } finally {
                    if (fOut != null) {
                        try {
                            fOut.close();
                        } catch (Exception ex) {
                            logger.error("Can't close certificate resource " + certificateFile, ex);
                        }
                    }
                    if (certStreamNew != null) {
                        try {
                            certStreamNew.close();
                        } catch (Exception ex) {
                            logger.error("Can't close certificate resource " + certificate, ex);
                        }
                    }
                }
            } catch (Exception ex) {
                String exMessage = "Failed to load or save caGrid CA's certificate " + certificate
                        + " to Truststore.";
                logger.error(exMessage, ex);
            }
        }
        Writer out = null;
        try {
            out = new BufferedWriter(new FileWriter(caCertsLoadedFile));
            out.write("true"); // just write anything to the file
        } catch (IOException e) {
            // ignore
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception ex) {
                // ignore
            }
        }
    }
}

From source file:org.apache.kerby.pkix.PkiLoader.java

public List<Certificate> loadCerts(InputStream inputStream) throws IOException {
    CertificateFactory certFactory = null;
    try {//from w w w  .  ja va2 s . c om
        certFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certs = certFactory.generateCertificates(inputStream);
        return new ArrayList<>(certs);
    } catch (CertificateException e) {
        throw new IOException("Failed to load certificates", e);
    }
}