Java Code Examples for java.security.cert.CertStore#getInstance()

The following examples show how to use java.security.cert.CertStore#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: URICertStore.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a URICertStore.
 *
 * @param parameters specifying the URI
 */
URICertStore(CertStoreParameters params)
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
    super(params);
    if (!(params instanceof URICertStoreParameters)) {
        throw new InvalidAlgorithmParameterException
            ("params must be instanceof URICertStoreParameters");
    }
    this.uri = ((URICertStoreParameters) params).getURI();
    // if ldap URI, use an LDAPCertStore to fetch certs and CRLs
    if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) {
        ldap = true;
        ldapCertStore = CertStore.getInstance("LDAP", params);
    }
    try {
        factory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException();
    }
}
 
Example 2
Source File: ClientTrustManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public ClientTrustManager(KeyStore trustTrust) {
    super();
    this.trustStore = trustTrust;

    //Note: A reference of the Collection is used in the CertStore, so we can add CRL's 
    // after creating the CertStore.
    crls = new ArrayList<>();
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(crls);
    
    try {
        crlStore = CertStore.getInstance("Collection", params);
    }
    catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException ex) {
        Log.warn("ClientTrustManager: ",ex);
    }

    loadCRL();
   
}
 
Example 3
Source File: TrustServiceStatusListSignatureVerifier.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static CertStore getCertStore() throws Exception {
   ArrayList certsAndCrls = new ArrayList();

   try {
      ConfigValidator config = ConfigFactory.getConfigValidator();
      KeyStore tslStore = KeyStore.getInstance(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.type", "JKS"));
      tslStore.load(ConnectorIOUtils.getResourceAsStream(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.location")), config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.pwd", "").toCharArray());
      Enumeration aliases = tslStore.aliases();

      while(aliases.hasMoreElements()) {
         String alias = (String)aliases.nextElement();
         X509Certificate cert = (X509Certificate)tslStore.getCertificate(alias);
         LOG.debug("Adding " + cert.getSubjectX500Principal().getName("RFC1779"));
         certsAndCrls.add(cert);
      }
   } catch (Exception var6) {
      LOG.error("Error while loading keystore", var6);
   }

   return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certsAndCrls));
}
 
Example 4
Source File: TrustServiceStatusListSignatureVerifier.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static CertStore getCertStore() throws Exception {
   ArrayList certsAndCrls = new ArrayList();

   try {
      ConfigValidator config = ConfigFactory.getConfigValidator();
      KeyStore tslStore = KeyStore.getInstance(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.type", "JKS"));
      tslStore.load(ConnectorIOUtils.getResourceAsStream(config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.location")), config.getProperty("be.fgov.ehealth.technicalconnector.bootstrap.tsl.keystore.pwd", "").toCharArray());
      Enumeration aliases = tslStore.aliases();

      while(aliases.hasMoreElements()) {
         String alias = (String)aliases.nextElement();
         X509Certificate cert = (X509Certificate)tslStore.getCertificate(alias);
         LOG.debug("Adding " + cert.getSubjectX500Principal().getName("RFC1779"));
         certsAndCrls.add(cert);
      }
   } catch (Exception var6) {
      LOG.error("Error while loading keystore", var6);
   }

   return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certsAndCrls));
}
 
Example 5
Source File: URICertStore.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a URICertStore.
 *
 * @param parameters specifying the URI
 */
URICertStore(CertStoreParameters params)
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
    super(params);
    if (!(params instanceof URICertStoreParameters)) {
        throw new InvalidAlgorithmParameterException
            ("params must be instanceof URICertStoreParameters");
    }
    this.uri = ((URICertStoreParameters) params).getURI();
    // if ldap URI, use an LDAPCertStore to fetch certs and CRLs
    if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) {
        ldap = true;
        ldapCertStore = CertStore.getInstance("LDAP", params);
    }
    try {
        factory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException();
    }
}
 
