Example usage for java.security.cert CollectionCertStoreParameters CollectionCertStoreParameters

List of usage examples for java.security.cert CollectionCertStoreParameters CollectionCertStoreParameters

Introduction

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

Prototype

public CollectionCertStoreParameters(Collection<?> collection) 

Source Link

Document

Creates an instance of CollectionCertStoreParameters which will allow certificates and CRLs to be retrieved from the specified Collection .

Usage

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Add alternative OCSP signing certs to the give collection.
 * @param certCollection//from www . j a v a 2s. c  o  m
 * @param ocspCollection
 * @throws CertificateRevocationCheckException
 */
private CertStore createCertStoreForRevChecking(Collection<AlternativeOCSP> ocspCollection)
        throws CertificateRevocationCheckException {

    Collection<Object> certCollection = new ArrayList<Object>();
    if (null != ocspCollection) {
        for (AlternativeOCSP altOCSP : ocspCollection) {
            X509Certificate cert = altOCSP.get_responderSigningCert();
            if (null != cert) {
                certCollection.add(cert);
            }
        }
    } else {
        //look for old place
        X509Certificate cert = this.certPolicy.getOCSPResponderSigningCert();
        if (null != cert) {
            certCollection.add(cert);
        }
    }

    try {
        return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCollection));
    } catch (Exception e) {
        throw new CertificateRevocationCheckException("Unable to create cert store." + e.getMessage(), e);
    }
}

From source file:mitm.common.security.certpath.CertPathBuilderTest.java

@Test
public void testBuildPathCRLUnavailableButCRLCheckOff() throws Exception {
    // add roots//  w  w w  . j  a  v  a2 s.co  m
    addCertificates("windows-xp-all-roots.p7b", rootStoreParams.getCertStore());
    addCertificates("mitm-test-root.cer", rootStoreParams.getCertStore());

    addCertificates("windows-xp-all-intermediates.p7b", certStoreParams.getCertStore());
    addCertificates("mitm-test-ca.cer", certStoreParams.getCertStore());
    addCertificates("testCertificates.p7b", certStoreParams.getCertStore());

    trustAnchors = getTrustAnchors();

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("115FD110A82F742D0AE14A71B651962"));
    selector.setIssuer("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL");

    CertificatePathBuilder builder = new PKIXCertificatePathBuilder();

    builder.setTrustAnchors(trustAnchors);
    builder.addCertPathChecker(new SMIMEExtendedKeyUsageCertPathChecker());
    builder.addCertStore(certStore);
    builder.setRevocationEnabled(false);

    CertPathBuilderResult result = builder.buildPath(selector);

    List<? extends Certificate> certificates = result.getCertPath().getCertificates();

    assertEquals(2, certificates.size());

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

    Collection<? extends Certificate> foundCertificates = store.getCertificates(selector);

    assertEquals(1, foundCertificates.size());
}

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Create parameters for CertPathValidator using PKIX algorithm.
 *
 * The parameter object was defined with given trustStore and CRL collection
 * @param trustStore2//from w  w  w  .j av a  2s  .  c  om
 * @return non-null PKIXParameters
 * @throws CertificateRevocationCheckException
 */
