Example usage for org.bouncycastle.cms CMSSignedData getSignerInfos

List of usage examples for org.bouncycastle.cms CMSSignedData getSignerInfos

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedData getSignerInfos.

Prototype

public SignerInformationStore getSignerInfos() 

Source Link

Document

return the collection of signers that are associated with the signatures for the message.

Usage

From source file:eu.europa.esig.dss.cades.signature.CounterSignatureBuilder.java

License:Open Source License

/**
 * This method applies a countersignature to an existing signature
 * @param signedData the countersignature
 * @return the updated signature, in which the countersignature has been embedded
 *///from www  .  j av  a 2s. c o m
public CMSSignedData signDocument(final CMSSignedData signedData) {

    //Retrieve the SignerInformation from the countersigned signature
    final SignerInformationStore originalSignerInfos = cmsSignedData.getSignerInfos();
    //Retrieve the SignerInformation from the countersignature
    final SignerInformationStore signerInfos = signedData.getSignerInfos();

    //Add the countersignature
    SignerInformation updatedSI = cmsSignedData.getSignerInfos().get(selector)
            .addCounterSigners(originalSignerInfos.get(selector), signerInfos);

    //Create updated SignerInformationStore
    Collection<SignerInformation> counterSignatureInformationCollection = new ArrayList<SignerInformation>();
    counterSignatureInformationCollection.add(updatedSI);
    SignerInformationStore signerInformationStore = new SignerInformationStore(
            counterSignatureInformationCollection);

    //Return new, updated signature
    return CMSSignedData.replaceSigners(cmsSignedData, signerInformationStore);
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * Returns the first {@code SignerInformation} extracted from {@code CMSSignedData}.
 *
 * @param cms/*  w  w w .  ja va 2 s . co  m*/
 *            CMSSignedData
 * @return returns {@code SignerInformation}
 */
private static SignerInformation getFirstSignerInformation(final CMSSignedData cms) {
    final Collection<SignerInformation> signers = cms.getSignerInfos().getSigners();
    if (signers.size() > 1) {
        LOG.warn("!!! The framework handles only one signer (SignerInformation) !!!");
    }
    final SignerInformation signerInformation = signers.iterator().next();
    return signerInformation;
}

From source file:fixture.pdfboxeg.CreateSignatureBase.java

License:Apache License

/**
 * We just extend CMS signed Data//from ww  w . j a va2s.  co m
 *
 * @param signedData Generated CMS signed data
 * @return CMSSignedData Extended CMS signed data
 * @throws IOException
 * @throws org.bouncycastle.tsp.TSPException
 */
private CMSSignedData signTimeStamps(CMSSignedData signedData) throws IOException, TSPException {
    SignerInformationStore signerStore = signedData.getSignerInfos();
    List<SignerInformation> newSigners = new ArrayList<>();

    for (SignerInformation signer : signerStore.getSigners()) {
        newSigners.add(signTimeStamp(signer));
    }

    // TODO do we have to return a new store?
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:id.govca.detachedsignature.CMSController.java

public boolean VerifyCMS(CMSSignedData signedData, String content_digest) throws IOException, CMSException,
        CertificateException, OperatorCreationException, UnmatchedSignatureException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        StringFormatException, ParseException, GeneralSecurityException {
    rootCertCandidate = null;/*from w  w  w. j a v a 2 s .c  o m*/

    Security.addProvider(new BouncyCastleProvider());

    byte[] dataku = (byte[]) signedData.getSignedContent().getContent();
    System.out.format("%-32s%s\n", "Base64 of Signed Content", Hex.toHexString(dataku));

    Store store = signedData.getCertificates();

    CertStore certsAndCRLs = new JcaCertStoreBuilder().setProvider("BC")
            .addCertificates(signedData.getCertificates()).build();

    // Verify signature
    SignerInformationStore signers = signedData.getSignerInfos();
    Collection c = signers.getSigners();
    System.out.format("%-32s%s\n", "Number of Signers", c.size());

    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        AttributeTable att = signer.getSignedAttributes();

        Attribute mdAtt = att.get(CMSAttributes.messageDigest);
        ASN1Primitive asp = mdAtt.getAttrValues().getObjectAt(0).toASN1Primitive();
        byte[] hasil = asp.getEncoded("DER");

        System.out.format("%-32s%s\n", "Digest of Signature", Hex.toHexString(hasil));

        Collection certCollection = store.getMatches(signer.getSID());
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC");

        ArrayList<X509CertificateHolder> listCertDatFirm = new ArrayList(store.getMatches(null));
        System.out.format("%-32s%d\n", "Number of cert Holders All", listCertDatFirm.size());

        try {
            verifyChain(listCertDatFirm);
        } catch (CertificateVerificationException ex) {
            System.out.println("CERTIFICATE CHAIN VERIFICATION FAILED");
            Logger.getLogger(CMSController.class.getName()).log(Level.SEVERE, null, ex);
            throw new UnmatchedSignatureException("Certificate Chain verification failed");
        }
        System.out.println("CERTIFICATE CHAIN VERIFIED");

        Collection<X509CertificateHolder> holders = store.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider()).getCertificate(certHolder);

        Principal princ = certFromSignedData.getIssuerDN();

        //Get Signer Name
        Principal p = certFromSignedData.getSubjectDN();
        System.out.format("%-32s%s\n", "Signer Distinguished Name", p.getName());

        this.setDN_fields(StringHelper.DNFieldsMapper(p.getName()));

        //Get Signing Time
        org.bouncycastle.asn1.cms.Attribute signingTime = att
                .get(new ASN1ObjectIdentifier("1.2.840.113549.1.9.5"));
        String asn1time = signingTime.getAttrValues().toString();
        System.out.format("%-32s%s\n", "Signing Time (RAW format)", asn1time);

        Date signtime = StringHelper.ASN1DateParser(asn1time);
        SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
        String formattedDate = formatter.format(signtime);
        System.out.format("%-32s%s\n", "Signing Time (Pretty format)", formattedDate);

        PublicKey pubkey = certFromSignedData.getPublicKey();

        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider())
                .build(certFromSignedData))) {
            System.out.println("SIGNATURE VERIFIED <BY BOUNCY CASTLE STANDARD>");
        } else {
            System.out.println("SIGNATURE VERIFICATION <BY BOUNCY CASTLE STANDARD> FAILED");
            throw new UnmatchedSignatureException(
                    "Signature verification failed, probably the signature (CMS) has been altered!");
        }

        Cipher RSADecrypter;

        RSADecrypter = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

        //Initialize the Cipher using our the first key in the keystore  works fine for both
        RSADecrypter.init(Cipher.DECRYPT_MODE, pubkey);
        byte[] try_decrypt = RSADecrypter.doFinal(dataku);

        String decrypt_result = Hex.toHexString(try_decrypt);
        //Because there is magic number for hash algorithm at the beginning of the string,
        //we only need the last 64 characters from the decryption result
        String sanitized_decrypt_result = decrypt_result.substring(decrypt_result.length() - 64);

        System.out.format("%-32s%s\n", "Decryption Result", decrypt_result);
        System.out.format("%-32s%s\n", "Sanitized Decryption Result", sanitized_decrypt_result);

        if (!content_digest.equals(sanitized_decrypt_result)) {
            System.out.println("CONTENT DIGEST VERIFICATION FAILED");
            throw new UnmatchedSignatureException(
                    "Content digest verification failed, probably the content has been altered!");
        }
        System.out.println("CONTENT DIGEST VERIFIED");

        try {
            RootCertChecker rc = new RootCertChecker();

            rc.checkCertificate(rootCertCandidate, getRoot_cert_path());
        } catch (FileNotFoundException | InvalidKeyException | NoSuchAlgorithmException
                | NoSuchProviderException | SignatureException | CertificateException ex) {
            System.out.println("ROOT CERT VERIFICATION FAILED");
            throw new UnmatchedSignatureException("The System does not recognized this root Certificate");
        }
        System.out.println("ROOT CERTIFICATE VERIFIED");

    }

    return true;
}

