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:ec.gov.informatica.firmadigital.signature.BouncyCastleSignatureProcessor.java

License:Open Source License

@Override
public byte[] addSignature(byte[] signedBytes, PrivateKey privateKey, Certificate[] chain) {
    X509Certificate cert = (X509Certificate) chain[0];

    try {/*  ww w  .j  av  a 2s  .c o m*/
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSigner(privateKey, cert, CMSSignedDataGenerator.DIGEST_SHA1);

        CertStore certs = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(Arrays.asList(chain)));

        CMSSignedData signedData = new CMSSignedData(signedBytes);
        SignerInformationStore signers = signedData.getSignerInfos();
        CertStore existingCerts = signedData.getCertificatesAndCRLs("Collection", "BC");
        X509Store x509Store = signedData.getAttributeCertificates("Collection", "BC");

        // add new certs
        generator.addCertificatesAndCRLs(certs);
        // add existing certs
        generator.addCertificatesAndCRLs(existingCerts);
        // add existing certs attributes
        generator.addAttributeCertificates(x509Store);
        // add existing signers
        generator.addSigners(signers);

        CMSProcessable content = signedData.getSignedContent();
        signedData = generator.generate(content, true, "BC");
        return signedData.getEncoded();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    } catch (CMSException e) {
        throw new RuntimeException(e);
    } catch (NoSuchStoreException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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álida, no hace nada. Si no es
 * válida, lanza una excepción.
 * @param sign Firma que se desea validar.
 * @param data Datos para la comprobación.
 * @throws CMSException Cuando la firma no tenga una estructura válida.
 * @throws CertStoreException Cuando se encuentra un error en los certificados de
 * firma o estos no pueden recuperarse./*from  w  w  w  .ja va 2s.  c  o  m*/
 * @throws CertificateExpiredException Cuando el certificado estáa caducado.
 * @throws CertificateNotYetValidException Cuando el certificado aun no es vá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 w ww  .ja v  a  2 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:es.gob.afirma.signers.tsp.pkcs7.CMSTimestamper.java

License:Open Source License

/** A&ntilde;ade un sello de tiempo a las firmas encontradas dentro de una estructura PKCS#7.
 * @param pkcs7 Estructura que contiene las firmas a estampar un sello de tiempo
 * @param hashAlgorithm Algoritmo de huella digital a usar en los sellos de tiempo (si se indica <code>null</code> se usa SHA-1)
 * @param time Tiempo del sello/*from ww  w.  ja  v a 2s  .co  m*/
 * @return Nueva estructura PKCS#7 con los sellos de tiempo a&ntilde;adidos
 * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella digital del sello de tiempo
 * @throws AOException Cuando ocurren errores gen&eacute;ricos
 * @throws IOException Si hay errores de entrada / salida */
public byte[] addTimestamp(final byte[] pkcs7, final String hashAlgorithm, final Calendar time)
        throws NoSuchAlgorithmException, AOException, IOException {

    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(hashAlgorithm);

    final CMSSignedData signedData;
    try {
        signedData = new CMSSignedData(pkcs7);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Los datos de entrada no son un SignedData de CMS: " + e); //$NON-NLS-1$
    }

    final SignerInformationStore origSignerInfoStore = signedData.getSignerInfos();

    // Insertamos un sello de tiempo en cada una de las firmas encontradas en el PKCS#7
    final List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>();

    final Collection<?> ovSigners = origSignerInfoStore.getSigners();
    for (final Object name : ovSigners) {

        final SignerInformation si = (SignerInformation) name;

        final byte[] tsToken = getTimeStampToken(
                MessageDigest.getInstance(digestAlgorithm).digest(si.getSignature()), digestAlgorithm, time);

        final ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(tsToken));
        final ASN1Primitive derObj = is.readObject();
        is.close();
        final DERSet derSet = new DERSet(derObj);

        final Attribute unsignAtt = new Attribute(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID),
                derSet);

        final Hashtable<ASN1ObjectIdentifier, Attribute> ht = new Hashtable<ASN1ObjectIdentifier, Attribute>();
        ht.put(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID), unsignAtt);

        final AttributeTable unsignedAtts = new AttributeTable(ht);

        vNewSigners.add(SignerInformation.replaceUnsignedAttributes(si, unsignedAtts));
    }

    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(vNewSigners)).getEncoded();

}

From source file:es.mityc.firmaJava.ts.TSCliente.java

License:LGPL