private PKIXParameters createPKIXParameters(Collection<Object> crlCollection)
        throws CertificateRevocationCheckException {

    PKIXParameters params = null;
    try {
        Validate.notNull(trustStore, "TrustStore can not be null.");
        params = new PKIXParameters(trustStore);

        if (this.certPolicy.revocationCheckEnabled()) {
            params.setRevocationEnabled(true);
        } else {
            params.setRevocationEnabled(false);
        }
    } catch (KeyStoreException e) {
        throw new CertificateRevocationCheckException(
                "Error creating validator parameters: Please check trust store" + e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateRevocationCheckException("Error creating validator parameters:" + e.getMessage(),
                e);
    } catch (Throwable e) {
        //have this block in case a new type of error was thrown
        throw new CertificateRevocationCheckException("Error creating validator parameters:" + e.getMessage(),
                e);
    }

    if (!crlCollection.isEmpty()) {
        try {
            CertStore crlStore = CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(crlCollection));
            params.addCertStore(crlStore);
        } catch (InvalidAlgorithmParameterException e) {
            throw new CertificateRevocationCheckException(
                    "Error adding CRLs to validating parameters:" + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new CertificateRevocationCheckException(
                    "Error adding CRLs to validating parameters:" + e.getMessage(), e);
        }
    } else {
        logger.debug("Revocation check: CRL list empty");
    }

    // setup certificate policy white list

    String[] oidWhiteList = this.certPolicy.getOIDs();

    if (oidWhiteList != null && oidWhiteList.length > 0) {
        Set<String> oidSet = new HashSet<String>();
        for (String oid : oidWhiteList) {
            oidSet.add(oid);
        }
        params.setInitialPolicies(oidSet);
        params.setExplicitPolicyRequired(true);
    }
    return params;

}

From source file:com.verisign.epp.codec.launch.EPPLaunchTst.java

/**
 * Loads the trust store file and the Certificate Revocation List (CRL) file
 * into the <code>PKIXParameters</code> used to verify the certificate chain
 * and verify the certificate against the CRL. Both the Java Trust Store is
 * loaded with the trusted root CA certificates (trust anchors) and the CRL
 * file is attempted to be loaded to identify the revoked certificates. If
 * the CRL file is not found, then no CRL checking will be done.
 * /*  w w w. j a v  a 2s .c  o  m*/
 * @param aTrustStoreName
 *            Trust store file name
 * @param aCrls
 *            List of Certificate Revocation List (CRL) file names
 * 
 * @return Initialized <code>PKIXParameters</code> instance.
 * 
 * @throws Exception
 *             Error initializing the PKIX parameters
 */
public static PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);
    PKIXParameters pkixParameters = new PKIXParameters(trustStore);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    Collection crlContentsList = new ArrayList();

    for (String currCrl : aCrls) {
        File crlFile = new File(currCrl);
        if (crlFile.exists()) {
            InputStream inStream = null;

            try {
                inStream = new FileInputStream(currCrl);
                crlContentsList.add(certFactory.generateCRL(inStream));
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            System.err.println("CRL file \"" + currCrl + "\" NOT found.");
        }

    }

    // At least 1 CRL was loaded
    if (crlContentsList.size() != 0) {

        List<CertStore> certStores = new ArrayList<CertStore>();
        certStores.add(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlContentsList)));

        pkixParameters.setCertStores(certStores);
        pkixParameters.setRevocationEnabled(true);
        System.out.println("Revocation enabled");
    } else {
        pkixParameters.setRevocationEnabled(false);
        System.out.println("Revocation disabled.");

    }

    return pkixParameters;
}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);/*from  w  w w  . j a  va2 s .  c  o  m*/

    for (Certificate c : certs) {
        if (!(c instanceof X509Certificate))
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

        X509Certificate xCert = (X509Certificate) c;

        Principal subject = xCert.getSubjectDN();
        Principal issuer = xCert.getIssuerDN();

        anchors.add(new TrustAnchor(xCert, null));
    }

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java

