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:org.apache.ws.security.components.crypto.CryptoBase.java

/**
 * Singleton certificate factory for this Crypto instance.
 * <p/>//ww  w .j a va2s . c o  m
 *
 * @return Returns a <code>CertificateFactory</code> to construct
 *         X509 certificates
 * @throws org.apache.ws.security.WSSecurityException
 *
 */
public synchronized CertificateFactory getCertificateFactory() throws WSSecurityException {
    String provider = getCryptoProvider();
    String keyStoreProvider = keystore == null ? null : keystore.getProvider().getName();

    //Try to find a CertificateFactory that generates certs that are fully
    //compatible with the certs in the KeyStore  (Sun -> Sun, BC -> BC, etc...)
    CertificateFactory factory = null;
    if (provider != null) {
        factory = (CertificateFactory) certFactMap.get(provider);
    } else if (keyStoreProvider != null) {
        factory = (CertificateFactory) certFactMap.get(mapKeystoreProviderToCertProvider(keyStoreProvider));
        if (factory == null) {
            factory = (CertificateFactory) certFactMap.get(keyStoreProvider);
        }
    } else {
        factory = (CertificateFactory) certFactMap.get("DEFAULT");
    }
    if (factory == null) {
        try {
            if (provider == null || provider.length() == 0) {
                if (keyStoreProvider != null && keyStoreProvider.length() != 0) {
                    try {
                        factory = CertificateFactory.getInstance("X.509",
                                mapKeystoreProviderToCertProvider(keyStoreProvider));
                        certFactMap.put(keyStoreProvider, factory);
                        certFactMap.put(mapKeystoreProviderToCertProvider(keyStoreProvider), factory);
                    } catch (Exception ex) {
                        log.debug(ex);
                        //Ignore, we'll just use the default since they didn't specify one.
                        //Hopefully that will work for them.
                    }
                }
                if (factory == null) {
                    factory = CertificateFactory.getInstance("X.509");
                    certFactMap.put("DEFAULT", factory);
                }
            } else {
                factory = CertificateFactory.getInstance("X.509", provider);
                certFactMap.put(provider, factory);
            }
            certFactMap.put(factory.getProvider().getName(), factory);
        } catch (CertificateException e) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "unsupportedCertType",
                    null, e);
        } catch (NoSuchProviderException e) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "noSecProvider", null,
                    e);
        }
    }
    return factory;
}

From source file:no.digipost.api.client.filters.response.ResponseSignatureFilter.java

public X509Certificate lastSertifikat() {
    try {//from ww  w  . jav a 2s  .c om
        InputStream certStream = new ByteArrayInputStream(
                apiService.getEntryPoint().getCertificate().getBytes());

        CertificateFactory cf = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
        X509Certificate sertifikat = (X509Certificate) cf.generateCertificate(certStream);
        if (sertifikat == null) {
            throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                    "Kunne ikke laste Digipost's public key - server-signatur kunne ikke sjekkes");
        }
        return sertifikat;
    } catch (GeneralSecurityException e) {
        throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                "Kunne ikke laste Digiposts public key - server-signatur kunne ikke sjekkes");
    }
}

From source file:org.qipki.ca.http.presentation.rest.resources.tools.CryptoInspectorResource.java

private boolean isDER(InputStream stream) {
    CertificateFactory certFactory = null;
    try {/*from   w  w  w .  j  av  a2s. c  o m*/
        certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
    } catch (GeneralSecurityException ignored) {
        return false;
    }
    try {
        certFactory.generateCRLs(stream);
        return true;
    } catch (CRLException ignored) {
    }
    try {
        certFactory.generateCertificates(stream);
        return true;
    } catch (CertificateException ignored) {
    }
    // TODO : all other types ........
    return false;
}

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 {/*from ww w  .  jav  a 2  s  .com*/
        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:net.shirayu.android.WlanLogin.MyHttpClient.java

public static X509Certificate readPem(InputStream stream)
        throws CertificateException, NoSuchProviderException, IOException {
    CertPath cp;//from   w w w.  j  a  v  a  2s  . com
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        cp = cf.generateCertPath(stream, "PEM");
    } finally {
        stream.close();
    }
    List<? extends Certificate> certs = cp.getCertificates();
    if (certs.size() < 1) {
        throw new CertificateException("Certificate list is empty");
    } else if (certs.size() > 1) {
        throw new CertificateException("Intermediate certificate is not allowed");
    }
    if (certs.get(0) instanceof X509Certificate) {
        X509Certificate cert = (X509Certificate) certs.get(0);
        cert.checkValidity();
        return cert;
    } else {
        throw new CertificateException("Certificate is not X509Certificate");
    }
}

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