Example 6
Source File: CertUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of CRLs from files and create a CertStore from them.
 *
 * @param relPath relative path containing CRLs (must end in file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @return the <code>CertStore</code> created
 * @throws Exception on error
 */
public static CertStore createCRLStore(String relPath, String [] fileNames)
    throws Exception {
    Set<X509CRL> crls = new HashSet<X509CRL>();
    for (int i = 0; i < fileNames.length; i++) {
        crls.add(getCRLFromFile(relPath + fileNames[i]));
    }
    return CertStore.getInstance("Collection",
        new CollectionCertStoreParameters(crls));
}
 
Example 7
Source File: NoExtensions.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 8
Source File: CertUtils.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of certs from files and create a CertStore from them.
 *
 * @param relPath relative path containing certs (must end in
 *    file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @return the <code>CertStore</code> created
 * @throws Exception on error
 */
public static CertStore createStore(String relPath, String [] fileNames)
    throws Exception {
    Set<X509Certificate> certs = new HashSet<X509Certificate>();
    for (int i = 0; i < fileNames.length; i++) {
        certs.add(getCertFromFile(relPath + fileNames[i]));
    }
    return CertStore.getInstance("Collection",
        new CollectionCertStoreParameters(certs));
}
 
Example 9
Source File: BuildEEBasicConstraints.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 10
Source File: CertUtils.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of CRLs from files and create a CertStore from them.
 *
 * @param relPath relative path containing CRLs (must end in file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @return the <code>CertStore</code> created
 * @throws Exception on error
 */
public static CertStore createCRLStore(String relPath, String [] fileNames)
    throws Exception {
    Set<X509CRL> crls = new HashSet<X509CRL>();
    for (int i = 0; i < fileNames.length; i++) {
        crls.add(getCRLFromFile(relPath + fileNames[i]));
    }
    return CertStore.getInstance("Collection",
        new CollectionCertStoreParameters(crls));
}
 
Example 11
Source File: NoLDAP.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try {
        Class.forName("javax.naming.ldap.LdapName");
        System.out.println("LDAP is present, test skipped");
        return;
    } catch (ClassNotFoundException ignore) { }

    try {
        CertStore.getInstance("LDAP", new LDAPCertStoreParameters());
        throw new RuntimeException("NoSuchAlgorithmException expected");
    } catch (NoSuchAlgorithmException x) {
        System.out.println("NoSuchAlgorithmException thrown as expected");
    }
}
 
Example 12
Source File: BuildEEBasicConstraints.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 13
Source File: PathCertificateVerifier.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Attempts to build a certification chain for given certificate to verify
 * it. Relies on a set of root CA certificates (trust anchors) and a set of
 * intermediate certificates (to be used as part of the chain).
 */
private PKIXCertPathBuilderResult verifyCertificate(X509Certificate certificate, Set<X509Certificate> trustedRootCerts, Set<X509Certificate> intermediateCerts)
		throws GeneralSecurityException {

	// Create the selector that specifies the starting certificate
	X509CertSelector selector = new X509CertSelector();
	selector.setBasicConstraints(-2);
	selector.setCertificate(certificate);

	// Create the trust anchors (set of root CA certificates)
	Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
	for (X509Certificate trustedRootCert : trustedRootCerts) {
		trustAnchors.add(new TrustAnchor(trustedRootCert, null));
	}

	// Configure the PKIX certificate builder algorithm parameters
	PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);

	// Turn off default revocation-checking mechanism
	pkixParams.setRevocationEnabled(false);

	// Specify a list of intermediate certificates
	CertStore intermediateCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts));
	pkixParams.addCertStore(intermediateCertStore);

	// Build and verify the certification chain
	CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
	PKIXCertPathBuilderResult certPathBuilderResult = (PKIXCertPathBuilderResult) builder.build(pkixParams);

	// Additional check to Verify cert path
	CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
	PKIXCertPathValidatorResult certPathValidationResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPathBuilderResult.getCertPath(), pkixParams);

	return certPathBuilderResult;
}
 
Example 14
Source File: CertUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of certs from files and create a CertStore from them.
 *
 * @param relPath relative path containing certs (must end in
 *    file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @return the <code>CertStore</code> created
 * @throws Exception on error
 */
public static CertStore createStore(String relPath, String [] fileNames)
    throws Exception {
    Set<X509Certificate> certs = new HashSet<X509Certificate>();
    for (int i = 0; i < fileNames.length; i++) {
        certs.add(getCertFromFile(relPath + fileNames[i]));
    }
    return CertStore.getInstance("Collection",
        new CollectionCertStoreParameters(certs));
}
 
Example 15
Source File: NoLDAP.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try {
        Class.forName("javax.naming.ldap.LdapName");
        System.out.println("LDAP is present, test skipped");
        return;
    } catch (ClassNotFoundException ignore) { }

    try {
        CertStore.getInstance("LDAP", new LDAPCertStoreParameters());
        throw new RuntimeException("NoSuchAlgorithmException expected");
    } catch (NoSuchAlgorithmException x) {
        System.out.println("NoSuchAlgorithmException thrown as expected");
    }
}
 