From source file:io.aos.crypto.spl09.SignedDataProcessor.java

License:Apache License

/**
 * Take a CMS SignedData message and a trust anchor and determine if
 * the message is signed with a valid signature from a end entity
 * entity certificate recognized by the trust anchor rootCert.
 *//*from  w  w w.  j a v  a 2s  .  c o  m*/
public static boolean isValid(CMSSignedData signedData, X509Certificate rootCert) throws Exception {
    CertStore certsAndCRLs = signedData.getCertificatesAndCRLs("Collection", "BC");
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator it = signers.getSigners().iterator();

    if (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();

        signerConstraints.setKeyUsage(getKeyUsageForSignature());

        PKIXCertPathBuilderResult result = Utils.buildPath(rootCert, signer.getSID(), certsAndCRLs);

        return signer.verify(result.getPublicKey(), "BC");
    }

    return false;
}

From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java

License:Open Source License

/**
 * Merges two SignedData Objects//w  ww.j av  a2 s . co m
 * 
 * @param cms
 *            existing cms signed data
 * @param s
 *            new cms signed data
 * @param checkSameDigest
 *            check if messageDigest value is the same for all signers?
 * @return the merged cms
 */
public CMSSignedData mergeCms(CMSSignedData cms, CMSSignedData s) {

    try {

        SignerInformationStore existingSignersStore = cms.getSignerInfos();
        Collection<SignerInformation> existingSignersCollection = existingSignersStore.getSigners();

        SignerInformationStore newSignersStore = s.getSignerInfos();
        Collection<SignerInformation> newSignersCollection = newSignersStore.getSigners();

        // do some sanity checks
        if (existingSignersCollection.isEmpty()) {
            System.out.println("Error: existing signed data has no signers.");
            return null;
        }
        if (newSignersCollection.isEmpty()) {
            System.out.println("Error: new signed data has no signers.");
            return null;
        }
        byte[] cmsBytes = (byte[]) cms.getSignedContent().getContent();
        byte[] sBytes = (byte[]) s.getSignedContent().getContent();
        if (!Arrays.equals(cmsBytes, sBytes)) {
            System.out.println("Error: content data differs.");
            return null;
        }

        /* Digest could differ, if hashing algorithms are different
                 if (checkSameDigest)
                    if (!isSameDigest(existingSignersCollection,
          newSignersCollection)) {
                       System.out
             .println("Error: messageDigest for some signers differ.");
                               
                       return null;
                    }
        */
        CertStore existingCertsStore = cms.getCertificatesAndCRLs("Collection", "BC");
        CertStore newCertsStore = s.getCertificatesAndCRLs("Collection", "BC");

        X509Store x509Store = cms.getAttributeCertificates("Collection", "BC");
        X509Store newX509Store = s.getAttributeCertificates("Collection", "BC");

        Collection newCertsCollection = newCertsStore.getCertificates(null);

        Iterator<SignerInformation> existingSignersIterator = existingSignersCollection.iterator();
        // ciclo tra tutti i vecchi firmatari
        while (existingSignersIterator.hasNext()) {
            SignerInformation exSigner = existingSignersIterator.next();
            // Controllo la presenza di certificati firmatario corrente
            // tra i nuovi certificati
            Collection exSignerCerts = newCertsStore.getCertificates(exSigner.getSID());

            // ... e nel caso li rimuovo
            Iterator exSignerCertsIt = exSignerCerts.iterator();
            while (exSignerCertsIt.hasNext())
                newCertsCollection.remove(exSignerCertsIt.next());
        }
        // Rigenero la lista dei nuovi certificati,
        // ora disgiunta da quella dei vecchi
        newCertsStore = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(newCertsCollection), "BC");

        // Si crea un CMSSignedDataGenerator locale,
        // inizializzandolo conn i dati gi presenti.

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // add old certs
        signGen.addCertificatesAndCRLs(existingCertsStore);
        // add old certs attributes
        signGen.addAttributeCertificates(x509Store);
        // add old signers
        signGen.addSigners(existingSignersStore);

        // add new certs
        signGen.addCertificatesAndCRLs(newCertsStore);
        // add new certs attributes
        signGen.addAttributeCertificates(newX509Store);
        // add new signers
        signGen.addSigners(newSignersStore);

        CMSProcessable cp = new CMSProcessableByteArray((byte[]) cms.getSignedContent().getContent());

        s = signGen.generate(cp, true, "BC");

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return s;
}

