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

/**
 * downloads and decodes given certificate, updates HashMap of results
 * //from   w w w  .j ava 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 {/*w w  w .j a v a 2  s.co  m*/
        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.guardtime.ksi.trust.CMSSignature.java

License:Apache License

public CMSSignature(byte[] signedData, byte[] cmsSignature) throws InvalidCmsSignatureException {
    try {//  w  w  w .  ja  v a  2  s.  c o  m
        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.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 ww . j ava  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. j a va  2 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:ee.ria.xroad.proxy.messagelog.TimestamperUtil.java

License:Open Source License

@SuppressWarnings("unchecked")
static TimeStampToken addSignerCertificate(TimeStampResponse tsResponse, X509Certificate signerCertificate)
        throws Exception {
    CMSSignedData cms = tsResponse.getTimeStampToken().toCMSSignedData();

    List<X509Certificate> collection = new ArrayList<>();
    collection.add(signerCertificate);/*w ww.  j  a v  a  2s.  c o  m*/
    collection.addAll(cms.getCertificates().getMatches(null));

    return new TimeStampToken(CMSSignedData.replaceCertificatesAndCRLs(cms, new JcaCertStore(collection),
            cms.getAttributeCertificates(), cms.getCRLs()));
}

From source file:es.gob.afirma.cert.signvalidation.ValidateBinarySignature.java

License:Open Source License

/** Verifica la valides de una firma. Si la firma es v&aacute;lida, no hace nada. Si no es
 * v&aacute;lida, lanza una excepci&oacute;n.
 * @param sign Firma que se desea validar.
 * @param data Datos para la comprobaci&oacute;n.
 * @throws CMSException Cuando la firma no tenga una estructura v&aacute;lida.
 * @throws CertStoreException Cuando se encuentra un error en los certificados de
 * firma o estos no pueden recuperarse.//from w  w w .j  a va  2  s  .co  m
 * @throws CertificateExpiredException Cuando el certificado est&aacute;a caducado.
 * @throws CertificateNotYetValidException Cuando el certificado aun no es v&aacute;lido.
 * @throws NoSuchAlgorithmException Cuando no se reconoce o soporta alguno de los
 * algoritmos utilizados en la firma.
 * @throws NoMatchDataException Cuando los datos introducidos no coinciden con los firmados.
 * @throws CRLException Cuando ocurre un error con las CRL de la firma.
 * @throws NoSuchProviderException Cuando no se encuentran los proveedores de seguridad necesarios para validar la firma
 * @throws IOException Cuando no se puede crear un certificado desde la firma para validarlo
 * @throws OperatorCreationException Cuando no se puede crear el validado de contenido de firma*/
private static void verifySignatures(final byte[] sign, final byte[] data)
        throws CMSException, CertStoreException, NoSuchAlgorithmException, NoMatchDataException, CRLException,
        NoSuchProviderException, CertificateException, IOException, OperatorCreationException {

    final CMSSignedData s;
    if (data == null) {
        s = new CMSSignedData(sign);
    } else {
        s = new CMSSignedData(new CMSProcessableByteArray(data), sign);
    }
    final Store<X509CertificateHolder> store = s.getCertificates();

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$

    for (final Object si : s.getSignerInfos().getSigners()) {
        final SignerInformation signer = (SignerInformation) si;

        final Iterator<X509CertificateHolder> certIt = store
                .getMatches(new CertHolderBySignerIdSelector(signer.getSID())).iterator();
        final X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(certIt.next().getEncoded()));

        if (!signer
                .verify(new SignerInformationVerifier(new DefaultCMSSignatureAlgorithmNameGenerator(),
                        new DefaultSignatureAlgorithmIdentifierFinder(), new JcaContentVerifierProviderBuilder()
                                .setProvider(new BouncyCastleProvider()).build(cert),
                        new BcDigestCalculatorProvider()))) {
            throw new CMSException("Firma no valida"); //$NON-NLS-1$
        }

    }

}

From source file:es.gob.afirma.signature.ValidateBinarySignature.java

License:Open Source License

/** Verifica la valides de una firma. Si la firma es v&aacute;lida, no hace nada. Si no es
 * v&aacute;lida, lanza una excepci&oacute;n.
 * @param sign Firma que se desea validar.
 * @param data Datos para la comprobaci&oacute;n.
 * @throws CMSException Cuando la firma no tenga una estructura v&aacute;lida.
 * @throws CertStoreException Cuando se encuentra un error en los certificados de
 * firma o estos no pueden recuperarse./*from  www.j  a  v a2 s . c  o m*/
 * @throws CertificateExpiredException Cuando el certificado est&aacute;a caducado.
 * @throws CertificateNotYetValidException Cuando el certificado aun no es v&aacute;lido.
 * @throws NoSuchAlgorithmException Cuando no se reconoce o soporta alguno de los
 * algoritmos utilizados en la firma.
 * @throws NoMatchDataException Cuando los datos introducidos no coinciden con los firmados.
 * @throws CRLException Cuando ocurre un error con las CRL de la firma.
 * @throws NoSuchProviderException Cuando no se encuentran los proveedores de seguridad necesarios para validar la firma
 * @throws IOException Cuando no se puede crear un certificado desde la firma para validarlo
 * @throws OperatorCreationException Cuando no se puede crear el validado de contenido de firma*/
private static void verifySignatures(final byte[] sign, final byte[] data)
        throws CMSException, CertStoreException, NoSuchAlgorithmException, NoMatchDataException, CRLException,
        NoSuchProviderException, CertificateException, IOException, OperatorCreationException {

    final CMSSignedData s;
    if (data == null) {
        s = new CMSSignedData(sign);
    } else {
        s = new CMSSignedData(new CMSProcessableByteArray(data), sign);
    }
    final Store store = s.getCertificates();

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$

    for (final Object si : s.getSignerInfos().getSigners()) {
        final SignerInformation signer = (SignerInformation) si;

        final Iterator<X509CertificateHolder> certIt = store
                .getMatches(new CertHolderBySignerIdSelector(signer.getSID())).iterator();
        final X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(certIt.next().getEncoded()));

        if (!signer
                .verify(new SignerInformationVerifier(new DefaultCMSSignatureAlgorithmNameGenerator(),
                        new DefaultSignatureAlgorithmIdentifierFinder(), new JcaContentVerifierProviderBuilder()
                                .setProvider(new BouncyCastleProvider()).build(cert),
                        new BcDigestCalculatorProvider()))) {
            throw new CMSException("Firma no valida"); //$NON-NLS-1$
        }

    }

}

