Example usage for org.bouncycastle.cms CMSSignedData getCertificates

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

Introduction

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

Prototype

public Store<X509CertificateHolder> getCertificates() 

Source Link

Document

Return any X.509 certificate objects in this SignedData structure as a Store of X509CertificateHolder objects.

Usage

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESLevelBaselineLT.java

License:Open Source License

protected CMSSignedData postExtendCMSSignedData(CMSSignedData cmsSignedData,
        SignerInformation signerInformation, SignatureParameters parameters) {
    CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
    cadesSignature.setDetachedContents(parameters.getDetachedContent());
    final ValidationContext validationContext = cadesSignature
            .getSignatureValidationContext(certificateVerifier);

    Store certificatesStore = cmsSignedData.getCertificates();
    final Store attributeCertificatesStore = cmsSignedData.getAttributeCertificates();
    Store crlsStore = cmsSignedData.getCRLs();
    Store otherRevocationInfoFormatStoreBasic = cmsSignedData
            .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
    Store otherRevocationInfoFormatStoreOcsp = cmsSignedData
            .getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);

    final Set<CertificateToken> certificates = cadesSignature.getCertificatesForInclusion(validationContext);
    final Collection<X509CertificateHolder> newCertificateStore = new HashSet<X509CertificateHolder>(
            certificatesStore.getMatches(null));
    for (final CertificateToken certificateToken : certificates) {
        final X509CertificateHolder x509CertificateHolder = DSSUtils.getX509CertificateHolder(certificateToken);
        newCertificateStore.add(x509CertificateHolder);
    }/*www .  jav  a  2 s.c  om*/

    certificatesStore = new CollectionStore(newCertificateStore);

    final Collection<X509CRLHolder> newCrlsStore = new HashSet<X509CRLHolder>(crlsStore.getMatches(null));
    final DefaultAdvancedSignature.RevocationDataForInclusion revocationDataForInclusion = cadesSignature
            .getRevocationDataForInclusion(validationContext);
    for (final CRLToken crlToken : revocationDataForInclusion.crlTokens) {
        final X509CRLHolder x509CRLHolder = crlToken.getX509CrlHolder();
        newCrlsStore.add(x509CRLHolder);
    }
    crlsStore = new CollectionStore(newCrlsStore);

    final Collection<ASN1Primitive> newOtherRevocationInfoFormatStore = new HashSet<ASN1Primitive>(
            otherRevocationInfoFormatStoreBasic.getMatches(null));
    for (final OCSPToken ocspToken : revocationDataForInclusion.ocspTokens) {
        final BasicOCSPResp basicOCSPResp = ocspToken.getBasicOCSPResp();
        newOtherRevocationInfoFormatStore.add(DSSASN1Utils.toASN1Primitive(DSSUtils.getEncoded(basicOCSPResp)));
    }
    otherRevocationInfoFormatStoreBasic = new CollectionStore(newOtherRevocationInfoFormatStore);

    final CMSSignedDataBuilder cmsSignedDataBuilder = new CMSSignedDataBuilder(certificateVerifier);
    cmsSignedData = cmsSignedDataBuilder.regenerateCMSSignedData(cmsSignedData, parameters, certificatesStore,
            attributeCertificatesStore, crlsStore, otherRevocationInfoFormatStoreBasic,
            otherRevocationInfoFormatStoreOcsp);
    return cmsSignedData;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CMSSignedDataBuilder.java

License:Open Source License

