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:test.integ.be.fedict.trust.TSATest.java

@Test
public void testTSA2014() throws Exception {
    InputStream p7InputStream = TSATest.class.getResourceAsStream("/tsa-2014-chain.der");
    assertNotNull(p7InputStream);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(p7InputStream);
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    LOG.debug("# of certificates: " + certificates.size());
    for (Certificate certificate : certificates) {
        certificateChain.add((X509Certificate) certificate);
    }/*w  ww. j  av a 2 s.  c  o  m*/

    XKMS2Client client = new XKMS2Client("https://www.e-contract.be/eid-trust-service-ws/xkms2");
    client.validate(TrustServiceDomains.BELGIAN_TSA_TRUST_DOMAIN, certificateChain);
}

From source file:test.integ.be.fedict.trust.TSATest.java

@Test
public void testNewTSACertificateChain2012() throws Exception {
    InputStream p7InputStream = TSATest.class.getResourceAsStream("/Fedict2012Chainpub.p7c");
    assertNotNull(p7InputStream);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(p7InputStream);
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    LOG.debug("# of certificates: " + certificates.size());
    for (Certificate certificate : certificates) {
        LOG.debug("certificate: " + certificate);
        certificateChain.add(0, (X509Certificate) certificate);
    }//  w w  w.  ja  v a 2  s .  c  om

    XKMS2Client client = new XKMS2Client("https://www.e-contract.be/eid-trust-service-ws/xkms2");
    client.setProxy("proxy.yourict.net", 8080);
    client.validate(TrustServiceDomains.BELGIAN_TSA_TRUST_DOMAIN, certificateChain);
}

From source file:org.eclipse.che.ide.ext.datasource.server.ssl.KeyStoreObject.java

public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;/* ww w . j ava2 s .  c  om*/
    while (uploadedFilesIterator.hasNext()) {
        FileItem fileItem = uploadedFilesIterator.next();
        if (!fileItem.isFormField()) {
            if ("keyFile".equals(fileItem.getFieldName())) {
                KeyFactory kf = KeyFactory.getInstance("RSA");
                privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
            }
            if ("certFile".equals(fileItem.getFieldName())) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
            }
        }
    }

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

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
}

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

private static void importIdpMetadata(Options options, CommandLine cmd, String unisonXMLFile,
        TremoloType ttRead, TremoloType ttWrite, String ksPath, KeyStore ks)
        throws ParserConfigurationException, SAXException, IOException, FileNotFoundException,
        UnmarshallingException, Exception, Base64DecodingException, CertificateException, KeyStoreException,
        NoSuchAlgorithmException, JAXBException, PropertyException {
    logger.info("Import SP Metadata into the IdP");

    logger.info("Loading Metadata...");
    String metadataFile = loadOption(cmd, "pathToMetaData", options);

    InitializationService.initialize();/*ww  w.  j a  v  a  2 s .com*/

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    DocumentBuilder builder = factory.newDocumentBuilder();

    Element root = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(metadataFile))))
            .getDocumentElement();

    EntityDescriptor ed = (EntityDescriptor) XMLObjectSupport.getUnmarshaller(root).unmarshall(root);

    logger.info("Loading IdP...");
    String idpName = loadOption(cmd, "idpName", options);

    ApplicationType idp = null;

    for (ApplicationType app : ttWrite.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }

    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }

    SPSSODescriptor sp = ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");

    TrustType trust = null;

    trust = new TrustType();

    if (sp.getID() == null) {
        trust.setName(ed.getEntityID());
    } else {
        trust.setName(sp.getID());
    }

    for (AssertionConsumerService svc : sp.getAssertionConsumerServices()) {
        if (svc.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) {
            ParamType pt = new ParamType();
            pt.setName("httpPostRespURL");
            pt.setValue(svc.getLocation());
            trust.getParam().add(pt);
        }
    }

    ParamType pt = new ParamType();
    pt.setName("signAssertion");
    pt.setValue(Boolean.toString(sp.getWantAssertionsSigned().booleanValue()));
    trust.getParam().add(pt);

    if (pt.getValue().equalsIgnoreCase("false")) {

        pt = new ParamType();
        pt.setName("signResponse");
        pt.setValue("true");
        trust.getParam().add(pt);
    } else {
        pt = new ParamType();
        pt.setName("signResponse");
        pt.setValue("false");
        trust.getParam().add(pt);
    }

    boolean first = true;
    for (NameIDFormat nameid : sp.getNameIDFormats()) {
        if (first) {

            pt = new ParamType();
            pt.setName("defaultNameId");
            pt.setValue(nameid.getFormat());
            trust.getParam().add(pt);

            first = false;
        }

        pt = new ParamType();
        pt.setName("nameIdMap");
        pt.setValue(nameid.getFormat() + "=");
        trust.getParam().add(pt);
    }

    boolean encryptAssertion = false;
    boolean signAssertion = false;
    for (KeyDescriptor kd : sp.getKeyDescriptors()) {

        if (kd.getUse().equals(UsageType.SIGNING)) {
            String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
            String name = "verify-" + ed.getEntityID() + "-sp-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());
            }

            pt = new ParamType();
            pt.setName("spSigKey");
            pt.setValue(name);
            trust.getParam().add(pt);

            signAssertion = true;
        }

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

            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());
            }

            pt = new ParamType();
            pt.setName("spEncKey");
            pt.setValue(name);
            trust.getParam().add(pt);

            encryptAssertion = true;
        }
    }

    pt = new ParamType();
    pt.setName("encAssertion");
    pt.setValue(encryptAssertion ? "true" : "false");
    trust.getParam().add(pt);

    if (!signAssertion) {
        pt = new ParamType();
        pt.setName("spSigKey");
        pt.setValue("");
        trust.getParam().add(pt);
    }

    if (!encryptAssertion) {
        pt = new ParamType();
        pt.setName("spEncKey");
        pt.setValue("");
        trust.getParam().add(pt);
    }

    pt = new ParamType();
    pt.setName("defaultAuthCtx");
    pt.setValue("");
    trust.getParam().add(pt);

    TrustType cur = null;
    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        if (trustType.getName().equals(trust.getName())) {
            cur = trustType;
            break;
        }
    }

    if (cur != null) {
        idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().remove(cur);
    }

    idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().add(trust);

    OpenUnisonUtils.storeMethod(unisonXMLFile, ttWrite, ksPath, ks);
}

