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:com.blackberry.bidhelper.BidCertificateVerifierAndroid.java

License:Apache License

@Override
public boolean verifyReport(byte[] tzReport, byte[] signature) throws CertificateException {
    if (this.bidCert == null) {
        throw new IllegalStateException("Certificate not yet set");
    }//  w w  w.  ja va2s  .  com

    try {
        CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(tzReport), signature);

        Store certStore = cms.getCertificates();
        SignerInformationStore signers = cms.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();

        if (c.size() != 1) {
            return false;
        }

        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certStore.getMatches(signer.getSID());
            Iterator certIt = certCollection.iterator();

            // If there is no certificate part of the signature then the report may have been created before 
            // the certificate was cut.
            if (certCollection.size() == 0) {
                return signer
                        .verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(this.bidCert));
            }

            X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
            X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                    .getCertificate(certHolder);
            return signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert));
        }
    } catch (CMSException e) {
        throw new CertificateException(e.toString());
    } catch (OperatorCreationException oce) {
        throw new CertificateException(oce.toString());
    } catch (Exception ex) {
        throw ex;
    }

    return false;
}

From source file:com.google.code.p.keytooliui.ktl.util.jarsigner.CmsVerif.java

License:LGPL

public boolean doJob() {
    String strMethod = "doJob()";

    try {//  ww w  .  j  a  v a2  s.c  o m
        //_validateCmsSignature();
        CMSSignedData cms = _getSignPkcs7();

        SignerInformationStore sis = cms.getSignerInfos();
        Collection colSignerInfo = sis.getSigners();
        Iterator itrSignerInfo = colSignerInfo.iterator();
        SignerInformation sin = (SignerInformation) itrSignerInfo.next();

        //rcupration du certificat du signataire
        CertStore cse = cms.getCertificatesAndCRLs("Collection", CmsVerif._STR_KST_PROVIDER_BC);
        Iterator itrCert = cse.getCertificates(sin.getSID()).iterator();
        X509Certificate crt = (X509Certificate) itrCert.next();

        // Verifie la signature
        boolean blnCoreValidity = sin.verify(crt, CmsVerif._STR_KST_PROVIDER_BC);

        if (blnCoreValidity) {
            MySystem.s_printOutTrace(this, strMethod, "blnCoreValidity=true");

            String strBody = "CMS Detached signature is OK!";

            strBody += "\n\n" + ". CMS signature file location:";
            strBody += "\n  " + super._strPathAbsFileSig_;

            strBody += "\n\n" + ". Data file location:";
            strBody += "\n  " + super._strPathAbsFileData_;

            OPAbstract.s_showDialogInfo(super._frmOwner_, strBody);

            //SignerInfo sio = sin.toSignerInfo();

            SignerId sid = sin.getSID();

            if (sid != null) {
                System.out.println("sid.getSerialNumber()=" + sid.getSerialNumber());
                System.out.println("sid.getIssuerAsString()=" + sid.getIssuerAsString());
                System.out.println("sid.getSubjectAsString()=" + sid.getSubjectAsString());
            }

            /*System.out.println("sin.getDigestAlgOID()=" + sin.getDigestAlgOID());
            System.out.println("sin.getEncryptionAlgOID()=" + sin.getEncryptionAlgOID());
            System.out.println("sin.toString()=" + sin.toString());
            System.out.println("sin.getVersion()=" + sin.getVersion());*/
        }

        else {
            MySystem.s_printOutWarning(this, strMethod, "blnCoreValidity=true");

            String strBody = "CMS Detached signature is WRONG!";

            strBody += "\n\n" + ". CMS signature file location:";
            strBody += "\n  " + super._strPathAbsFileSig_;

            strBody += "\n\n" + ". Data file location:";
            strBody += "\n  " + super._strPathAbsFileData_;

            OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);
        }

    }

    catch (Exception exc) {
        exc.printStackTrace();
        MySystem.s_printOutError(this, strMethod, "exc caught");

        String strBody = "Failed to verify CMS detached signature.";

        strBody += "\n\n" + "Possible reason: wrong data file";

        strBody += "\n\n" + "got exception.";
        strBody += "\n" + exc.getMessage();
        strBody += "\n\n" + "More: see your session.log";

        OPAbstract.s_showDialogError(super._frmOwner_, strBody);

        return false;
    }

    // TODO
    return true;
}

From source file:com.guardtime.ksi.trust.CMSSignature.java

License:Apache License