/**
 * Note:/*  w ww .  ja v  a2s .co m*/
 * Section 5.1 of RFC 3852 [4] requires that, the CMS SignedData version be set to 3 if certificates from
 * SignedData is present AND (any version 1 attribute certificates are present OR any SignerInfo structures
 * are version 3 OR eContentType from encapContentInfo is other than id-data). Otherwise, the CMS
 * SignedData version is required to be set to 1.
 * ---> CMS SignedData Version is handled automatically by BouncyCastle.
 *
 * @param parameters                 set of the driving signing parameters
 * @param contentSigner              the contentSigned to get the hash of the data to be signed
 * @param signerInfoGeneratorBuilder true if the unsigned attributes must be included
 * @param originalSignedData         the original signed data if extending an existing signature. null otherwise.  @return the bouncycastle signed data generator which will
 *                                   sign
 *                                   the document and add the required signed and unsigned CMS attributes
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
protected CMSSignedDataGenerator createCMSSignedDataGenerator(final SignatureParameters parameters,
        final ContentSigner contentSigner, final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder,
        final CMSSignedData originalSignedData) throws DSSException {
    try {

        final X509Certificate signingCertificate = parameters.getSigningCertificate();

        final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        final X509CertificateHolder certHolder = DSSUtils.getX509CertificateHolder(signingCertificate);
        final SignerInfoGenerator signerInfoGenerator = signerInfoGeneratorBuilder.build(contentSigner,
                certHolder);

        generator.addSignerInfoGenerator(signerInfoGenerator);

        final Set<X509Certificate> newCertificateChain = new HashSet<X509Certificate>();

        if (originalSignedData != null) {

            generator.addSigners(originalSignedData.getSignerInfos());
            generator.addAttributeCertificates(originalSignedData.getAttributeCertificates());
            generator.addCRLs(originalSignedData.getCRLs());
            generator.addOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic,
                    originalSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic));
            generator.addOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response,
                    originalSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response));

            final Store certificates = originalSignedData.getCertificates();
            final Collection<X509CertificateHolder> certificatesMatches = certificates.getMatches(null);
            for (final X509CertificateHolder certificatesMatch : certificatesMatches) {
                newCertificateChain.add(DSSUtils.getCertificate(certificatesMatch));
            }
        }
        final List<X509Certificate> certificateChain = parameters.getCertificateChain();
        newCertificateChain.addAll(certificateChain);
        final Store jcaCertStore = getJcaCertStore(signingCertificate, newCertificateChain);
        generator.addCertificates(jcaCertStore);
        return generator;

    } catch (CMSException e) {
        throw new DSSException(e);
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    }
}

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

License:Open Source License

@Override
protected CMSSignedData postExtendCMSSignedData(CMSSignedData cmsSignedData,
        SignerInformation signerInformation, CAdESSignatureParameters parameters) {
    CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
    cadesSignature.setDetachedContents(parameters.getDetachedContent());
    final ValidationContext validationContext = cadesSignature
            .getSignatureValidationContext(certificateVerifier);

    Store<X509CertificateHolder> certificatesStore = cmsSignedData.getCertificates();
    final Set<CertificateToken> certificates = cadesSignature.getCertificatesForInclusion(validationContext);
    final Collection<X509CertificateHolder> newCertificateStore = new HashSet<X509CertificateHolder>(
            certificatesStore.getMatches(null));
    for (final CertificateToken certificateToken : certificates) {
        final X509CertificateHolder x509CertificateHolder = DSSASN1Utils
                .getX509CertificateHolder(certificateToken);
        newCertificateStore.add(x509CertificateHolder);
    }/*from   ww w.j ava  2 s.c  o m*/
    certificatesStore = new CollectionStore<X509CertificateHolder>(newCertificateStore);

    Store<X509CRLHolder> crlsStore = cmsSignedData.getCRLs();
    final Collection<X509CRLHolder> newCrlsStore = new HashSet<X509CRLHolder>(crlsStore.getMatches(null));
    final DefaultAdvancedSignature.RevocationDataForInclusion revocationDataForInclusion = cadesSignature
            .getRevocationDataForInclusion(validationContext);
    for (final CRLToken crlToken : revocationDataForInclusion.crlTokens) {
        final X509CRLHolder x509CRLHolder = getX509CrlHolder(crlToken);
        newCrlsStore.add(x509CRLHolder);
    }
    crlsStore = new CollectionStore<X509CRLHolder>(newCrlsStore);

    Store otherRevocationInfoFormatStoreBasic = cmsSignedData
            .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
    final Collection<ASN1Primitive> newOtherRevocationInfoFormatStore = new HashSet<ASN1Primitive>(
            otherRevocationInfoFormatStoreBasic.getMatches(null));
    for (final OCSPToken ocspToken : revocationDataForInclusion.ocspTokens) {
        final BasicOCSPResp basicOCSPResp = ocspToken.getBasicOCSPResp();
        newOtherRevocationInfoFormatStore
                .add(DSSASN1Utils.toASN1Primitive(DSSASN1Utils.getEncoded(basicOCSPResp)));
    }
    otherRevocationInfoFormatStoreBasic = new CollectionStore(newOtherRevocationInfoFormatStore);

    Store attributeCertificatesStore = cmsSignedData.getAttributeCertificates();
    Store otherRevocationInfoFormatStoreOcsp = cmsSignedData
            .getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);

    final CMSSignedDataBuilder cmsSignedDataBuilder = new CMSSignedDataBuilder(certificateVerifier);
    cmsSignedData = cmsSignedDataBuilder.regenerateCMSSignedData(cmsSignedData, parameters, certificatesStore,
            attributeCertificatesStore, crlsStore, otherRevocationInfoFormatStoreBasic,
            otherRevocationInfoFormatStoreOcsp);
    return cmsSignedData;
}

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