private void validateChain(final List<Certificate> chain, final Certificate cert) {

    final List<Certificate> certs = new ArrayList<Certificate>();
    final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);/*from w w w. j  a v a 2s  . co  m*/

    for (final Certificate c : certs) {
        if (!(c instanceof X509Certificate)) {
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");
        }
        final X509Certificate xCert = (X509Certificate) c;
        anchors.add(new TrustAnchor(xCert, null));
    }

    final X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);

    } catch (final InvalidAlgorithmParameterException | CertPathBuilderException | NoSuchAlgorithmException e) {
        throw new IllegalStateException("Invalid certificate chain", e);
    } catch (final NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

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

/**
 * Certificate Path Validation process/*  ww  w .j  a v  a  2s .  co  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);
    }
}

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

/**
 * Certificate Path Validation process//w w  w. j  a  va2 s.co  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.apache.ws.security.components.crypto.Merlin.java

public void loadProperties(Properties properties, ClassLoader loader) throws CredentialException, IOException {
    if (properties == null) {
        return;//w w  w. j  a va  2 s  .  com
    }
    this.properties = properties;
    //
    // Load the provider(s)
    //
    String provider = properties.getProperty(CRYPTO_KEYSTORE_PROVIDER);
    if (provider != null) {
        provider = provider.trim();
    }
    String certProvider = properties.getProperty(CRYPTO_CERT_PROVIDER);
    if (certProvider != null) {
        setCryptoProvider(certProvider);
    }
    //
    // Load the KeyStore
    //
    String alias = properties.getProperty(KEYSTORE_ALIAS);
    if (alias != null) {
        alias = alias.trim();
        defaultAlias = alias;
    }
    String keyStoreLocation = properties.getProperty(KEYSTORE_FILE);
    if (keyStoreLocation == null) {
        keyStoreLocation = properties.getProperty(OLD_KEYSTORE_FILE);
    }
    if (keyStoreLocation != null) {
        keyStoreLocation = keyStoreLocation.trim();
        InputStream is = loadInputStream(loader, keyStoreLocation);

        try {
            String passwd = properties.getProperty(KEYSTORE_PASSWORD, "security");
            if (passwd != null) {
                passwd = passwd.trim();
            }
            String type = properties.getProperty(KEYSTORE_TYPE, KeyStore.getDefaultType());
            if (type != null) {
                type = type.trim();
            }
            keystore = load(is, passwd, provider, type);
            if (DO_DEBUG) {
                LOG.debug("The KeyStore " + keyStoreLocation + " of type " + type + " has been loaded");
            }
            String privatePasswd = properties.getProperty(KEYSTORE_PRIVATE_PASSWORD);
            if (privatePasswd != null) {
                privatePasswordSet = true;
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        if (DO_DEBUG) {
            LOG.debug("The KeyStore is not loaded as KEYSTORE_FILE is null");
        }
    }

    //
    // Load the TrustStore
    //
    String trustStoreLocation = properties.getProperty(TRUSTSTORE_FILE);
    if (trustStoreLocation != null) {
        trustStoreLocation = trustStoreLocation.trim();
        InputStream is = loadInputStream(loader, trustStoreLocation);

        try {
            String passwd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
            if (passwd != null) {
                passwd = passwd.trim();
            }
            String type = properties.getProperty(TRUSTSTORE_TYPE, KeyStore.getDefaultType());
            if (type != null) {
                type = type.trim();
            }
            truststore = load(is, passwd, provider, type);
            if (DO_DEBUG) {
                LOG.debug("The TrustStore " + trustStoreLocation + " of type " + type + " has been loaded");
            }
            loadCACerts = false;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        String loadCacerts = properties.getProperty(LOAD_CA_CERTS, "false");
        if (loadCacerts != null) {
            loadCacerts = loadCacerts.trim();
        }
        if (Boolean.valueOf(loadCacerts).booleanValue()) {
            String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
            if (cacertsPath != null) {
                cacertsPath = cacertsPath.trim();
            }
            InputStream is = new FileInputStream(cacertsPath);
            try {
                String cacertsPasswd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
                if (cacertsPasswd != null) {
                    cacertsPasswd = cacertsPasswd.trim();
                }
                truststore = load(is, cacertsPasswd, null, KeyStore.getDefaultType());
                if (DO_DEBUG) {
                    LOG.debug("CA certs have been loaded");
                }
                loadCACerts = true;
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
    }
    //
    // Load the CRL file
    //
    String crlLocation = properties.getProperty(X509_CRL_FILE);
    if (crlLocation != null) {
        crlLocation = crlLocation.trim();
        InputStream is = loadInputStream(loader, crlLocation);

        try {
            CertificateFactory cf = getCertificateFactory();
            X509CRL crl = (X509CRL) cf.generateCRL(is);

            if (provider == null || provider.length() == 0) {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)));
            } else {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)), provider);
            }
            if (DO_DEBUG) {
                LOG.debug("The CRL " + crlLocation + " has been loaded");
            }
        } catch (Exception e) {
            if (DO_DEBUG) {
                LOG.debug(e.getMessage(), e);
            }
            throw new CredentialException(CredentialException.IO_ERROR, "ioError00", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}

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

@Override
public void loadProperties(Properties properties, ClassLoader loader) throws CredentialException, IOException {
    if (properties == null) {
        return;//ww w  .  j a  v a  2 s .c om
    }
    this.properties = properties;
    //
    // Load the provider(s)
    //
    String provider = properties.getProperty(CRYPTO_KEYSTORE_PROVIDER);
    if (provider != null) {
        provider = provider.trim();
    }
    String certProvider = properties.getProperty(CRYPTO_CERT_PROVIDER);
    if (certProvider != null) {
        setCryptoProvider(certProvider);
    }
    //
    // Load the KeyStore
    //
    String alias = properties.getProperty(KEYSTORE_ALIAS);
    if (alias != null) {
        alias = alias.trim();
        defaultAlias = alias;
    }
    String keyStoreLocation = properties.getProperty(KEYSTORE_FILE);
    if (keyStoreLocation == null) {
        keyStoreLocation = properties.getProperty(OLD_KEYSTORE_FILE);
    }
    String keyStorePassword = properties.getProperty(KEYSTORE_PASSWORD, "security");
    if (keyStorePassword != null) {
        keyStorePassword = keyStorePassword.trim();
    }
    String keyStoreType = properties.getProperty(KEYSTORE_TYPE, KeyStore.getDefaultType());
    if (keyStoreType != null) {
        keyStoreType = keyStoreType.trim();
    }
    if (keyStoreLocation != null) {
        keyStoreLocation = keyStoreLocation.trim();
        InputStream is = loadInputStream(loader, keyStoreLocation);

        try {
            keystore = load(is, keyStorePassword, provider, keyStoreType);
            if (DO_DEBUG) {
                LOG.debug("The KeyStore " + keyStoreLocation + " of type " + keyStoreType + " has been loaded");
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        keystore = load(null, keyStorePassword, provider, keyStoreType);
    }

    //
    // Load the TrustStore
    //
    String trustStorePassword = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
    if (trustStorePassword != null) {
        trustStorePassword = trustStorePassword.trim();
    }
    String trustStoreType = properties.getProperty(TRUSTSTORE_TYPE, KeyStore.getDefaultType());
    if (trustStoreType != null) {
        trustStoreType = trustStoreType.trim();
    }
    String loadCacerts = properties.getProperty(LOAD_CA_CERTS, "false");
    if (loadCacerts != null) {
        loadCacerts = loadCacerts.trim();
    }
    String trustStoreLocation = properties.getProperty(TRUSTSTORE_FILE);
    if (trustStoreLocation != null) {
        trustStoreLocation = trustStoreLocation.trim();
        InputStream is = loadInputStream(loader, trustStoreLocation);

        try {
            truststore = load(is, trustStorePassword, provider, trustStoreType);
            if (DO_DEBUG) {
                LOG.debug("The TrustStore " + trustStoreLocation + " of type " + trustStoreType
                        + " has been loaded");
            }
            loadCACerts = false;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else if (Boolean.valueOf(loadCacerts).booleanValue()) {
        String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
        if (cacertsPath != null) {
            cacertsPath = cacertsPath.trim();
        }
        InputStream is = new FileInputStream(cacertsPath);
        try {
            String cacertsPasswd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
            if (cacertsPasswd != null) {
                cacertsPasswd = cacertsPasswd.trim();
            }
            truststore = load(is, cacertsPasswd, null, KeyStore.getDefaultType());
            if (DO_DEBUG) {
                LOG.debug("CA certs have been loaded");
            }
            loadCACerts = true;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        truststore = load(null, trustStorePassword, provider, trustStoreType);
    }
    //
    // Load the CRL file
    //
    String crlLocation = properties.getProperty(X509_CRL_FILE);
    if (crlLocation != null) {
        crlLocation = crlLocation.trim();
        InputStream is = loadInputStream(loader, crlLocation);

        try {
            CertificateFactory cf = getCertificateFactory();
            X509CRL crl = (X509CRL) cf.generateCRL(is);

            if (provider == null || provider.length() == 0) {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)));
            } else {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)), provider);
            }
            if (DO_DEBUG) {
                LOG.debug("The CRL " + crlLocation + " has been loaded");
            }
        } catch (Exception e) {
            if (DO_DEBUG) {
                LOG.debug(e.getMessage(), e);
            }
            throw new CredentialException(CredentialException.IO_ERROR, "ioError00", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}