From source file:it.trento.comune.j4sign.examples.CLITest.java

License:Open Source License

/**
 * Tests (possibly multiple) digital signatures using PKCS#11 tokens. After
 * correct integrity verification of all signatures, the CMS signed message
 * is saved on the filesystem under the users's home directory.
 * //from w  w w .  j  a v a  2  s.c  o  m
 */
public void testExternalSignature() {

    try {

        System.out.println("\n========= CMS (PKCS7) Signed message test ========\n");

        System.out.print("The test message to sign is:\t");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(this.msgBytes);
        System.out.println(baos.toString());
        System.out.print("As exadecimal string:\t\t");
        System.out.println(formatAsString(this.msgBytes, " ", WRAP_AFTER));
        System.out.println();

        CMSProcessable msg = new CMSProcessableByteArray(this.msgBytes);

        // questa versione del generatore  priva della classe interna
        // per
        // la generazione delle SignerInfo, che  stata promossa a
        // classe a
        // s.
        ExternalSignatureCMSSignedDataGenerator gen = new ExternalSignatureCMSSignedDataGenerator();

        // Conterr la lista dei certificati; come minimo dovr
        // contenere i certificati dei firmatari; opzionale, ma
        // consigliabile,
        // l'aggiunta dei certificati root per completare le catene di
        // certificazione.
        ArrayList certList = new ArrayList();

        ExternalSignatureSignerInfoGenerator sig = null;

        String answer = "STARTVALUE";
        String question = "Do you want to sign this message?";
        String defaultChoice = null;
        int i = 0;
        Prompt prompt = new Prompt();
        String[] choices = { "Y", "N" };

        while (!answer.equals("N")) {

            answer = prompt.question(question, "Type Y or N:", choices, defaultChoice);

            if (answer.equals("Y")) {
                System.out.println("========================");
                System.out.println("ADDING SIGNATURE " + i);

                if (detectCardAndCriptoki()) {
                    System.out.println("Starting signing process.");
                    // System.out
                    // .println("Applying SHA1 digest with RSA
                    // encryption.");
                    sig = getSignerInfoGenerator(msg, this.digestAlg, this.encAlg, this.makeDigestOnToken, // digest
                            // on
                            // token?
                            certList);

                    if (sig != null)
                        gen.addSignerInf(sig);
                } // if card detected

                question = "\nAdd another signature?";
                defaultChoice = "N";
                answer = "STARTVALUE";
            }
            i++;
        }

        if (certList.size() != 0) {

            // Per passare i certificati al generatore li si incapsula
            // in un
            // CertStore.
            CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                    "BC");

            System.out.println("Adding certificates ... ");
            gen.addCertificatesAndCRLs(store);

            // Finalmente, si pu creare il l'oggetto CMS.
            System.out.println("Generating CMSSignedData ");
            CMSSignedData s = gen.generate(msg, true);

            // Verifica

            System.out.println("\nStarting CMSSignedData verification ... ");
            // recupero dal CMS la lista dei certificati
            Store certs = s.getCertificates();

            // Recupero i firmatari.
            SignerInformationStore signers = s.getSignerInfos();
            Collection<?> c = signers.getSigners();

            System.out.println(c.size() + " signers found.");

            Iterator it = c.iterator();

            // ciclo tra tutti i firmatari
            i = 0;
            while (it.hasNext()) {
                SignerInformation signer = (SignerInformation) it.next();
                Collection<?> certCollection = certs.getMatches(signer.getSID());

                if (certCollection.size() == 1) {
                    // Iterator certIt = certCollection.iterator();
                    // X509Certificate cert = (X509Certificate)
                    // certIt.next();

                    X509CertificateHolder ch = (X509CertificateHolder) certCollection.toArray()[0];

                    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                            .getCertificate(ch);

                    System.out.println(i + ") Verifiying signature from:\n" + cert.getSubjectDN());
                    /*
                     * System.out.println("Certificate follows:");
                     * System.out
                     * .println("====================================");
                     * System.out.println(cert);
                     * System.out.println("===================================="
                     * );
                     */

                    if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {

                        System.out.println("SIGNATURE " + i + " OK!");
                    } else
                        System.err.println("SIGNATURE " + i + " Failure!");
                } else
                    System.out.println("There is not exactly one certificate for this signer!");
                i++;
            }

            // writing CMS file to user's home directory

            this.filePath = System.getProperty("user.home") + System.getProperty("file.separator")
                    + "ciao.txt.p7m";

            System.out.println("\nSAVING FILE TO: " + filePath);

            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(s.getEncoded());
            fos.flush();
            fos.close();
        }

    } catch (Exception ex) {
        System.err.println("EXCEPTION:\n" + ex);
    }

}