License:Open Source License

/**
 * Note:// ww w .  j  av  a2s .com
 * Section 5.1 of RFC 3852 [4] requires that, the CMS SignedData version be set to 3 if certificates from
 * SignedData is present AND (any version 1 attribute certificates are present OR any SignerInfo structures
 * are version 3 OR eContentType from encapContentInfo is other than id-data). Otherwise, the CMS
 * SignedData version is required to be set to 1.
 * ---> CMS SignedData Version is handled automatically by BouncyCastle.
 *
 * @param parameters                 set of the driving signing parameters
 * @param contentSigner              the contentSigned to get the hash of the data to be signed
 * @param signerInfoGeneratorBuilder true if the unsigned attributes must be included
 * @param originalSignedData         the original signed data if extending an existing signature. null otherwise.
 * @return the bouncycastle signed data generator which signs the document and adds the required signed and unsigned CMS attributes
 * @throws eu.europa.esig.dss.DSSException
 */
protected CMSSignedDataGenerator createCMSSignedDataGenerator(final CAdESSignatureParameters parameters,
        final ContentSigner contentSigner, final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder,
        final CMSSignedData originalSignedData) throws DSSException {
    try {

        final CertificateToken signingCertificate = parameters.getSigningCertificate();

        final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        final X509CertificateHolder certHolder = DSSASN1Utils.getX509CertificateHolder(signingCertificate);
        final SignerInfoGenerator signerInfoGenerator = signerInfoGeneratorBuilder.build(contentSigner,
                certHolder);

        generator.addSignerInfoGenerator(signerInfoGenerator);

        final Set<CertificateToken> certificateChain = new HashSet<CertificateToken>();

        if (originalSignedData != null) {

            generator.addSigners(originalSignedData.getSignerInfos());
            generator.addAttributeCertificates(originalSignedData.getAttributeCertificates());
            generator.addCRLs(originalSignedData.getCRLs());
            generator.addOtherRevocationInfo(id_pkix_ocsp_basic,
                    originalSignedData.getOtherRevocationInfo(id_pkix_ocsp_basic));
            generator.addOtherRevocationInfo(id_ri_ocsp_response,
                    originalSignedData.getOtherRevocationInfo(id_ri_ocsp_response));

            final Store certificates = originalSignedData.getCertificates();
            final Collection<X509CertificateHolder> certificatesMatches = certificates.getMatches(null);
            for (final X509CertificateHolder certificatesMatch : certificatesMatches) {

                final CertificateToken x509Certificate = DSSASN1Utils.getCertificate(certificatesMatch);
                certificateChain.add(x509Certificate);
            }
        }
        certificateChain.add(parameters.getSigningCertificate());
        certificateChain.addAll(parameters.getCertificateChain());

        final boolean trustAnchorBPPolicy = parameters.bLevel().isTrustAnchorBPPolicy();
        final Store jcaCertStore = getJcaCertStore(certificateChain, trustAnchorBPPolicy);
        generator.addCertificates(jcaCertStore);
        return generator;
    } catch (CMSException e) {
        throw new DSSException(e);
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    }
}

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. ja v a2 s.co  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: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.
 * //  w  w w  .  j a  v a2  s .co 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.verification.RootsVerifier.java

