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:MainClass.java

public static void main(String args[]) throws Exception {

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    for (int i = 0; i < args.length; i++) {
        FileInputStream in = new FileInputStream(args[i]);
        Certificate c = cf.generateCertificate(in);
        mylist.add(c);// www  .  ja  va 2 s . com
    }
    CertStoreParameters cparam = new CollectionCertStoreParameters(mylist);
    CertStore cs = CertStore.getInstance("Collection", cparam);
    System.out.println(cs.getCertStoreParameters());
    System.out.println(cs.getProvider());
    System.out.println(cs.getType());

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);//from  w w w.  ja v a 2s.  com

    CertStoreParameters cparam = new CollectionCertStoreParameters(mylist);
    CertStore cs = CertStore.getInstance("Collection", cparam);
    X509CertSelector selec = new X509CertSelector();
    selec.setIssuer("CN=YourName,OU=Network Center," + "O=University,L=ZB,ST=Toronto,C=CN");
    Set clct = (Set) cs.getCertificates(selec);
    Object o[] = clct.toArray();
    for (int i = 0; i < o.length; i++) {
        X509Certificate ct = (X509Certificate) o[i];
        System.out.println("Certificate " + i + " ");
        System.out.println(ct.getSubjectDN());

    }
}

From source file:createSod.java

/**
 * @param args//w  ww .java2  s. c o m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:FileSystemDirectoryCertStore.java

/**
 * Creates a new instance over a directory using the specified extensions
 * @param dirPath the path for the base directory
 * @param certsFilesExts extensions for included certificate files
 * @param crlsFilesExts  extensions for included CRL files
 * @throws CertificateException if there's an error reading the certificates
 * @throws CRLException if there's an error reading the CRLs
 *///from   w  w  w  .  j  a va2s. co m
public FileSystemDirectoryCertStore(String dirPath, final String[] certsFilesExts, final String[] crlsFilesExts)
        throws CertificateException, CRLException {
    File dir = new File(dirPath);
    if (!dir.exists() || !dir.isDirectory())
        throw new IllegalArgumentException("Specified path doesn't exist or doesn't refer a directory");

    Collection contentList = new ArrayList();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    transverseDirToFindContent(dir, contentList, certsFilesExts, crlsFilesExts, cf);

    try {
        this.content = CertStore.getInstance("Collection", new CollectionCertStoreParameters(contentList));
        return;
    } catch (InvalidAlgorithmParameterException ex) {
    } catch (NoSuchAlgorithmException ex) {
    }
    // ToDo: this is a bit ugly!
    throw new CertificateException("Error getting Collection CertStore");
}

From source file:be.apsu.extremon.probes.ocsp.OCSPProbe.java