Example 16
Source File: BuildEEBasicConstraints.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 17
Source File: CertUtils.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of certs from files and create a CertStore from them.
 *
 * @param relPath relative path containing certs (must end in
 *    file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @return the <code>CertStore</code> created
 * @throws Exception on error
 */
public static CertStore createStore(String relPath, String [] fileNames)
    throws Exception {
    Set<X509Certificate> certs = new HashSet<X509Certificate>();
    for (int i = 0; i < fileNames.length; i++) {
        certs.add(getCertFromFile(relPath + fileNames[i]));
    }
    return CertStore.getInstance("Collection",
        new CollectionCertStoreParameters(certs));
}
 
Example 18
Source File: CertUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of CRLs from files and create a CertStore from them.
 *
 * @param relPath relative path containing CRLs (must end in file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @return the <code>CertStore</code> created
 * @throws Exception on error
 */
public static CertStore createCRLStore(String relPath, String [] fileNames)
    throws Exception {
    Set<X509CRL> crls = new HashSet<X509CRL>();
    for (int i = 0; i < fileNames.length; i++) {
        crls.add(getCRLFromFile(relPath + fileNames[i]));
    }
    return CertStore.getInstance("Collection",
        new CollectionCertStoreParameters(crls));
}
 
Example 19
Source File: CertUtils.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a bunch of certs from files and create a CertStore from them.
 *
 * @param relPath relative path containing certs (must end in
 *    file.separator)
 * @param fileNames an array of <code>String</code>s that are file names
 * @return the <code>CertStore</code> created
 * @throws Exception on error
 */
public static CertStore createStore(String relPath, String [] fileNames)
    throws Exception {
    Set<X509Certificate> certs = new HashSet<X509Certificate>();
    for (int i = 0; i < fileNames.length; i++) {
        certs.add(getCertFromFile(relPath + fileNames[i]));
    }
    return CertStore.getInstance("Collection",
        new CollectionCertStoreParameters(certs));
}
 
Example 20
Source File: SparkTrustManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
public Collection<X509CRL> loadCRL(X509Certificate[] chain) throws IOException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, CertStoreException, CRLException, CertificateException {

    // for each certificate in chain
    for (X509Certificate cert : chain) {
        if (cert.getExtensionValue(Extension.cRLDistributionPoints.getId()) != null) {
            ASN1Primitive primitive = JcaX509ExtensionUtils
                    .parseExtensionValue(cert.getExtensionValue(Extension.cRLDistributionPoints.getId()));
            // extract distribution point extension
            CRLDistPoint distPoint = CRLDistPoint.getInstance(primitive);
            DistributionPoint[] dp = distPoint.getDistributionPoints();
            // each distribution point extension can hold number of distribution points
            for (DistributionPoint d : dp) {
                DistributionPointName dpName = d.getDistributionPoint();
                // Look for URIs in fullName
                if (dpName != null && dpName.getType() == DistributionPointName.FULL_NAME) {
                    GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                    // Look for an URI
                    for (GeneralName genName : genNames) {
                        // extract url
                        URL url = new URL(genName.getName().toString());
                        try {
                            // download from Internet to the collection
                            crlCollection.add(downloadCRL(url));
                        } catch (CertificateException | CRLException e) {
                            throw new CRLException("Couldn't download CRL");
                        }
                    }
                }
            }
        } else {
            Log.warning("Certificate " + cert.getSubjectX500Principal().getName().toString() + " have no CRLs");
        }
        // parameters for cert store is collection type, using collection with crl create parameters
        CollectionCertStoreParameters params = new CollectionCertStoreParameters(crlCollection);
        // this parameters are next used for creation of certificate store with crls
        crlStore = CertStore.getInstance("Collection", params);
    }
    return crlCollection;
}