/**
 * Este mtodo valida el Sello de Tiempo/* w ww. ja v  a  2 s  .  c  o m*/
 * @param binarioaSellar fichero binario a validar
 * @param sellodeTiempo El Sello de Tiempo se ingresa en formato binario
 * @return TSValidacion Valores TSA
 * @throws NoSuchAlgorithmException
 * @throws TSPException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws CertStoreException
 * @throws TSClienteError
 */
public static TSValidacion validarSelloTiempo(byte[] binarioaSellar, byte[] sellodeTiempo)
        throws NoSuchAlgorithmException, TSPException, IOException, NoSuchProviderException, CertStoreException,
        TSClienteError {

    //       Set permitidos = new HashSet(Arrays.asList(TSPAlgoritmos.getValoresPermitidos()));
    //       si el algoritmo pasado no es permitido o es nulo se usa el algortimo por defecto

    TimeStampToken tst = null;
    TSValidacion tsv = new TSValidacion();

    try {
        tst = new TimeStampToken(new CMSSignedData(sellodeTiempo));
    } catch (CMSException e) {
        // Intenta obtenerlo como una TimeStampResp
        try {
            TimeStampResponse tsr = new TimeStampResponse(sellodeTiempo);
            tst = tsr.getTimeStampToken();
            if (tst == null)
                throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2));
        } catch (TSPException ex) {
            throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2));
        } catch (IOException ex) {
            throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2));
        }
    }

    tsv.setTst(tst);
    TimeStampTokenInfo tokenInfo = tst.getTimeStampInfo();

    MessageDigest resumen = TSPAlgoritmos.getDigest(tokenInfo.getMessageImprintAlgOID());
    if (resumen == null) {
        tsv.setRespuesta(false);
        return tsv;
    }

    resumen.update(binarioaSellar);
    if (MessageDigest.isEqual(resumen.digest(), tst.getTimeStampInfo().getMessageImprintDigest())) {
        //TimeStampTokenInfo tokenInfo = tst.getTimeStampInfo();                          
        SimpleDateFormat formato = new SimpleDateFormat(FORMATO_FECHA);
        tsv.setFecha(formato.format(tokenInfo.getGenTime()));
        tsv.setFechaDate(tokenInfo.getGenTime());

        GenTimeAccuracy precision = tokenInfo.getGenTimeAccuracy();
        tsv.setPrecision(precision);

        long accuLong = 0;
        if (precision != null) {
            accuLong = (precision.getMicros() * 1L) + (precision.getMillis() * 1000L)
                    + (precision.getSeconds() * 1000000L);
        }
        tsv.setPrecisionLong(accuLong);

        tsv.setSello(tokenInfo.getSerialNumber());
        tsv.setFirmaDigest(new String(Base64Coder.encode(tokenInfo.getMessageImprintDigest())));
        tsv.setRespuesta(true);
        tsv.setSelloAlg(tokenInfo.getMessageImprintAlgOID());
        tsv.setEmisor(tst.getSID().getIssuer());
    } else {
        tsv.setRespuesta(false);
    }
    return tsv;
}

From source file:eu.europa.ec.markt.dss.applet.model.SignatureWizardModel.java

License:Open Source License

