Example usage for org.bouncycastle.tsp TimeStampToken TimeStampToken

List of usage examples for org.bouncycastle.tsp TimeStampToken TimeStampToken

Introduction

In this page you can find the example usage for org.bouncycastle.tsp TimeStampToken TimeStampToken.

Prototype

public TimeStampToken(CMSSignedData signedData) throws TSPException, IOException 

Source Link

Usage

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

License:LGPL

/**
 * Este mtodo valida el Sello de Tiempo//from w  w w .  j a  v a  2  s .c  om
 * @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.DSSASN1Utils.java

License:Open Source License

/**
 * This method generates a bouncycastle {@code TimeStampToken} based on base 64 encoded {@code String}.
 *
 * @param base64EncodedTimestamp/* w w w  . j  av a2 s .  c  o  m*/
 * @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);
    }
}

From source file:eu.europa.ec.markt.dss.signature.pdf.pdfbox.PdfBoxDocTimestampInfo.java

License:Open Source License

/**
 * @param validationCertPool/*from  w ww  . ja v a2  s.  co  m*/
 * @param outerCatalog       the PDF Dict of the outer document, if the PDFDocument in a enclosed revision. Can be null.
 * @param document           the signed PDFDocument
 * @param cms                the CMS (CAdES) bytes
 * @param inputStream        the stream of the whole signed document
 * @throws IOException
 */