public OCSPProbe() {
    CertificateFactory certificateFactory = null;

    try {/*from  ww  w. ja va2  s  .  c o m*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException cex) {
        log("Don't Have Crypto Libs:" + cex.getMessage());
        System.exit(1);
    }

    try {
        certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("certificate"))));
        trustAnchorCert = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("trustanchor"))));
    } catch (CertificateException cex) {
        log("certificate and trustanchor required in config:" + cex.getMessage());
        System.exit(2);
    }

    this.delay = confInt("delay", DEFAULT_DELAY);

    try {
        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        certs.add(this.certificate);
        this.certificatePath = (CertPath) certificateFactory.generateCertPath(certs);

        TrustAnchor trustAnchor = new TrustAnchor(this.trustAnchorCert, null);
        Set<TrustAnchor> trustedCertsSet = new HashSet<TrustAnchor>();
        trustedCertsSet.add(trustAnchor);

        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        certSet.add(this.trustAnchorCert);
        CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
        CertStore store = CertStore.getInstance("Collection", storeParams);

        pkixParams = new PKIXParameters(trustedCertsSet);
        pkixParams.addCertStore(store);

        Security.setProperty("ocsp.enable", "true");
        Security.setProperty("ocsp.responderURL", confStr("url"));
        Security.setProperty("ocsp.responderCertSubjectName",
                this.trustAnchorCert.getSubjectX500Principal().getName());

        this.certificatePathValidator = CertPathValidator.getInstance("PKIX");
    } catch (InvalidAlgorithmParameterException iaex) {
        log("Invalid Algorithm Parameter:" + iaex.getMessage());
        System.exit(3);
    } catch (CertificateException cex) {
        log("Certificate Exception:" + cex.getMessage());
        System.exit(4);
    } catch (NoSuchAlgorithmException nsaex) {
        log("No Such Algorithm:" + nsaex.getMessage());
        System.exit(5);
    } catch (Exception ex) {
        log(ex.getMessage());
        System.exit(6);
    }

    start();
    log("Initialized");
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

@Override
public void afterPropertiesSet() throws Exception {
    if (this.keystore == null) {
        this.logger.warn("No S/MIME KeyStore configured. Email update notifications will NOT be signed");
    } else {/*from  w  w  w . j  a va2  s  . c o  m*/
        Security.addProvider(new BouncyCastleProvider());

        final KeyStore signingKeyStore = KeyStore.getInstance("JKS");

        final InputStream keyStoreStream = this.keystore.getInputStream();
        try {
            signingKeyStore.load(keyStoreStream, this.keystorePassword.toCharArray());
        } finally {
            IOUtils.closeQuietly(keyStoreStream);
        }

        final List<Certificate> certList = new ArrayList<Certificate>(1);
        for (final Enumeration<String> aliasesEnum = signingKeyStore.aliases(); aliasesEnum
                .hasMoreElements();) {
            final String alias = aliasesEnum.nextElement();
            final Certificate cert = signingKeyStore.getCertificate(alias);
            if (cert != null) {
                certList.add(cert);
            }
        }

        final PrivateKey signingKey = (PrivateKey) signingKeyStore.getKey(this.certificateAlias,
                this.keystorePassword.toCharArray());
        final X509Certificate signingCert = (X509Certificate) signingKeyStore
                .getCertificate(this.certificateAlias);

        // create a CertStore containing the certificates we want carried
        // in the signature
        final CertStore certsAndcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), "BC");

        // create the generator for creating an smime/signed message
        smimeSignedGenerator = new SMIMESignedGenerator();

        // add a signer to the generator - this specifies we are using SHA1 and
        // adding the smime attributes above to the signed attributes that
        // will be generated as part of the signature. The encryption algorithm
        // used is taken from the key - in this RSA with PKCS1Padding
        smimeSignedGenerator.addSigner(signingKey, signingCert, SMIMESignedGenerator.DIGEST_SHA1);

        // add our pool of certs and cerls (if any) to go with the signature
        smimeSignedGenerator.addCertificatesAndCRLs(certsAndcrls);
    }
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Verify that a given certificate is trusted.
 * /*from w ww.  j  av  a2s  . c o  m*/
 * @param chain certificate chain
 * @throws CertPathBuilderException thrown on verification error
 * @throws CertificateVerificationException thrown on any error
 */
public void verify(X509Certificate[] chain) throws CertificateVerificationException, CertPathBuilderException {
    try {
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(chain[0]);

        // Root certificates
        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
        for (X509Certificate rootCert : rootCerts) {
            trustAnchors.add(new TrustAnchor(rootCert, null));
        }

        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);

        pkixParams.setRevocationEnabled(true);

        // Built-in intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts)));

        // Additional intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain))));

        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
        builder.build(pkixParams); // Will error on failure to verify
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateVerificationException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateVerificationException(e);
    }
}

From source file:com.vmware.identity.idm.IDPConfig.java

/**
 * Validate the chain is in the required order user's certificate first,
 * root CA certificate last including the case of only root CA is present.
 * Also validate that there is only one chain, which consists of all the
 * certificates listed./*from www  . ja v  a2s.c  o  m*/
 */