public CMSSignature(byte[] signedData, byte[] cmsSignature) throws InvalidCmsSignatureException {
    try {/*from w  w w  . j  ava2  s.  c  om*/
        if (signedData == null || signedData.length < 1) {
            throw new InvalidCmsSignatureException("CMS signature signed data is null or empty array");
        }
        if (cmsSignature == null || cmsSignature.length < 1) {
            throw new InvalidCmsSignatureException("CMS signature is null or empty array");
        }
        CMSProcessableByteArray cmsProcessable = new CMSProcessableByteArray(signedData);
        CMSSignedData cmsSignedData = new CMSSignedData(cmsProcessable, cmsSignature);
        this.signerInformationStore = cmsSignedData.getSignerInfos();
        this.signedDataCertificates = cmsSignedData.getCertificates();
        LOGGER.debug("CMS signature contains {} signer information elements", signerInformationStore.size());
    } catch (CMSException e) {
        throw new InvalidCmsSignatureException("Invalid CMS signature", e);
    }
}

From source file:com.indivica.olis.Driver.java

License:Open Source License

public static String unsignData(String data) {

    byte[] dataBytes = Base64.decode(data);

    try {/*from w ww  .j  av a2 s  .co  m*/

        CMSSignedData s = new CMSSignedData(dataBytes);
        CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = s.getSignerInfos();
        @SuppressWarnings("unchecked")
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();
        while (it.hasNext()) {
            X509Certificate cert = null;
            SignerInformation signer = it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());
            @SuppressWarnings("unchecked")
            Iterator<X509Certificate> certIt = certCollection.iterator();
            cert = certIt.next();
            if (!signer.verify(cert.getPublicKey(), "BC"))
                throw new Exception("Doesn't verify");
        }

        CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent();
        byte[] signedContent = (byte[]) cpb.getContent();
        String content = new String(signedContent);
        return content;
    } catch (Exception e) {
        MiscUtils.getLogger().error("error", e);
    }
    return null;

}

From source file:com.infinities.keystone4j.utils.Cms.java

License:Apache License

@SuppressWarnings("rawtypes")
public String verifySignature(byte[] sigbytes, String signingCertFileName, String caFileName)
        throws CMSException, CertificateException, OperatorCreationException, NoSuchAlgorithmException,
        NoSuchProviderException, CertPathBuilderException, InvalidAlgorithmParameterException, IOException,
        CertificateVerificationException {
    logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, caFileName });
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate signercert = generateCertificate(signingCertFileName);
    X509Certificate cacert = generateCertificate(caFileName);
    Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>();
    additionalCerts.add(cacert);/*from ww  w .  j  a  v  a2 s.c o m*/

    CertificateVerifier.verifyCertificate(signercert, additionalCerts, true); // .validateKeyChain(signercert,
    // certs);
    if (Base64Verifier.isBase64(sigbytes)) {
        try {
            sigbytes = Base64.decode(sigbytes);
            logger.debug("Signature file is BASE64 encoded");
        } catch (Exception ioe) {
            logger.warn("Problem decoding from b64", ioe);
        }
    }

    // sigbytes = Base64.decode(sigbytes);

    // --- Use Bouncy Castle provider to verify included-content CSM/PKCS#7
    // signature ---
    ASN1InputStream in = null;
    try {
        logger.debug("sigbytes size: {}", sigbytes.length);
        in = new ASN1InputStream(new ByteArrayInputStream(sigbytes), Integer.MAX_VALUE);

        CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(in.readObject()));
        Store store = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        int verified = 0;

        while (it.hasNext()) {
            X509Certificate cert = null;
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = store.getMatches(signer.getSID());
            if (certCollection.isEmpty() && signercert == null)
                continue;
            else if (signercert != null) // use a signer cert file for
                // verification, if it was
                // provided
                cert = signercert;
            else { // use the certificates included in the signature for
                   // verification
                Iterator certIt = certCollection.iterator();
                cert = (X509Certificate) certIt.next();
            }

            // if (signer.verify(new
            // JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            // verified++;
        }

        if (verified == 0) {
            logger.warn(" No signers' signatures could be verified !");
        } else if (signercert != null)
            logger.info("Verified a signature using signer certificate file  {}", signingCertFileName);
        else
            logger.info("Verified a signature using a certificate in the signature data");

        CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent();
        byte[] rawcontent = (byte[]) cpb.getContent();

        return new String(rawcontent);
    } catch (Exception ex) {
        logger.error("Couldn't verify included-content CMS signature", ex);
        throw new RuntimeException("Couldn't verify included-content CMS signature", ex);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.itdhq.poc.ocrsign.CreateSignature.java

License:Apache License

/**
 * We just extend CMS signed Data//  w ww. j  ava  2 s  .  c o  m
 *
 * @param signedData -Generated CMS signed data
 * @return CMSSignedData - Extended CMS signed data
 */
@Override
protected CMSSignedData signTimeStamps(CMSSignedData signedData) throws IOException, TSPException {
    SignerInformationStore signerStore = signedData.getSignerInfos();
    List<SignerInformation> newSigners = new ArrayList<SignerInformation>();

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

    // TODO do we have to return a new stePrivateKeyPass -keystore samlKeystore.jks -keyalg RSA -sigalg SHA1WithRSAore?
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:com.miguelpazo.signature.test.SignDataTest.java

public void verifyData(String envelopedData) throws Exception {
    CMSSignedData cms = new CMSSignedData(Base64.decode(envelopedData.getBytes()));
    Store store = cms.getCertificates();

    SignerInformationStore signers = cms.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();/*  w w  w .  ja  v  a2  s.co  m*/

    //        Object content = cms.getSignedContent().getContent();
    //        byte[] b = (byte[]) content;
    //        byte[] dataSigned = Base64.encode(cms.getSignedContent());
    System.out.println(cms.getSignedContent());

    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = store.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();

        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certHolder);

        System.out.println("data => " + certFromSignedData.getSubjectDN().toString());

        //            byte[] data = Base64.encode(signer.getContentDigest());
        //            System.out.println(new String(data));
        //            if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certFromSignedData))) {
        //                System.out.println("Signature verified");
        //            } else {
        //                System.out.println("Signature verification failed");
        //            }
    }
}

