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:com.cesnet.pki.DigicertConnector.java

/**
 * downloads and decodes given certificate, updates HashMap of results
 * // www.ja  va  2s.  c  o m
 * @param certificateId certificate id
 * @param parentId id of parent organization
 * @param apiKey api key to access downloading certificate
 * @throws MalformedURLException if no protocol is specified, or an unknown protocol is found, or spec is null
 * @throws ProtocolException if the method cannot be reset or if the requested method isn't valid for HTTP
 * @throws IllegalArgumentException if Input-buffer size is less or equal zero
 * @throws UnsupportedEncodingException if the named charset is not supported
 * @throws IOException if an I/O error occurs while creating the input stream
 * @throws UnknownServiceException if the protocol does not support input
 * @throws ParseException if the beginning of the specified string cannot be parsed
 * @throws CMSException master exception type for all exceptions caused in OpenCms
 * @throws CertificateException this exception indicates one of a variety of certificate problems
 */
private void decodeCertificate(int orderId, int certificateId, int parentId, String parentName, String apiKey)
        throws MalformedURLException, ProtocolException, IllegalArgumentException, UnsupportedEncodingException,
        IOException, UnknownServiceException, CMSException, ParseException, CertificateException,
        JSONException {

    String certificate = callDigicert("certificate/" + certificateId + "/download/format/p7b", apiKey);

    if (certificate == null) {
        System.out.println("certificate is null");
        System.out.println("orderId:\t" + orderId + "\tcertificateId:\t" + certificateId + "\tparentId:\t"
                + parentId + "\tparentName:\t" + parentName + "\tApiKey:\t" + apiKey);
    } else {

        byte[] source = DatatypeConverter
                .parseBase64Binary(new String(certificate.getBytes(Charset.forName("UTF-8"))));
        CMSSignedData signature = new CMSSignedData(source);
        Store cs = signature.getCertificates();

        ArrayList<X509CertificateHolder> listCertData = new ArrayList(cs.getMatches(null));

        // we want only first certificate
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(listCertData.get(0));

        CertificateData data = new CertificateData(cert, orderId, parentId, parentName);

        // store found certificate in HashMap
        cache.put(orderId, data);

        if (isCertValidAtDay(cert, referenceDate)) {
            int value = 0;
            if (parentId_has_numOfCerts.get(parentId) != null) {
                value = parentId_has_numOfCerts.get(parentId);
            }
            parentId_has_numOfCerts.put(parentId, value + 1);
        }
    }
}

From source file:com.cordova.plugin.CertPlugin.java

License:Open Source License

private X509Certificate getX509CertificateFromP7cert(String p7cert) {
    try {/*from   ww  w.  jav a2 s.  c  om*/
        byte[] encapSigData = Base64.decode(p7cert, 0);
        //            ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        CMSSignedData s = new CMSSignedData(encapSigData);
        Store certStore = s.getCertificates();
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
        @SuppressWarnings("unchecked")
        ArrayList<X509CertificateHolder> certificateHolders = (ArrayList<X509CertificateHolder>) certStore
                .getMatches(null);
        for (X509CertificateHolder holder : certificateHolders) {
            X509Certificate cert = converter.getCertificate(holder);

            X500Name x500Name = holder.getSubject();
            RDN[] rdns = x500Name.getRDNs(BCStyle.CN);
            RDN rdn = rdns[0];
            String name = IETFUtils.valueToString(rdn.getFirst().getValue());
            if (!name.contains("ROOT")) {
                //cn ?? ROOT ??
                return cert;
            }
            //                certList.add(cert);
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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

License:Open Source License

public static String unsignData(String data) {

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

    try {/* www.  j  a va2 s.c o  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  w  w w .ja  va 2  s.  c  om

    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.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 ww.jav  a  2 s.c o 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.yacme.ext.oxsit.cust_it.security.crl.CertificationAuthorities.java

License:Open Source License

private static InputStream getCmsInputStream(URL url) {

    ByteArrayInputStream bais = null;
    try {/*from www  .  j a  v a 2  s.  co  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) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bais;
}

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

License:Open Source License

private CMSSignedData getCNIPA_CMS() throws CMSException, FileNotFoundException {

    FileInputStream is = null;/*from   w w w .j  a va2  s .  c  o m*/

    is = new FileInputStream(CAFilePath);

    return new CMSSignedData(is);
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Returns the digest OID algorithm from a pkcs7 signature The return value
 * for sha1 is e.g. "1.3.14.3.2.26".//  w w  w  .  j av  a 2  s. c om
 */
public String getDigestAlgOIDFromSignature(byte[] signature) throws Exception {
    if (signature == null) {
        throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Signature is absent");
    }
    CMSSignedData signedData = new CMSSignedData(signature);
    SignerInformationStore signers = signedData.getSignerInfos();
    Collection signerCollection = signers.getSigners();
    Iterator iterator = signerCollection.iterator();
    while (iterator.hasNext()) {
        SignerInformation signerInfo = (SignerInformation) iterator.next();
        return (signerInfo.getDigestAlgOID());
    }
    throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Unable to identify signature algorithm.");
}

From source file:de.rub.dez6a3.jpdfsigner.TimeStampToken.java

License:Open Source License

TimeStampToken(ContentInfo contentInfo) throws TSPException, IOException {
    this(new CMSSignedData(contentInfo));
}

From source file:ec.gov.informatica.firmadigital.signature.BouncyCastleSignatureProcessor.java

License:Open Source License

public byte[] verify(byte[] signedBytes) throws SignatureVerificationException {
    try {//w  w w.  j av a2 s  .c o m
        Signature sig = Signature.getInstance("Sha1withRSAEncryption");
        CMSSignedData signedData = new CMSSignedData(signedBytes);
        CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC");
        Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
        for (SignerInformation signer : signers) {
            Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
            if (!certCollection.isEmpty()) {
                X509Certificate cert = (X509Certificate) certCollection.iterator().next();
                if (!signer.verify(cert.getPublicKey(), "BC")) {
                    throw new SignatureVerificationException("La firma no verifico con " + signer.getSID());
                }
                setCert(cert);
            }
        }

        CMSProcessable signedContent = signedData.getSignedContent();
        System.out.println("Tiene:" + signedContent.getContent());
        return (byte[]) signedContent.getContent();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e); // FIXME

    } catch (CMSException e) {
        throw new RuntimeException(e); // FIXME

    }
}