Example usage for org.bouncycastle.cms CMSSignedData CMSSignedData

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

Introduction

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

Prototype

public CMSSignedData(ContentInfo sigData) throws CMSException 

Source Link

Usage

From source file:it.govpay.core.utils.SignUtils.java

License:Open Source License

public static byte[] cleanCadesSignedFile(byte[] rt) throws KeyStoreException, CMSException, IOException {
    CMSSignedData cms = new CMSSignedData(rt);
    return ((byte[]) cms.getSignedContent().getContent());
}

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

License:Open Source License

public CMSVerifier(InputStream signedDataStream) {

    try {//from w ww . jav a  2s .c  om

        this.cmsSignedData = new CMSSignedData(signedDataStream);

    } catch (CMSException e) {
        if (debug)
            System.out.println("Dati firmati non corretti: " + e.getMessage());
    }
}

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

License:Open Source License

private InputStream getCmsInputStream(String path) {

    FileInputStream is = null;/* w ww  .  j  a  va2s  .  c om*/
    try {
        is = new FileInputStream(path);
    } catch (FileNotFoundException ex) {
        log.severe("Errore nell'acquisizione del file: " + ex);
    }
    ByteArrayInputStream bais = null;
    try {
        CMSSignedData cms = new CMSSignedData(is);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cms.getSignedContent().write(baos);
        bais = new ByteArrayInputStream(baos.toByteArray());
    } catch (CMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bais;

}

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

License:Open Source License

public static CMSSignedData buildCmsFromStream(InputStream is) throws CMSException, IOException {

    CMSSignedData aCms = null;/*from  ww  w .  j av  a 2  s.com*/

    aCms = new CMSSignedData(is);

    return aCms;
}

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

License:Open Source License

public static CMSSignedData buildCmsFromFile(String filepath) throws IOException, CMSException {

    CMSSignedData aCms = null;/*w  w w.  j  av a2 s  . c o m*/

    FileInputStream is = new FileInputStream(filepath);

    // Try to build object directly from file stream
    // (it's going to work if file is DER encoded)
    try {
        aCms = buildCmsFromStream(is);

    } catch (CMSException ex1) {
        // Not a DER encoding ...

        if (is != null)
            is.close();

        if (aCms == null) {
            // Try with PEM decoding
            try {
                FileReader r = new FileReader(filepath);
                PEMReader pr = new PEMReader(r);
                ContentInfo ci = (ContentInfo) pr.readObject();
                r.close();
                pr.close();

                aCms = new CMSSignedData(ci);

            } catch (Exception ePEM) {
                // Trying (at last) raw base64 ...
                byte[] buffer = new byte[1024];

                is = new FileInputStream(filepath);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                while (is.read(buffer) > 0) {
                    baos.write(buffer);
                }

                byte[] signedBytes = Base64.decode(baos.toByteArray());
                aCms = new CMSSignedData(signedBytes);

                is.close();

            }

        }
    }

    return aCms;
}

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. j  ava 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;
}

From source file:it.treviso.provincia.freesigner.applet.FreeSignerSignApplet3.java

License:Open Source License

/**
 * Prepares a signing procedure.//from  w ww  . j  a v a 2 s.  c  om
 * 
 * @param digestAlg
 *            String
 * @param encryptionAlg
 *            String
 * @param digestOnToken
 *            boolean
 * @throws InvalidKeyException
 * @throws CertificateEncodingException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CMSException
 */