License:Open Source License

private boolean verify(boolean forceCRLDownload) {

    String error = null;//w  w  w  . ja v  a2 s. c om
    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:net.jsign.pe.PEFile.java

License:Apache License

/**
 * Print detailed informations about the PE file.
 *//*  ww  w.jav  a2 s .c  o  m*/
public void printInfo(PrintWriter out) {
    out.println("PE File");
    out.println("  Name:          " + raf.getName());
    out.println("  Size:          " + raf.length());
    out.println("  Last Modified: " + new Date(raf.lastModified()));
    out.println();

    out.println("PE Header");
    out.println("  Machine:                    " + getMachineType());
    out.println("  Number of sections:         " + getNumberOfSections());
    out.println("  Timestamp:                  " + getTimeDateStamp());
    out.println("  Pointer to symbol table:    0x" + Long.toHexString(getPointerToSymbolTable()));
    out.println("  Number of symbols:          " + getNumberOfSymbols());
    out.println("  Size of optional header:    " + getSizeOfOptionalHeader());
    out.println("  Characteristics:            0x" + Long.toBinaryString(getCharacteristics()));
    out.println();

    out.println("Optional Header");
    PEFormat format = getFormat();
    out.println(
            "  PE Format:                  0x" + Integer.toHexString(format.value) + " (" + format.label + ")");
    out.println("  Linker version:             " + getMajorLinkerVersion() + "." + getMinorLinkerVersion());
    out.println("  Size of code:               " + getSizeOfCode());
    out.println("  Size of initialized data:   " + getSizeOfInitializedData());
    out.println("  Size of uninitialized data: " + getSizeOfUninitializedData());
    out.println("  Address of entry point:     0x" + Long.toHexString(getAddressOfEntryPoint()));
    out.println("  Base of code:               0x" + Long.toHexString(getBaseOfCode()));
    if (PEFormat.PE32.equals(getFormat())) {
        out.println("  Base of data:               0x" + Long.toHexString(getBaseOfData()));
    }
    out.println("  Image base:                 0x" + Long.toHexString(getImageBase()));
    out.println("  Section alignment:          " + getSectionAlignment());
    out.println("  File alignment:             " + getFileAlignment());
    out.println("  Operating system version:   " + getMajorOperatingSystemVersion() + "."
            + getMinorOperatingSystemVersion());
    out.println("  Image version:              " + getMajorImageVersion() + "." + getMinorImageVersion());
    out.println(
            "  Subsystem version:          " + getMajorSubsystemVersion() + "." + getMinorSubsystemVersion());
    out.println("  Size of image:              " + getSizeOfImage());
    out.println("  Size of headers:            " + getSizeOfHeaders());
    out.println("  Checksum:                   0x" + Long.toHexString(getCheckSum()));
    out.println("  Checksum (computed):        0x" + Long.toHexString(computeChecksum()));
    out.println("  Subsystem:                  " + getSubsystem());
    out.println("  DLL characteristics:        0x" + Long.toBinaryString(getDllCharacteristics()));
    out.println("  Size of stack reserve:      " + getSizeOfStackReserve());
    out.println("  Size of stack commit:       " + getSizeOfStackCommit());
    out.println("  Size of heap reserve:       " + getSizeOfHeapReserve());
    out.println("  Size of heap commit:        " + getSizeOfHeapCommit());
    out.println("  Number of RVA and sizes:    " + getNumberOfRvaAndSizes());
    out.println();

    out.println("Data Directory");
    for (DataDirectoryType type : DataDirectoryType.values()) {
        DataDirectory entry = getDataDirectory(type);
        if (entry != null && entry.getVirtualAddress() != 0) {
            out.printf("  %-30s 0x%08x %8d bytes\n", type, entry.getVirtualAddress(), entry.getSize());
        }
    }
    out.println();

    int sectionTableOffset = getDataDirectoryOffset() + 8 * getNumberOfRvaAndSizes();
    out.println("Sections");
    out.println("      Name     Virtual Size  Virtual Address  Raw Data Size  Raw Data Ptr  Characteristics");
    for (int i = 0; i < getNumberOfSections(); i++) {
        Section section = new Section(this, sectionTableOffset + 40 * i);
        out.printf("  #%d  %-8s     %8d       0x%08x       %8d    0x%08x  %s\n", i + 1, section.getName(),
                section.getVirtualSize(), section.getVirtualAddress(), section.getSizeOfRawData(),
                section.getPointerToRawData(), section.getCharacteristics());
    }
    out.println();

    List<CMSSignedData> signatures = getSignatures();
    if (!signatures.isEmpty()) {
        out.println("Signatures");
        for (CMSSignedData signedData : signatures) {
            SignerInformation signerInformation = signedData.getSignerInfos().getSigners().iterator().next();
            X509CertificateHolder certificate = (X509CertificateHolder) signedData.getCertificates()
                    .getMatches(signerInformation.getSID()).iterator().next();

            String commonName = certificate.getSubject().getRDNs(X509ObjectIdentifiers.commonName)[0].getFirst()
                    .getValue().toString();

            AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
            boolean timestamped = unsignedAttributes != null
                    && (unsignedAttributes.get(PKCSObjectIdentifiers.pkcs_9_at_counterSignature) != null
                            || unsignedAttributes.get(AuthenticodeObjectIdentifiers.SPC_RFC3161_OBJID) != null);
            DigestAlgorithm algorithm = DigestAlgorithm
                    .of(signerInformation.getDigestAlgorithmID().getAlgorithm());
            out.println("  " + commonName + "  " + (algorithm != null ? "[" + algorithm.id + "]  " : "")
                    + (timestamped ? "(timestamped)" : ""));
        }
    }
}

From source file:net.jsign.timestamp.AuthenticodeTimestamper.java

License:Apache License

@Override
protected Collection<X509CertificateHolder> getExtraCertificates(CMSSignedData token) {
    return token.getCertificates().getMatches(null);
}

From source file:net.jsign.timestamp.Timestamper.java

License:Apache License

protected CMSSignedData modifySignedData(CMSSignedData sigData, AttributeTable unsignedAttributes,
        Collection<X509CertificateHolder> extraCertificates) throws IOException, CMSException {
    SignerInformation signerInformation = sigData.getSignerInfos().getSigners().iterator().next();
    signerInformation = SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes);

    Collection<X509CertificateHolder> certificates = new ArrayList<X509CertificateHolder>();
    certificates.addAll(sigData.getCertificates().getMatches(null));
    if (extraCertificates != null) {
        certificates.addAll(extraCertificates);
    }/*from   www.j a  v  a  2s  . c  o  m*/
    Store<X509CertificateHolder> certificateStore = new CollectionStore<X509CertificateHolder>(certificates);

    AuthenticodeSignedDataGenerator generator = new AuthenticodeSignedDataGenerator();
    generator.addCertificates(certificateStore);
    generator.addSigners(new SignerInformationStore(signerInformation));

    ASN1ObjectIdentifier contentType = new ASN1ObjectIdentifier(sigData.getSignedContentTypeOID());
    ASN1Encodable content = ASN1Sequence.getInstance(sigData.getSignedContent().getContent());

    return generator.generate(contentType, content);
}