private static X509Certificate[] loadCertificatesPkiPath(InputStream is) throws CryptoException {
    try {/*  w ww  .  ja v a2 s .c  om*/
        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce());
        CertPath certPath = cf.generateCertPath(is, PKI_PATH_ENCODING);

        List<? extends Certificate> certs = certPath.getCertificates();

        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 (CertificateException e) {
        throw new CryptoException(res.getString("NoLoadPkiPath.exception.message"), e);
    } catch (NoSuchProviderException e) {
        throw new CryptoException(res.getString("NoLoadPkiPath.exception.message"), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.apache.ws.security.components.crypto.CryptoProviderTest.java

/**
 * Test loading a certificate using BouncyCastle, and using it to encrypt a message, but
 * decrypt the message using the Java Keystore provider. In this case though the cert doesn't
 * correspond with the cert in wss86.keystore.
 *///from  w w w.  j a v  a 2  s.c  om
@org.junit.Test
public void testBadInterop() throws Exception {
    byte[] certBytes = org.apache.ws.security.util.Base64
            .decode("MIIDNDCCAp2gAwIBAgIBEDANBgkqhkiG9w0BAQQFADBmMQswCQYDVQQGEwJERTEPMA0GA1UECBMG"
                    + "QmF5ZXJuMQ8wDQYDVQQHEwZNdW5pY2gxDTALBgNVBAoTBEhvbWUxFTATBgNVBAsTDEFwYWNoZSBX"
                    + "U1M0SjEPMA0GA1UEAxMGV2VybmVyMB4XDTA4MDQwNDE5MzIxOFoXDTEwMDQwNDE5MzIxOFowYTEL"
                    + "MAkGA1UEBhMCREUxDzANBgNVBAgTBkJheWVybjEPMA0GA1UEBxMGTXVuaWNoMQ8wDQYDVQQKEwZB"
                    + "cGFjaGUxDjAMBgNVBAsTBVdTUzRKMQ8wDQYDVQQDEwZXZXJuZXIwgZ8wDQYJKoZIhvcNAQEBBQAD"
                    + "gY0AMIGJAoGBAINlL3/k0H/zvknpBtLo8jzXwx/IJU/CGSv6MsqJZ2fyZ6kpLlXCuSBUZ/tfkdxp"
                    + "uzhYq/Sc7A8csIk9gDf9RUbrhK0qKw0VP6DoCIJjS5IeN+NeJkx8YjmzLPmZqLYbNPXr/hy8CRrR"
                    + "6CqLTTSkBwoEJ+cDkfZrdH2/bND0FEIZAgMBAAGjgfYwgfMwCQYDVR0TBAIwADAsBglghkgBhvhC"
                    + "AQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFFSZXv0I5bG7XPEw"
                    + "jylwG3lmZGdiMIGYBgNVHSMEgZAwgY2AFL/FsHHolGIMacU1TZW/88Bd2EL6oWqkaDBmMQswCQYD"
                    + "VQQGEwJERTEPMA0GA1UECBMGQmF5ZXJuMQ8wDQYDVQQHEwZNdW5pY2gxDTALBgNVBAoTBEhvbWUx"
                    + "FTATBgNVBAsTDEFwYWNoZSBXU1M0SjEPMA0GA1UEAxMGV2VybmVyggkAuBIOAWJ19mwwDQYJKoZI"
                    + "hvcNAQEEBQADgYEAUiUh/wORVcQYXxIh13h3w2Btg6Kj2g6V6YO0Utc/gEYWwT310C2OuroKAwwo"
                    + "HapMIIWiJRclIAiA8Hnb0Sv/puuHYD4G4NWFdiVjRord90eZJe40NMGruRmlqIRIGGKCv+wv3E6U"
                    + "x1cWW862f5H9Eyrcocke2P+3GNAGy83vghA=");
    CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new java.io.ByteArrayInputStream(certBytes));

    WSSecEncrypt encrypt = new WSSecEncrypt();
    encrypt.setUseThisCert(cert);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document encryptedDoc = encrypt.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }
    try {
        verify(encryptedDoc);
        fail("Failure expected on encryption with a key that does not exist in the keystore");
    } catch (Exception ex) {
        // expected
    }

}

From source file:be.fedict.trust.service.bean.HarvesterMDB.java

private void processHarvestMessage(HarvestMessage harvestMessage) {
    if (null == harvestMessage) {
        return;/*from   ww w. ja va 2 s. c om*/
    }
    String caName = harvestMessage.getCaName();
    boolean update = harvestMessage.isUpdate();
    String crlFilePath = harvestMessage.getCrlFile();
    File crlFile = new File(crlFilePath);

    LOG.debug("processHarvestMessage - Don't have CA's Serial Number??");
    LOG.debug("issuer: " + caName);
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(caName);
    if (null == certificateAuthority) {
        LOG.error("unknown certificate authority: " + caName);
        deleteCrlFile(crlFile);
        return;
    }
    if (!update && Status.PROCESSING != certificateAuthority.getStatus()) {
        /*
         * Possible that another harvester instance already activated or is
         * processing the CA cache in the meanwhile.
         */
        LOG.debug("CA status not marked for processing");
        deleteCrlFile(crlFile);
        return;
    }

    Date validationDate = new Date();

    X509Certificate issuerCertificate = certificateAuthority.getCertificate();

    Date notAfter = issuerCertificate.getNotAfter();
    if (validationDate.after(notAfter)) {
        LOG.info("will not update CRL cache for expired CA: " + issuerCertificate.getSubjectX500Principal());
        deleteCrlFile(crlFile);
        return;
    }

    FileInputStream crlInputStream;
    try {
        crlInputStream = new FileInputStream(crlFile);
    } catch (FileNotFoundException e) {
        LOG.error("CRL file does not exist: " + crlFilePath);
        return;
    }
    X509CRL crl;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
        crl = (X509CRL) certificateFactory.generateCRL(crlInputStream);
    } catch (Exception e) {
        LOG.error("BC error: " + e.getMessage(), e);
        deleteCrlFile(crlFile);
        return;
    }

    LOG.debug("checking integrity CRL...");
    boolean crlValid = CrlTrustLinker.checkCrlIntegrity(crl, issuerCertificate, validationDate);
    if (!crlValid) {
        this.auditDAO.logAudit("Invalid CRL for CA=" + caName);
        deleteCrlFile(crlFile);
        return;
    }
    BigInteger crlNumber = getCrlNumber(crl);
    LOG.debug("CRL number: " + crlNumber);

    BigInteger currentCrlNumber = this.certificateAuthorityDAO.findCrlNumber(caName);
    if (null != currentCrlNumber) {
        LOG.debug("CRL number in database: " + currentCrlNumber);
    }
    if (null != currentCrlNumber && currentCrlNumber.compareTo(crlNumber) >= 0
            && certificateAuthority.getStatus() == Status.ACTIVE) {
        // current CRL cache is higher or equal, no update needed
        LOG.debug("current CA cache is new enough.");
        deleteCrlFile(crlFile);
        return;
    }

    List<RevokedCertificateEntity> revokedCertificateEntities = this.certificateAuthorityDAO
            .getRevokedCertificates(caName);
    LOG.debug("number of revoked certificates in database: " + revokedCertificateEntities.size());
    Map<String, RevokedCertificateEntity> revokedCertificatesMap = new HashMap<String, RevokedCertificateEntity>();
    for (RevokedCertificateEntity revokedCertificateEntity : revokedCertificateEntities) {
        String serialNumber = revokedCertificateEntity.getPk().getSerialNumber();
        revokedCertificatesMap.put(serialNumber, revokedCertificateEntity);
    }

    LOG.debug("processing CRL... " + caName);
    boolean isIndirect;
    Enumeration revokedCertificatesEnum;
    try {
        isIndirect = isIndirectCRL(crl);
        revokedCertificatesEnum = getRevokedCertificatesEnum(crl);
    } catch (Exception e) {
        this.auditDAO.logAudit("Failed to parse CRL for CA=" + caName);
        this.failures++;
        throw new RuntimeException(e);
    }

    int entries = 0;
    if (revokedCertificatesEnum.hasMoreElements()) {
        /*
         * Split up persisting the crl entries to avoid memory issues.
         */
        Set<X509CRLEntry> revokedCertsBatch = new HashSet<X509CRLEntry>();
        X500Principal previousCertificateIssuer = crl.getIssuerX500Principal();
        int added = 0;
        while (revokedCertificatesEnum.hasMoreElements()) {

            TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) revokedCertificatesEnum.nextElement();
            X500Name x500name = new X500Name(previousCertificateIssuer.getName(X500Principal.RFC1779));
            X509CRLEntryObject revokedCertificate = new X509CRLEntryObject(entry, isIndirect, x500name);
            previousCertificateIssuer = revokedCertificate.getCertificateIssuer();

            revokedCertsBatch.add(revokedCertificate);
            added++;
            if (added == BATCH_SIZE) {
                /*
                 * Persist batch
                 */
                this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                        crl.getIssuerX500Principal(), revokedCertificatesMap);
                entries += revokedCertsBatch.size();
                revokedCertsBatch.clear();
                added = 0;
            }
        }
        /*
         * Persist final batch
         */
        this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                crl.getIssuerX500Principal(), revokedCertificatesMap);
        entries += revokedCertsBatch.size();

        /*
         * Cleanup redundant CRL entries
         */
        if (null != crlNumber) {
            this.certificateAuthorityDAO.removeOldRevokedCertificates(crlNumber,
                    crl.getIssuerX500Principal().toString());
        }
    }

    deleteCrlFile(crlFile);

    LOG.debug("CRL this update: " + crl.getThisUpdate());
    LOG.debug("CRL next update: " + crl.getNextUpdate());
    certificateAuthority.setStatus(Status.ACTIVE);
    certificateAuthority.setThisUpdate(crl.getThisUpdate());
    certificateAuthority.setNextUpdate(crl.getNextUpdate());
    LOG.debug("cache activated for CA: " + crl.getIssuerX500Principal() + " (entries=" + entries + ")");
}