From source file:it.trento.comune.j4sign.examples.GUITest.java

License:Open Source License

/**
 * Creates the signed data structure, using signer infos precedently
 * accumulated./*w w  w  .  ja v  a  2  s. c  o  m*/
 * 
 * @return
 * @throws CertStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws CertificateExpiredException
 * @throws CertificateNotYetValidException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 */
private CMSSignedData buildCMSSignedData()
        throws CertStoreException, InvalidAlgorithmParameterException, CertificateExpiredException,
        CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, CMSException {
    CMSSignedData s = null;

    if (this.signersCertList.size() != 0) {

        // Per passare i certificati al generatore li si incapsula
        // in un
        // CertStore.
        CertStore store = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(this.signersCertList), "BC");

        log.println("Adding certificates ... ");
        this.cmsGenerator.addCertificatesAndCRLs(store);

        // Finalmente, si pu creare il l'oggetto CMS.
        log.println("Generating CMSSignedData ");
        s = this.cmsGenerator.generate(this.msg, true);

        // Verifica

        log.println("\nStarting CMSSignedData verification ... ");
        // recupero dal CMS la lista dei certificati
        CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");

        // Recupero i firmatari.
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();

        log.println(c.size() + " signers found.");

        Iterator it = c.iterator();

        // ciclo tra tutti i firmatari
        int i = 0;
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());

            if (certCollection.size() == 1) {
                // Iterator certIt = certCollection.iterator();
                // X509Certificate cert = (X509Certificate)
                // certIt.next();

                X509Certificate cert = (X509Certificate) certCollection.toArray()[0];
                log.println(i + ") Verifiying signature from:\n" + cert.getSubjectDN());
                /*
                 * log.println("Certificate follows:");
                 * log.println("====================================");
                 * log.println(cert);
                 * log.println("====================================");
                 */
                if (signer.verify(cert, "BC")) {

                    log.println("SIGNATURE " + i + " OK!");
                } else
                    log.println("SIGNATURE " + i + " Failure!");
            } else
                log.println("There is not exactly one certificate for this signer!");
            i++;
        }
    }

    return s;
}