From source file:com.modemo.javase.signature.ValidationTimeStamp.java

License:Apache License

/**
 * Extend cms signed data with TimeStamp first or to all signers
 *
 * @param signedData Generated CMS signed data
 * @return CMSSignedData Extended CMS signed data
 * @throws IOException//from   www .  j ava2  s .  c o m
 */
public CMSSignedData addSignedTimeStamp(CMSSignedData signedData) throws IOException {
    SignerInformationStore signerStore = signedData.getSignerInfos();
    List<SignerInformation> newSigners = new ArrayList<>();

    for (SignerInformation signer : signerStore.getSigners()) {
        // This adds a timestamp to every signer (into his unsigned attributes) in the signature.
        newSigners.add(signTimeStamp(signer));
    }

    // Because new SignerInformation is created, new SignerInfoStore has to be created 
    // and also be replaced in signedData. Which creates a new signedData object.
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:com.yacme.ext.oxsit.cust_it.security.crl.RootsVerifier.java

License:Open Source License

private byte[] getFingerprint() {

    byte[] fingerprint = null;
    String sDispDate = "";

    CertStore certs = null;/*from  w w w.java  2s  . c  o m*/
    CMSSignedData CNIPA_CMS = null;
    try {
        CNIPA_CMS = getCNIPA_CMS();

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

        try {
            certs = CNIPA_CMS.getCertificatesAndCRLs("Collection", "BC");
        } catch (CMSException ex2) {
            m_aLogger.severe("getFingerprint", "Errore nel CMS delle RootCA", ex2);
        } catch (NoSuchProviderException ex2) {
            m_aLogger.severe("getFingerprint", "Non esiste il provider del servizio", ex2);
        } catch (NoSuchAlgorithmException ex2) {
            m_aLogger.severe("getFingerprint", "Errore nell'algoritmo", ex2);
        }

        if (certs == null)
            m_aLogger.severe("getFingerprint", "No certs for CNIPA signature!");
        else {
            SignerInformationStore signers = CNIPA_CMS.getSignerInfos();
            Collection<SignerInformation> c = signers.getSigners();
            if (c.size() != 1) {
                m_aLogger.severe("getFingerprint", "There is not exactly one signer!");
            } else {

                Iterator<SignerInformation> it = c.iterator();

                if (it.hasNext()) {
                    SignerInformation signer = it.next();
                    //grab date
                    AttributeTable att = signer.getSignedAttributes();
                    if (att.get(CMSAttributes.signingTime) == null) {
                        //no date
                        m_aLogger.info("getFingerprint()",
                                "A date is NOT present on CA root archive signature !");
                    } else {
                        Attribute atime = att.get(CMSAttributes.signingTime);
                        //date present
                        //@FIXME get date in a more clean way
                        String sdate = atime.getAttrValues().toString();
                        sDispDate = "20" + sdate.substring(1, 3) + "-" + sdate.substring(3, 5) + "-"
                                + sdate.substring(5, 7) + " " + sdate.substring(7, 9) + ":"
                                + sdate.substring(9, 11) + ":" + sdate.substring(11, 13) + " UTC";
                        m_aLogger.debug("getFingerprint()", "A date is present: " + sDispDate);
                    }

                    Collection<?> certCollection = null;
                    try {
                        certCollection = certs.getCertificates(signer.getSID());

                        if (certCollection.size() == 1) {
                            m_aRootSignatureCert = (X509Certificate) certCollection.toArray()[0];
                            fingerprint = getCertFingerprint(m_aRootSignatureCert);
                        } else {
                            //print an error?
                            m_aLogger.severe("getFingerprint",
                                    "There is not exactly one certificate for this signer!");
                        }
                    } catch (CertStoreException ex1) {
                        //print an error?
                        m_aLogger.severe("Errore nel CertStore", ex1);
                    }
                }
            }
        }

        //grab the localized text to display
        String _format = "id_root_verify_message";
        String _title = "id_root_verify_message_title";
        String _no_fp = "id_root_verify_message_ko";
        MessageConfigurationAccess m_aRegAcc = null;
        m_aRegAcc = new MessageConfigurationAccess(m_xCC, m_xMCF);

        try {
            _title = m_aRegAcc.getStringFromRegistry(_title);
            _format = m_aRegAcc.getStringFromRegistry(_format);
            _no_fp = m_aRegAcc.getStringFromRegistry(_no_fp);
        } catch (Exception e) {
            m_aLogger.severe(e);
        }
        m_aRegAcc.dispose();

        String theFingerprint = ((fingerprint == null) ? _no_fp : formatAsGUString(fingerprint));
        String _mex = String.format(_format, sDispDate, theFingerprint);

        DialogRootVerify aDialog1 = new DialogRootVerify(m_xFrame, m_xCC, m_xMCF, _mex);
        //      DialogRootVerify aDialog1 = new DialogRootVerify( null, m_xCC, m_xMCF,_mex );
        //PosX and PosY should be obtained from the parent window (in this case the frame)
        //the problem is that we get the pixel, but we need the logical pixel, so for now it doesn't work...
        int BiasX = ControlDims.RSC_SP_DLG_INNERBORDER_LEFT;
        int BiasY = ControlDims.RSC_SP_DLG_INNERBORDER_TOP;
        short ret;
        try {
            aDialog1.initialize(BiasX, BiasY);
            ret = aDialog1.executeDialog();
            // ret = 0: NO
            // ret = 1: Yes
            if (ret == 1) {
                return fingerprint;
            }
        } catch (BasicErrorException e) {
            m_aLogger.severe(e);
        } catch (Exception e) {
            m_aLogger.severe(e);
        }
    } catch (FileNotFoundException ex) {
        m_aLogger.severe("getFingerprint", "Errore nella lettura del file delle RootCA: ", ex);
    } catch (CMSException e) {
        m_aLogger.severe("getFingerprint", "Errore nel CMS delle RootCA: ", e);
    }
    return null;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) {

    try {/* ww w.  j  a  va2 s . com*/
        SignerInformationStore signerStore = null;
        try (InputStream sigIs = new ByteArrayInputStream(
                Base64.decode(signature.getBytes(StandardCharsets.UTF_8)))) {
            CMSProcessable content = new CMSProcessableByteArray(data.getBytes(StandardCharsets.UTF_8));
            CMSSignedData signedData = new CMSSignedData(content, sigIs);
            signerStore = signedData.getSignerInfos();
        }

        Collection<SignerInformation> signers = signerStore.getSigners();
        Iterator<SignerInformation> it = signers.iterator();

        SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder()
                .setProvider(BC_PROVIDER).build(publicKey);
        while (it.hasNext()) {
            SignerInformation signerInfo = (SignerInformation) it.next();
            if (signerInfo.verify(infoVerifier)) {
                return true;
            }
        }
    } catch (CMSException ex) {
        LOG.error("validatePKCS7Signature: unable to initialize CMSSignedData object: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(
                "validatePKCS7Signature: Caught OperatorCreationException when creating JcaSimpleSignerInfoVerifierBuilder: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (IOException ex) {
        LOG.error("validatePKCS7Signature: Caught IOException when closing InputStream: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("validatePKCS7Signature: unable to validate signature: " + ex.getMessage());
        throw new CryptoException(ex.getMessage());
    }

    return false;
}