From source file:org.ejbca.extra.db.ExtRAMsgHelper.java

/**
 * Method used to verify signed data.// ww w  .  j  a  v  a 2s .co  m
 * 
 * @param TrustedCACerts a Collection of trusted certificates, should contain the entire chains
 * @param TrustedCRLs a Collection of trusted CRLS, use null if no CRL check should be used.
 * @param signedData the data to verify
 * @param date the date used to check the validity against.
 * @return a ParsedSignatureResult.
 */
public static ParsedSignatureResult verifySignature(Collection cACertChain, Collection trustedCRLs,
        byte[] signedData, Date date) {
    boolean verifies = false;
    X509Certificate usercert = null;
    ParsedSignatureResult retval = new ParsedSignatureResult(false, null, null);
    byte[] content = null;

    try {
        // First verify the signature
        CMSSignedData sp = new CMSSignedData(signedData);

        CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = sp.getSignerInfos();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ((CMSProcessableByteArray) sp.getSignedContent()).write(baos);
        content = baos.toByteArray();
        baos.close();

        Collection c = signers.getSigners();
        Iterator it = c.iterator();

        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());

            Iterator certIt = certCollection.iterator();
            usercert = (X509Certificate) certIt.next();

            boolean validalg = signer.getDigestAlgOID().equals(signAlg);

            verifies = validalg && signer.verify(usercert.getPublicKey(), "BC");

        }

        // Second validate the certificate           
        X509Certificate rootCert = null;
        Iterator iter = cACertChain.iterator();
        while (iter.hasNext()) {
            X509Certificate cert = (X509Certificate) iter.next();
            if (cert.getIssuerDN().equals(cert.getSubjectDN())) {
                rootCert = cert;
                break;
            }
        }

        if (rootCert == null) {
            throw new CertPathValidatorException("Error Root CA cert not found in cACertChain");
        }

        List list = new ArrayList();
        list.add(usercert);
        list.add(cACertChain);
        if (trustedCRLs != null) {
            list.add(trustedCRLs);
        }

        CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
        CertStore store = CertStore.getInstance("Collection", ccsp);

        //validating path
        List certchain = new ArrayList();
        certchain.addAll(cACertChain);
        certchain.add(usercert);
        CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);

        Set trust = new HashSet();
        trust.add(new TrustAnchor(rootCert, null));

        CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);
        param.addCertStore(store);
        param.setDate(date);
        if (trustedCRLs == null) {
            param.setRevocationEnabled(false);
        } else {
            param.setRevocationEnabled(true);
        }
        cpv.validate(cp, param);
        retval = new ParsedSignatureResult(verifies, usercert, content);
    } catch (Exception e) {
        log.error("Error verifying data : ", e);
    }

    return retval;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.HopsworksRMAppSecurityActions.java

private void initX509() throws MalformedURLException, GeneralSecurityException {
    signEndpoint = new URL(hopsworksHost, conf.get(YarnConfiguration.HOPS_HOPSWORKS_SIGN_ENDPOINT_KEY,
            YarnConfiguration.DEFAULT_HOPS_HOPSWORKS_SIGN_ENDPOINT));
    revokePath = conf.get(YarnConfiguration.HOPS_HOPSWORKS_REVOKE_ENDPOINT_KEY,
            YarnConfiguration.DEFAULT_HOPS_HOPSWORKS_REVOKE_ENDPOINT);
    if (revokePath.startsWith("/")) {
        revokePath = "%s" + revokePath;
    } else {/* w  w w  . ja v a2s  .  c  o m*/
        revokePath = "%s/" + revokePath;
    }
    certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    x509Configured = true;
}