private static boolean validateSingleX509CertChain(List<X509Certificate> chain)
        throws ExternalIDPExtraneousCertsInCertChainException, ExternalIDPCertChainInvalidTrustedPathException {
    final String ALGO_PKIX = "PKIX"; //for X.509

    final String CERTSTORE_PROVIDER_COLLECTION = "Collection";

    try {
        Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
        anchors.add(new TrustAnchor(chain.get(chain.size() - 1), null));

        X509CertSelector targetCertSelector = new X509CertSelector();
        targetCertSelector.setCertificate(chain.get(0));

        CertStore builderStore = CertStore.getInstance(CERTSTORE_PROVIDER_COLLECTION,
                new CollectionCertStoreParameters(chain));

        PKIXBuilderParameters buildParams = new PKIXBuilderParameters(anchors, targetCertSelector);
        buildParams.addCertStore(builderStore);
        buildParams.setRevocationEnabled(false);

        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(ALGO_PKIX);
        CertPathBuilderResult builderResult = pathBuilder.build(buildParams);

        if (chain.size() - 1 != builderResult.getCertPath().getCertificates().size()) {
            throw new ExternalIDPExtraneousCertsInCertChainException(chain);
        }
        return true;

    } catch (CertPathBuilderException cpbe) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(cpbe.getMessage(), chain); // no need to chain the exception.
    } catch (GeneralSecurityException gse) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(gse.getMessage(), chain);
    }
}

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

/**
 * Create and init PKIXBuilderParameters for CertPathBuilder.
 *
 * @param endCert//www  .  j  a  v a2  s. c  o  m
 *            the target user certificate to use for building certificate
 *            path
 * @return
 * @throws CertificatePathBuildingException
 */
private PKIXBuilderParameters CreatePKIXBuilderParameters(X509Certificate endCert)
        throws CertificatePathBuildingException {
    X509CertSelector targetConstraints = new X509CertSelector();
    targetConstraints.setCertificate(endCert);
    PKIXBuilderParameters params;

    try {
        params = new PKIXBuilderParameters(trustStore, targetConstraints);

        // Do not validate the certificate at cert path building stage.
        // This would result in unknown failures.
        params.setRevocationEnabled(false);
    } catch (KeyStoreException e) {
        throw new CertificatePathBuildingException(
                "Error creating PKIXBuilderParameters: Please check trust store" + e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificatePathBuildingException("Error creating PKIXBuilderParameters:" + e.getMessage(), e);
    } catch (Throwable e) {
        // have this block in case a new type of error was thrown
        throw new CertificatePathBuildingException("Error creating PKIXBuilderParameters:" + e.getMessage(), e);
    }

    Collection<Object> certCollection = new ArrayList<Object>();
    // add trusted CAs to the collection
    addCertificateCandidates(endCert, certCollection);

    if (!certCollection.isEmpty()) {
        try {
            CertStore certStore = CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(certCollection));
            params.addCertStore(certStore);
        } catch (InvalidAlgorithmParameterException e) {
            throw new CertificatePathBuildingException(
                    "Error creating CertStore for PKIXBuilderParameters:" + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new CertificatePathBuildingException(
                    "Error creating CertStore for  PKIXBuilderParameters:" + e.getMessage(), e);
        }
    } else {
        logger.debug("Revocation check: CRL list empty");
    }
    return params;

}

From source file:com.verisign.epp.serverstub.LaunchDomainHandler.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  va 2 s .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
 */
private PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception {
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): enter");

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);
    trustStoreFile.close();
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): truststore = " + aTrustStoreName);
    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 {
                cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): adding CRL " + currCrl);
                inStream = new FileInputStream(currCrl);
                crlContentsList.add(certFactory.generateCRL(inStream));
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            throw new EPPException("CRL file " + currCrl + " does not exist.");
        }

    }

    // 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);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation enabled");
    } else {
        pkixParameters.setRevocationEnabled(false);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation disabled");
    }

    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): exit");
    return pkixParameters;
}