private void openSignature(String digestAlg, String encryptionAlg, boolean digestOnToken)
        throws InvalidKeyException, CertificateEncodingException, SignatureException, NoSuchProviderException,
        NoSuchAlgorithmException, IOException, CMSException {

    File inputFile = new File(fileDaAprire);

    if (fileDaAprire.substring(fileDaAprire.lastIndexOf('.') + 1, fileDaAprire.length()).toLowerCase()
            .equalsIgnoreCase("p7m")) {
        log.println("Resigning in progress...");
        // do resigning things
        resign = true;
        byte[] bytesFromFile = getBytesFromFile(inputFile);
        byte[] certData;
        try {
            certData = Base64.decode(bytesFromFile);
        } catch (Exception eb64) {
            certData = bytesFromFile;
        }
        CMSSignedData actualFile = new CMSSignedData(certData);
        this.msg = new CMSProcessableByteArray((byte[]) actualFile.getSignedContent().getContent());
    } else {
        this.msg = new CMSProcessableByteArray(getBytesFromFile(inputFile));
    }

    /**
     * Code notes:
     * 
     * On CLITest.java there is a method called getSignerInfoGenerator that gives some infos about the generator that then is added on the
     * 
     * ExternalSignatureCMSSignedDataGenerator() with cmsGenerator.addSignerInf(sig)
     * 
     */

    this.cmsGenerator = new ExternalSignatureCMSSignedDataGenerator();

    this.signersCertList = new ArrayList();

    log.println("\nCalculating digest ...\n");

    this.signerInfoGenerator = new ExternalSignatureSignerInfoGenerator(digestAlg, encryptionAlg);
    /* Cades Impl. */
    this.signerInfoGenerator.setCertificate(certforcades);
    /* End Cades Impl. */
    byte[] rawDigest = null;
    byte[] dInfoBytes = null;
    byte[] paddedBytes = null;

    /**
     * notes for multiple signing:
     * this.msg should be a CMSProcessableByteArray of the signedContent.
     * bytesToSign should be extracted with (byte[]) CMSSignedData.getSignedContent().getContent()
     */

    byte[] bytesToSign = this.signerInfoGenerator.getBytesToSign(PKCSObjectIdentifiers.data, msg, "BC");

    /*
     * Let's calculate DigestInfo in any case (even if digestOnToken is
     * TRUE) , in order to compare with decryption result
     */
    rawDigest = applyDigest(digestAlg, bytesToSign);

    log.println("Raw digest bytes:\n" + formatAsHexString(rawDigest));

    log.println("Encapsulating in a DigestInfo...");

    dInfoBytes = encapsulateInDigestInfo(digestAlg, rawDigest);

    log.println("DigestInfo bytes:\n" + formatAsHexString(dInfoBytes));

    if (!digestOnToken) {
        // MessageDigest md = MessageDigest.getInstance(digestAlg);
        // md.update(bytesToSign);
        // byte[] digest = md.digest();
        //
        // log.println("digestAlg digest:\n" + formatAsHexString(digest));
        // log.println("Done.");
        setEncodedDigest(encodeFromBytes(dInfoBytes));
    }

}

From source file:it.treviso.provincia.freesigner.applet.FreeSignerSignApplet3.java

License:Open Source License

/**
 * Creates the signed data structure, using signer infos precedently
 * accumulated./*from  ww  w.j ava 2 s .  c  om*/
 * 
 * @return @throws CertStoreException
 * @throws CertStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws CertificateExpiredException
 * @throws CertificateNotYetValidException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 * @throws NoSuchStoreException
 */