From source file:net.jsign.PESignerCLI.java

/**
 * Load the certificate chain from the specified PKCS#7 files.
 *//*w ww  . j  ava2 s. c o  m*/
@SuppressWarnings("unchecked")
private Certificate[] loadCertificateChain(File file) throws IOException, CertificateException {
    FileInputStream in = null;
    try {
        in = new FileInputStream(file);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<Certificate> certificates = (Collection<Certificate>) certificateFactory
                .generateCertificates(in);
        return certificates.toArray(new Certificate[certificates.size()]);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

public static X509Certificate[] loadCertificates(InputStream is, String keyStoreType) throws CryptoException {
    byte[] certsBytes = null;
    CertificateFactory cf = null;
    try {/* w w  w. j a va 2s. c  o  m*/
        certsBytes = ReadUtil.readFully(is);

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

        is = new ByteArrayInputStream(certsBytes);

        if (keyStoreType.equals("HTKS")) {
            cf = CertificateFactory.getInstance(X509_CERT_TYPE, "GNU-PKI");
        } else {
            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 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:it.cnr.icar.eric.common.security.X509Parser.java

/**
 * Parses a X509Certificate from a DER formatted input stream. Uses the 
 * BouncyCastle provider if available.//from w  w  w .  j a v a 2 s .  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:at.gv.egiz.pdfas.lib.pki.impl.DefaultCertificateVerificationDataProvider.java

/**
 * Retrieves the chain for a provided end entity certificate.
 * /*from   w  ww  . j av a 2 s  . co m*/
 * @param eeCertificate
 *            The end entity certificate.
 * @param settings
 *            The configuration of the PDF-AS environment (required; must not be {@code null}).
 * @return The CA chain (never {@code null}).
 * @throws IOException
 *             Thrown in case the chain could not be read.
 * @throws CertificateException
 *             Thrown in case of an error parsing the chain.
 * @throws IllegalStateException
 *             In case the {@code eeCertificate}'s chain is not supported. Use
 *             {@link #isSupportedCA(X509Certificate)} in order to assure the CA is supported before calling this
 *             method).
 */
private X509Certificate[] retrieveChain(X509Certificate eeCertificate, ISettings settings)
        throws IOException, CertificateException {

    File certChainFile = findChainFile(eeCertificate, settings);
    if (certChainFile == null) {
        throw new IllegalStateException("Unsupported CA.");
    }

    // load certificate chain
    try (InputStream certChainIn = new FileInputStream(certChainFile)) {
        Collection<? extends Certificate> certificates;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // not guaranteed to be thread-safe
            certificates = certificateFactory.generateCertificates(certChainIn);
        } catch (CertificateException e) {
            // should never occur (therefore not mentioned in javadoc)
            throw new IllegalStateException("X.509 certificates not supported.");
        }
        return Util.convertCertificateChain(certificates.toArray(new Certificate[certificates.size()]));
    }
}

From source file:mobac.mapsources.loader.MapPackManager.java

public MapPackManager(File mapPackDir) throws CertificateException, IOException {
    this.mapPackDir = mapPackDir;
    requiredMapPackVersion = Integer.parseInt(System.getProperty("mobac.mappackversion"));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certs = cf
            .generateCertificates(Utilities.loadResourceAsStream("cert/MapPack.cer"));
    mapPackCert = (X509Certificate) certs.iterator().next();
}