From source file:it.trento.comune.j4sign.verification.RootsVerifier.java

License:Open Source License

private boolean verify(boolean forceCRLDownload) {

    String error = null;//w  w w.j ava2s  .  c o m
    boolean rootsOk = false;

    log.info("Starting root certificates verification.");

    try {

        CertificationAuthorities CNIPARoot = new CertificationAuthorities();
        try {
            CNIPARoot.addCertificateAuthority(CNIPARoot.getBytesFromPath(this.CNIPACACertFilePath));
        } catch (GeneralSecurityException e) {
            log.severe("Errore nell'inizializzazione della CA CNIPA: " + e);
        }

        Store certs = null;

        CMSSignedData CNIPA_CMS = null;
        try {

            CNIPA_CMS = getCNIPA_CMS();

        } catch (FileNotFoundException ex) {
            log.severe("Errore nell'acquisizione del file: " + ex);
        }

        Provider p = new org.bouncycastle.jce.provider.BouncyCastleProvider();
        if (Security.getProvider(p.getName()) == null)
            Security.addProvider(p);

        certs = CNIPA_CMS.getCertificates();

        if (certs != null) {
            SignerInformationStore signers = CNIPA_CMS.getSignerInfos();
            Collection c = signers.getSigners();

            log.info(c.size() + " signers found.");

            Iterator it = c.iterator();

            // ciclo tra tutti i firmatari
            int i = 0;
            while (it.hasNext()) {
                SignerInformation signer = (SignerInformation) it.next();
                Collection certCollection = null;
                try {
                    certCollection = certs.getMatches(signer.getSID());
                } catch (StoreException ex1) {
                    log.severe("CertStore error: " + ex1);
                }

                if (certCollection.size() == 1) {

                    X509CertificateHolder ch = (X509CertificateHolder) certCollection.toArray()[0];

                    byte[] signerFingerprint = getCertFingerprint(ch.getEncoded());

                    log.info("Signer fingerprint: " + formatAsGUString(signerFingerprint));

                    if (Arrays.equals(signerFingerprint, this.userApprovedFingerprint)) {

                        // get Certificate
                        java.security.cert.X509Certificate cert = null;
                        try {

                            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(ch);

                            VerifyResult vr = new VerifyResult(this.conf, certs, cert, CNIPA_CMS, CNIPARoot,
                                    signer, false, forceCRLDownload, false, getCrlDir());

                            // rootsOk = vr.getPassed_cnipasigner_expired();
                            rootsOk = vr.getPassed();
                            error = vr.getCRLerror();

                        } catch (CertificateException e) {
                            log.severe("Certificate error:" + e.getMessage());
                        }

                    } else
                        log.severe("Signer cert has wrong fingerprint!");
                } else
                    log.severe("There is not exactly one certificate for this signer!");

                i++;
            }

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        log.severe(e.getMessage());
    } catch (CMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        log.severe(e.getMessage());
    }

    return rootsOk;

}

From source file:it.trento.comune.j4sign.verification.X509CertRL.java

License:Open Source License

/**
 * Returns certificate present in a file at the given filePath.<br>
 * This can be coded base64 or DER<br>
 * <br>//w w  w  .  ja  v a  2 s.  c om
 * Restituisce il certificato contenuto nel file specificato nel filePath.
 * Distingue tra codifica base64 e DER.
 * 
 * @return certificate
 * @param filePath
 *            String
 */
public static X509Certificate getCertificatesFromFile(String filePath) {
    X509Certificate cert = null;
    try {

        byte[] buffer = new byte[1024];
        FileInputStream is = new FileInputStream(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (is.read(buffer) > 0) {
            baos.write(buffer);
        }
        byte[] risultato = baos.toByteArray();

        // codifica file Base64 o DER?
        byte[] certData;
        try {
            // se Base64, decodifica (italian law!)
            certData = Base64.decode(risultato);
            // Decodifica base64 completata
            System.out.println("Il file  in formato Base64");
        } catch (Exception e) {
            // il file non e' in formato base64
            // quindi  in DER
            System.out.println("Il file  in formato DER");
            certData = risultato;

        }
        // Estrazione del certificato dal file (ora codificato DER)
        CMSSignedData s = new CMSSignedData(certData);

        org.bouncycastle.jce.provider.BouncyCastleProvider p = new org.bouncycastle.jce.provider.BouncyCastleProvider();
        if (Security.getProvider(p.getName()) == null)
            Security.addProvider(p);

        // recupero dal CMS la lista dei certificati

        CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");

        // Recupero i firmatari.
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();

        Iterator it = c.iterator();

        // ciclo tra tutti i firmatari
        int i = 0;
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());

            if (certCollection.size() == 1) {
                // Iterator certIt = certCollection.iterator();
                // X509Certificate cert = (X509Certificate)
                // certIt.next();

                cert = (X509Certificate) certCollection.toArray()[0];

            } else {
                System.out.println("There is not exactly one certificate for this signer!");
            }
            i++;
        }

    } catch (Exception ex) {
        System.err.println("EXCEPTION:\n" + ex);
    }

    return cert;
}