@SuppressWarnings("deprecation")
private CMSSignedData buildCMSSignedData() throws CertStoreException, InvalidAlgorithmParameterException,
        CertificateExpiredException, CertificateNotYetValidException, NoSuchAlgorithmException,
        NoSuchProviderException, CMSException, NoSuchStoreException {

    CMSSignedData s = null;
    CMSSignedData actualFile = null;

    /**
     * resign? reads the file and creates a CMSSignedData of the actual File
     */
    if (this.resign) {
        try {
            byte[] bytesFromFile = getBytesFromFile(new File(fileDaAprire));
            byte[] certData;
            try {
                certData = Base64.decode(bytesFromFile);
            } catch (Exception eb64) {
                certData = bytesFromFile;
            }
            actualFile = new CMSSignedData(certData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    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);

        getSignerCN(s);

        /**
         * Resigning process:
         * retrieves:
         *    - SignerInformationStore
         *  - CertStore
         *  - x509Store
         *  first from the actualFile (the one on disk) then from CMSSignedData generated in the previous step.
         * 
         */
        if (resign) {
            SignerInformationStore actualSigners = actualFile.getSignerInfos();
            CertStore existingCerts = actualFile.getCertificatesAndCRLs("Collection", "BC");
            X509Store x509Store = actualFile.getAttributeCertificates("Collection", "BC");
            CertStore newCerts = s.getCertificatesAndCRLs("Collection", "BC");
            X509Store newX509Store = s.getAttributeCertificates("Collection", "BC");
            SignerInformationStore newSigners = s.getSignerInfos();
            CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
            //add old certs
            signGen.addCertificatesAndCRLs(existingCerts);
            //add old certs attributes
            signGen.addAttributeCertificates(x509Store);
            //add old signers
            signGen.addSigners(actualSigners);
            //add new certs
            signGen.addCertificatesAndCRLs(newCerts);
            //add new certs attributes
            signGen.addAttributeCertificates(newX509Store);
            //add old signers
            signGen.addSigners(newSigners);

            s = signGen.generate(this.msg, true, "BC");
        }
        // 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;
        boolean verified = true;
        while (it.hasNext() && verified) {
            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 (verified = signer.verify(cert, "BC")) {

                    log.println("SIGNATURE " + i + " OK!");
                } else {
                    System.err.println("SIGNATURE " + i + " Failure!");
                    JOptionPane.showMessageDialog(this,
                            "La verifica della firma di:\n" + cert.getSubjectDN() + "\n  fallita!",
                            "Costruzione della busta pkcs7 fallita.", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                System.out.println("There is not exactly one certificate for this signer!");
            }
            i++;
        }
        if (!verified)
            s = null;
    }

    return s;
}

From source file:it.treviso.provincia.freesigner.applet.VerifyTask.java

License:Open Source License

/**
 * Reads file and instantiate iterator currentSigner to deal with multiple
 * signers <br>// w  w w.  jav  a2s  .c om
 * <br>
 * Legge il file e recupera l'iteratore currentSigner che verr usato per
 * scorrere i vari firmatari
 * 
 * 
 */

public void readFile() {

    byte[] buffer = new byte[1024];

    FileInputStream is = null;
    try {
        is = new FileInputStream(this.filepath);
    } catch (FileNotFoundException ex) {
        setCanceled("Errore nell'acquisizione del file");
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        while (is.read(buffer) > 0) {
            baos.write(buffer);
        }
    } catch (Exception ex) {
        setCanceled("Errore nella lettura del file");
    }

    byte[] risultato = baos.toByteArray();

    // Is file PEM, raw Base64 or DER encoded?
    byte[] certData = null;

    try {
        FileReader r = new FileReader(this.filepath);
        PEMReader pr = new PEMReader(r);
        ContentInfo ci = (ContentInfo) pr.readObject();
        r.close();

        this.cms = new CMSSignedData(ci);

    } catch (Exception e) {
        //ROB: trying raw base64 ...
        try { // se Base64, decodifica (italian law!) 
            certData = Base64.decode(risultato);
            // Decodifica base64 completata 
            //setMessage("Il file firmato  in formato Base64");
        } catch (Exception eb64) {
            // il file non e' in formato base64 //
            // quindi  in DER (againitalian law!) //
            // setMessage("Il file firmato  in formato DER");
            certData = risultato;
        }

    }
    // Estrazione del certificato dal file (ora codificato DER)
    try {
        if (certData != null)
            this.cms = new CMSSignedData(certData);
    } catch (CMSException ex1) {
        setCanceled("Errore nell'estrazione del certificato dal file");
        verifyError = "Errore nell'estrazione del certificato dal file";
    } catch (IllegalArgumentException ex1) {
        setCanceled("Errore nell'estrazione del certificato dal file");
        verifyError = "Errore nell'estrazione del certificato dal file";
    }
    if (verifyError.length() == 0) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        // recupero dal CMS la lista dei certificati

        try {
            CertStore certs = cms.getCertificatesAndCRLs("Collection", "BC");
        } catch (CMSException ex2) {
            setCanceled("Errore nel CMS");
        } catch (NoSuchProviderException ex2) {
            setCanceled("Non esiste il provider del servizio");
        } catch (NoSuchAlgorithmException ex2) {
            setCanceled("Errore nell'algoritmo");
        }

        // Recupero i firmatari.
        SignerInformationStore signers = cms.getSignerInfos();

        Collection c = signers.getSigners();
        differentSigners = cms.getSignerInfos().size();

        // non avrebbe senso che fossero uguali
        // quindi fa il ciclo tra i firmatari
        // PERO' PUO' CAPITARE CHE CI SIA UN FIRMATARIO CHE FIRMA DUE VOLTE
        // E IN QUESTO CASO DOVREBBE FARE IL GIRO SUI CERTIFICATI!!!
        currentSigner = c.iterator();
        if (!currentSigner.hasNext()) {
            done = true;
        }
    } else {
        canceled = true;
    }
}

From source file:it.treviso.provincia.freesigner.crl.CertificationAuthorities.java

License:Open Source License

private static InputStream getCmsInputStream(URL url) {

    ByteArrayInputStream bais = null;
    try {//from  w  w  w  . j a v a  2 s. c  o  m
        CMSSignedData cms = new CMSSignedData(url.openStream());

        cms.getSignedContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cms.getSignedContent().write(baos);
        bais = new ByteArrayInputStream(baos.toByteArray());
    } catch (CMSException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bais;

}