PdfBoxDocTimestampInfo(CertificatePool validationCertPool, PdfDict outerCatalog, PDDocument document,
        PDSignature signature, byte[] cms, InputStream inputStream) throws DSSException, IOException {
    super(validationCertPool, outerCatalog, document, signature, cms, inputStream);
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(cms));

        TimestampType timestampType = TimestampType.SIGNATURE_TIMESTAMP;
        if (document.getDocumentCatalog().getCOSDictionary().containsKey("DSS")) {
            timestampType = TimestampType.ARCHIVE_TIMESTAMP;
        }
        timestampToken = new TimestampToken(timeStampToken, timestampType, validationCertPool);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created PdfBoxDocTimestampInfo {}: {}", timestampType, uniqueId());
        }
    } catch (CMSException e) {
        throw new DSSException(e);
    } catch (TSPException e) {
        throw new DSSException(e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.asic.ASiCTimestampDocumentValidator.java

License:Open Source License

/**
 * The default constructor for ASiCXMLDocumentValidator.
 *
 * @param timestamp        {@code DSSDocument} representing the timestamp to validate
 * @param detachedContents the {@code List} containing the potential signed documents
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */// w  ww.j  a va2s  .c  o  m
public ASiCTimestampDocumentValidator(final DSSDocument timestamp, final List<DSSDocument> detachedContents)
        throws DSSException {

    super(timestamp);

    try {
        timeStampToken = new TimeStampToken(cmsSignedData);
    } catch (TSPException e) {
        throw new DSSException(e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
    if (detachedContents == null || detachedContents.size() == 0) {
        throw new DSSNullException(DSSDocument.class, "detachedContents");
    }
    timestampExternalContents = detachedContents;
}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java

License:Open Source License

private List<TimestampToken> getTimestampList(final ASN1ObjectIdentifier attrType,
        final TimestampType timestampType, final ArchiveTimestampType archiveTimestampType) {

    final List<TimestampToken> list = new ArrayList<TimestampToken>();

    final AttributeTable attributes;
    if (attrType.equals(PKCSObjectIdentifiers.id_aa_ets_contentTimestamp)) {

        attributes = signerInformation.getSignedAttributes();
    } else {//w w w  .ja  va  2s  . com

        attributes = signerInformation.getUnsignedAttributes();
    }
    if (attributes == null) {
        return list;
    }
    final ASN1EncodableVector archiveList = attributes.getAll(attrType);
    for (int i = 0; i < archiveList.size(); i++) {
        final Attribute attribute = (Attribute) archiveList.get(i);

        final ASN1Set attrValues = attribute.getAttrValues();
        for (final ASN1Encodable value : attrValues.toArray()) {
            try {
                TimeStampToken token = new TimeStampToken(
                        new CMSSignedData(value.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
                final TimestampToken timestampToken = new TimestampToken(token, timestampType, certPool);
                timestampToken.setArchiveTimestampType(archiveTimestampType);
                list.add(timestampToken);
            } catch (Exception e) {
                throw new RuntimeException("Parsing error", e);
            }
        }
    }
    return list;
}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java

License:Open Source License

/**
 * Remove any archive-timestamp-v2/3 attribute added after the timestampToken
 *///from   ww  w .  j a  va  2s  .c om
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes,
        TimestampToken timestampToken) {

    ASN1EncodableVector result = new ASN1EncodableVector();
    for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

        final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
        final ASN1ObjectIdentifier attrType = attribute.getAttrType();
        if (OID.id_aa_ets_archiveTimestampV2.equals(attrType)
                || OID.id_aa_ets_archiveTimestampV3.equals(attrType)) {
            try {

                TimeStampToken token = new TimeStampToken(new CMSSignedData(DSSASN1Utils
                        .getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive())));
                if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
                    continue;
                }
            } catch (Exception e) {
                throw new DSSException(e);
            }
        }
        result.add(unauthenticatedAttributes.getObjectAt(ii));
    }
    return new DERSequence(result);
}

From source file:eu.europa.esig.dss.asic.validation.ASiCTimestampDocumentValidator.java

License:Open Source License

/**
 * The default constructor for ASiCXMLDocumentValidator.
 *
 * @param timestamp        {@code DSSDocument} representing the timestamp to validate
 * @param detachedContents the {@code List} containing the potential signed documents
 * @throws eu.europa.esig.dss.DSSException
 *///from   ww w .  jav  a  2  s. com
public ASiCTimestampDocumentValidator(final DSSDocument timestamp, final List<DSSDocument> detachedContents)
        throws DSSException {

    super(timestamp);

    try {
        timeStampToken = new TimeStampToken(cmsSignedData);
    } catch (TSPException e) {
        throw new DSSException(e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
    if (detachedContents == null || detachedContents.size() == 0) {
        throw new NullPointerException("detachedContents");
    }
    timestampExternalContents = detachedContents;
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

private List<TimestampToken> createTimestamps(final ASN1ObjectIdentifier attrType,
        final TimestampType timestampType, final ArchiveTimestampType archiveTimestampType) {

    final List<TimestampToken> timestampTokenList = new ArrayList<TimestampToken>();
    final AttributeTable attributes = attrType.equals(id_aa_ets_contentTimestamp)
            ? signerInformation.getSignedAttributes()
            : signerInformation.getUnsignedAttributes();
    if (attributes != null) {

        final ASN1EncodableVector allAttributes = attributes.getAll(attrType);
        for (int ii = 0; ii < allAttributes.size(); ii++) {
            final Attribute attribute = (Attribute) allAttributes.get(ii);
            final ASN1Set attrValues = attribute.getAttrValues();
            for (final ASN1Encodable value : attrValues.toArray()) {
                if (value instanceof DEROctetString) {
                    LOG.warn("Illegal content for timestamp (OID : " + attrType
                            + ") : OCTET STRING is not allowed !");
                } else {
                    try {
                        byte[] encoded = value.toASN1Primitive().getEncoded();
                        final CMSSignedData signedData = new CMSSignedData(encoded);
                        final TimeStampToken token = new TimeStampToken(signedData);
                        final TimestampToken timestampToken = new TimestampToken(token, timestampType,
                                certPool);

                        timestampToken.setArchiveTimestampType(archiveTimestampType);
                        timestampTokenList.add(timestampToken);
                    } catch (Exception e) {
                        throw new DSSException(e);
                    }// ww  w . j a  v a 2  s.c o m
                }
            }
        }
    }
    return timestampTokenList;
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * Remove any archive-timestamp-v2/3 attribute added after the
 * timestampToken//from   w  w w .ja v a 2 s . c o m
 */
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes,
        TimestampToken timestampToken) {
    ASN1EncodableVector result = new ASN1EncodableVector();
    for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

        final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
        final ASN1ObjectIdentifier attrType = attribute.getAttrType();
        if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) {
            try {

                TimeStampToken token = new TimeStampToken(new CMSSignedData(DSSASN1Utils
                        .getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive())));
                if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
                    continue;
                }
            } catch (Exception e) {
                throw new DSSException(e);
            }
        }
        result.add(unauthenticatedAttributes.getObjectAt(ii));
    }
    return new DERSequence(result);
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxDocTimestampInfo.java

License:Open Source License

/**
 * @param validationCertPool/*from   ww  w .  j a  v  a  2s.c o m*/
 * @param dssDictionary
 *            the DSS dictionary
 * @param cms
 *            the CMS (CAdES) bytes
 * @param isArchiveTimestamp
 * @param inputStream
 *            the stream of the whole signed document
 * @throws DSSException
 */
PdfBoxDocTimestampInfo(CertificatePool validationCertPool, PDSignature signature, PdfDssDict dssDictionary,
        byte[] cms, byte[] signedContent, boolean isArchiveTimestamp) throws DSSException {
    super(signature, dssDictionary, cms, signedContent);
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(cms));
        TimestampType timestampType = TimestampType.SIGNATURE_TIMESTAMP;
        if (isArchiveTimestamp) {
            timestampType = TimestampType.ARCHIVE_TIMESTAMP;
        }
        timestampToken = new TimestampToken(timeStampToken, timestampType, validationCertPool);
        logger.debug("Created PdfBoxDocTimestampInfo {} : {}", timestampType, uniqueId());
    } catch (Exception e) {
        throw new DSSException(e);
    }
}