private Filetype getFiletype(FileDocument file) {
    if (file.getName() != null && file.getName().toLowerCase().endsWith(".xml")) {
        return Filetype.XML;
    }//  ww  w.j  av a2  s .co  m
    FileInputStream input = null;
    try {
        input = file.openStream();
        byte[] preamble = new byte[5];
        int read = input.read(preamble);
        input.close();
        if (read < 5) {
            throw new RuntimeException();
        }
        String preambleString = new String(preamble);
        if (preambleString.equals("<?xml")) {
            return Filetype.XML;
        } else if (preambleString.equals("%PDF-")) {
            return Filetype.PDF;
        } else {
            try {
                input = file.openStream();
                new CMSSignedData(input);
                return Filetype.CMS;
            } catch (Exception ex) {
                return Filetype.BINARY;
            } finally {
                input.close();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Cannot determine the mime/type");
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:eu.europa.ec.markt.dss.applet.util.FileTypeDetectorUtils.java

License:Open Source License

/**
 * @param file/*from   www  .j  a va 2  s  . c  o  m*/
 * @return
 * @throws FileNotFoundException
 */
private static boolean isCMS(final File file) throws FileNotFoundException {
    FileInputStream inputStream = null;

    try {
        inputStream = new FileInputStream(file);
        new CMSSignedData(inputStream);
        return true;
    } catch (final CMSException e) {
        return false;
    } finally {
        DSSUtils.closeQuietly(inputStream);
    }
}

From source file:eu.europa.ec.markt.dss.applet.WizardFinishedPanel.java

License:Open Source License

private void signAndSaveFile() throws NoSuchAlgorithmException, IOException {
    SignatureTokenConnection connection = null;

    DocumentSignatureService service = model.createDocumentSignatureService();

    Document document = model.getOriginalFile();

    SignatureParameters parameters = new SignatureParameters();
    parameters.setSigningDate(new Date());
    parameters.setSigningCertificate((X509Certificate) model.getPrivateKey().getCertificate());
    if (model.getPrivateKey().getCertificateChain() != null) {
        parameters.setCertificateChain(//w  w w  .  j  av a 2s  . c  o m
                Arrays.asList((X509Certificate[]) model.getPrivateKey().getCertificateChain()));
    }
    parameters.setSignatureFormat(model.getSignatureFormat());
    parameters.setSignaturePackaging(model.getPackaging());
    parameters.setClaimedSignerRole(model.getClaimedRole());
    parameters.setSignaturePolicy(model.getSignaturePolicyType());
    parameters.setSignaturePolicyId(model.getSignaturePolicy());
    parameters.setSignaturePolicyHashValue(model.getSignaturePolicyValue());
    parameters.setSignaturePolicyHashAlgo(model.getSignaturePolicyAlgo());

    connection = model.createTokenConnection(getWizard());

    Document contentInCMS = null;
    if (service instanceof CAdESService
            && parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPING) {

        FileInputStream original = null;
        try {
            CMSSignedData cmsData = new CMSSignedData(model.getOriginalFile().openStream());
            if (cmsData != null && cmsData.getSignedContent() != null
                    && cmsData.getSignedContent().getContent() != null) {
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                cmsData.getSignedContent().write(buf);
                contentInCMS = new InMemoryDocument(buf.toByteArray());
            }
        } catch (CMSException ex) {

        } finally {
            if (original != null) {
                original.close();
            }
        }
    }

    Document signedDocument = null;
    if (contentInCMS != null) {
        byte[] signatureValue = connection.sign(service.toBeSigned(contentInCMS, parameters),
                DigestAlgorithm.SHA1, model.getPrivateKey());
        CAdESService cadesService = (CAdESService) service;
        signedDocument = cadesService.addASignatureToDocument(document, parameters, signatureValue);
    } else {
        byte[] signatureValue = connection.sign(service.toBeSigned(document, parameters), DigestAlgorithm.SHA1,
                model.getPrivateKey());
        signedDocument = service.signDocument(document, parameters, signatureValue);
    }

    FileOutputStream output = new FileOutputStream(model.getSignedFile());
    IOUtils.copy(signedDocument.openStream(), output);
    output.close();

}

From source file:eu.europa.ec.markt.dss.DSSASN1Utils.java

License:Open Source License

/**
 * If the {@code DSSDocument} is a CMS message and the signed content's content is not null then the {@code CMSSignedData} is returned.
 * All exceptions are hidden/*from ww  w.  ja  v  a2 s. com*/
 *
 * @param dssDocument
 * @return {@code CMSSignedData} or {@code null}
 */
public static CMSSignedData getOriginalSignedData(final DSSDocument dssDocument) {

    CMSSignedData originalSignedData = null;

    try {
        // check if input toSignDocument is already signed
        originalSignedData = new CMSSignedData(dssDocument.getBytes());
        if (originalSignedData.getSignedContent().getContent() == null) {
            originalSignedData = null;
        }
    } catch (Exception e) {
        // not a parallel signature
    }
    return originalSignedData;
}

From source file:eu.europa.ec.markt.dss.DSSASN1Utils.java

License:Open Source License

/**
 * This method generates a bouncycastle {@code TimeStampToken} based on base 64 encoded {@code String}.
 *
 * @param base64EncodedTimestamp//from ww w. j a  va 2  s  . com
 * @return bouncycastle {@code TimeStampToken}
 * @throws DSSException
 */
public static TimeStampToken createTimeStampToken(final String base64EncodedTimestamp) throws DSSException {

    try {

        final byte[] tokenBytes = DSSUtils.base64Decode(base64EncodedTimestamp);
        final CMSSignedData signedData = new CMSSignedData(tokenBytes);
        return new TimeStampToken(signedData);
    } catch (DSSException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    } catch (TSPException e) {
        throw new DSSException(e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}