From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to verify the signature of the exCap in a form of CMSSignedData
 * @param signedData: the signed data/*from  ww  w  .  j a v  a2 s. c om*/
 * @return: true if the signature is valid, false otherwise
 * @throws CMSException
 * @throws OperatorException
 */
public static boolean validateCapSignature(CMSSignedData signedData) throws CMSException, OperatorException {
    Store certs = signedData.getCertificates();
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator it = signers.getSigners().iterator();

    if (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertificateHolder cert = (X509CertificateHolder) certs.getMatches(signer.getSID()).iterator()
                .next();

        SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder(
                new DefaultCMSSignatureAlgorithmNameGenerator(),
                new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(),
                new BcDigestCalculatorProvider()).build(cert);

        return signer.verify(verifier);
    }

    return false;
}

From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to verify exCap's signature with the issuer certificate stored in
 * the signed data /*from  w  w w .  j a v a 2 s  . c o m*/
 * @param text: the original signed text
 * @param signature: the signature in byte[]
 * @return: true if signature is valid, false otherwise
 * @throws CMSException
 * @throws OperatorException
 */
public static boolean validateCapSignature(String text, byte[] signature)
        throws CMSException, OperatorException {
    CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature);
    Store certs = signedData.getCertificates();
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator it = signers.getSigners().iterator();

    if (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertificateHolder cert = (X509CertificateHolder) certs.getMatches(signer.getSID()).iterator()
                .next();

        SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder(
                new DefaultCMSSignatureAlgorithmNameGenerator(),
                new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(),
                new BcDigestCalculatorProvider()).build(cert);

        return signer.verify(verifier);
    }
    return false;
}