Example usage for org.bouncycastle.tsp TimeStampResponse getTimeStampToken

List of usage examples for org.bouncycastle.tsp TimeStampResponse getTimeStampToken

Introduction

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

Prototype

public TimeStampToken getTimeStampToken() 

Source Link

Usage

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);//from  ww w  .java 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:ee.sk.digidoc.factory.BouncyCastleTimestampFactory.java

License:Open Source License

/**
 * Verifies this one timestamp/*w  ww. j a  va 2s  .  com*/
 * @param ts TimestampInfo object
 * @param tsaCert TSA certificate
 * @returns result of verification
 */
public boolean verifyTimestamp(TimestampInfo ts, X509Certificate tsaCert) throws DigiDocException {
    boolean bOk = false;

    if (m_logger.isDebugEnabled())
        m_logger.debug("Verifying TS: " + ts.getId() + " nr: " + ts.getSerialNumber());
    if (!SignedDoc.compareDigests(ts.getMessageImprint(), ts.getHash())) {
        m_logger.error("TS digest: " + Base64Util.encode(ts.getMessageImprint()) + " real digest: "
                + Base64Util.encode(ts.getHash()));
        throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_VERIFY,
                "Bad digest for timestamp: " + ts.getId(), null);
    }
    TimeStampResponse resp = ts.getTimeStampResponse();
    if (resp != null) {
        if (m_logger.isDebugEnabled())
            m_logger.debug("TS status: " + resp.getStatus());
        if (resp.getStatus() == PKIStatus.GRANTED || resp.getStatus() == PKIStatus.GRANTED_WITH_MODS) {
            try {
                resp.getTimeStampToken().validate(tsaCert, "BC");
                bOk = true;
            } catch (Exception ex) {
                bOk = false;
                m_logger.error("Timestamp verification error: " + ex);
                throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_VERIFY,
                        "Invalid timestamp: " + ex.getMessage(), ex);
            }
        } else
            throw new DigiDocException(DigiDocException.ERR_TIMESTAMP_VERIFY,
                    "Invalid timestamp status: " + resp.getStatus(), null);
    }

    return bOk;
}

From source file:es.gob.afirma.signers.tsp.pkcs7.CMSTimestamper.java

License:Open Source License

/** Obtiene directamente el <i>token</i> de sello de tiempo seg&uacute;n RFC3161.
 * @param imprint Huella digital de los datos sobre los que se quiere obtener el sello de tiempo
 * @param hashAlgorithm Algoritmo de huella digital usado para calcular la huella indicada en <code>imprint</code>.
 * @param time Tiempo de solicitud del sello.
 * @return <i>Token</i> de sello de tiempo seg&uacute;n RFC3161.
 * @throws AOException Si se produce un error en el protocolo TSA o en ASN.1.
 * @throws IOException Si hay errores en la comunicaci&oacute;n o en la lectura de datos con la TSA. */
public byte[] getTimeStampToken(final byte[] imprint, final String hashAlgorithm, final Calendar time)
        throws AOException, IOException {

    final TimeStampRequest request = this.tsqGenerator.generate(
            new ASN1ObjectIdentifier(hashAlgorithm != null ? AOAlgorithmID.getOID(hashAlgorithm)
                    : X509ObjectIdentifiers.id_SHA1.getId()),
            imprint, BigInteger.valueOf(time != null ? time.getTimeInMillis() : System.currentTimeMillis()));

    final byte[] requestBytes = request.getEncoded();

    final byte[] rawResponse = getTSAResponse(requestBytes);
    final TimeStampResponse response;
    try {/*from  w  ww. j a v a2 s  .  co m*/
        response = new TimeStampResponse(rawResponse);
    } catch (final Exception e) {
        throw new AOException("Error obteniendo la respuesta de la TSA: " + e, e); //$NON-NLS-1$
    }

    // Validamos los atributos de la respuesta (RFC 3161 PKIStatus)
    try {
        response.validate(request);
    } catch (final Exception e) {
        throw new AOException("Error validando la respuesta de la TSA: " + e, e); //$NON-NLS-1$
    }
    final PKIFailureInfo failure = response.getFailInfo();
    final int value = failure == null ? 0 : failure.intValue();
    if (value != 0) {
        throw new AOException("Respuesta invalida de la TSA ('" + this.tsaURL + "') con el codigo " + value); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Extraemos el token de sello de tiempo (quitando la informacion de estado de las comunicaciones)
    final TimeStampToken tsToken = response.getTimeStampToken();
    if (tsToken == null) {
        throw new AOException("La respuesta de la TSA ('" + this.tsaURL + "') no es un sello de tiempo valido: " //$NON-NLS-1$//$NON-NLS-2$
                + new String(rawResponse));
    }

    return tsToken.getEncoded();
}

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

License:LGPL

/**
 * Este mtodo valida el Sello de Tiempo//w w  w  .j  a  va2 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.signature.pades.PAdESProfileLTV.java

License:Open Source License

@Override
public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters)
        throws IOException {

    try {/*  ww w  .  j a v a  2 s  .c  om*/
        final PdfReader reader = new PdfReader(document.openStream());
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        final PdfStamper stamper = new PdfStamper(reader, output, '\0', true);

        LTVSignatureValidationCallback callback = new LTVSignatureValidationCallback(stamper);
        pdfSignatureService.validateSignatures(document.openStream(), callback);

        PdfIndirectReference certsRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(callback.getCertsArray(), certsRef, false);

        PdfDictionary dssDictionary = new PdfDictionary(new PdfName("DSS"));
        PdfDictionary vriDictionary = new PdfDictionary(new PdfName("VRI"));

        PdfDictionary sigVriDictionary = new PdfDictionary();

        integrateCRL(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary);

        integrateOCSP(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary);

        // Add the signature's VRI dictionary, hashing the signature block from the callback method
        MessageDigest _md = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName());
        String hexHash = Hex.encodeHexString(_md.digest(callback.getSignatureBlock())).toUpperCase();

        PdfIndirectReference sigVriRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(sigVriDictionary, sigVriRef, false);
        vriDictionary.put(new PdfName(hexHash), sigVriRef);
        PdfIndirectReference vriRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(vriDictionary, vriRef, false);

        // Add final objects to DSS dictionary
        dssDictionary.put(new PdfName("VRI"), vriRef);
        dssDictionary.put(new PdfName("Certs"), certsRef);

        PdfIndirectReference dssRef = stamper.getWriter().getPdfIndirectReference();
        stamper.getWriter().addToBody(dssDictionary, dssRef, false);
        reader.getCatalog().put(new PdfName("DSS"), dssRef);

        // /Extensions<</ADBE<</BaseVersion/1.7/ExtensionLevel 5>>>>
        PdfDeveloperExtension etsiExtension = new PdfDeveloperExtension(PdfName.ADBE, new PdfName("1.7"), 5);
        stamper.getWriter().addDeveloperExtension(etsiExtension);
        stamper.getWriter().addToBody(reader.getCatalog(), reader.getCatalog().getIndRef(), false);

        stamper.close();
        output.close();

        Document extendedDocument = new InMemoryDocument(output.toByteArray());

        ByteArrayOutputStream ltvDoc = new ByteArrayOutputStream();

        ITextPDFDocTimeSampService service = new ITextPDFDocTimeSampService();
        byte[] digest = service.digest(extendedDocument.openStream(), parameters);
        TimeStampResponse tsToken = tspSource.getTimeStampResponse(parameters.getDigestAlgorithm(), digest);
        service.sign(extendedDocument.openStream(), tsToken.getTimeStampToken().getEncoded(), ltvDoc,
                parameters);

        return new InMemoryDocument(ltvDoc.toByteArray());

    } catch (DocumentException ex) {
        throw new RuntimeException(ex);
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

License:Open Source License

protected XAdESTimeStampType createXAdESTimeStamp(DigestAlgorithm algorithm, byte[] digest) throws IOException {

    LOG.info("Create timestamp for digest " + new String(Hex.encodeHex(digest)));
    TimeStampResponse resp = tspSource.getTimeStampResponse(algorithm, digest);
    byte[] timeStampToken = resp.getTimeStampToken().getEncoded();

    XAdESTimeStampType xadesTimeStamp = xadesObjectFactory.createXAdESTimeStampType();
    CanonicalizationMethodType c14nMethod = getXmldsigObjectFactory().createCanonicalizationMethodType();
    c14nMethod.setAlgorithm(CanonicalizationMethod.EXCLUSIVE);
    xadesTimeStamp.setCanonicalizationMethod(c14nMethod);
    xadesTimeStamp.setId("time-stamp-" + UUID.randomUUID().toString());

    EncapsulatedPKIDataType encapsulatedTimeStamp = xadesObjectFactory.createEncapsulatedPKIDataType();
    encapsulatedTimeStamp.setValue(timeStampToken);
    encapsulatedTimeStamp.setId("time-stamp-token-" + UUID.randomUUID().toString());
    List<Serializable> timeStampContent = xadesTimeStamp.getEncapsulatedTimeStampOrXMLTimeStamp();
    timeStampContent.add(encapsulatedTimeStamp);

    return xadesTimeStamp;
}

From source file:eu.europa.ec.markt.dss.validation102853.tsp.OnlineTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {

    try {/*from www  . j  a va  2  s  .com*/

        if (LOG.isTraceEnabled()) {

            LOG.trace("Timestamp digest algorithm: " + digestAlgorithm.getName());
            LOG.trace("Timestamp digest value    : " + DSSUtils.toHex(digest));
        }

        // Setup the time stamp request
        final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (policyOid != null) {
            tsqGenerator.setReqPolicy(policyOid);
        }
        final long val = System.currentTimeMillis();
        final BigInteger nonce = BigInteger.valueOf(val);
        final ASN1ObjectIdentifier asn1ObjectIdentifier = digestAlgorithm.getOid();
        final TimeStampRequest request = tsqGenerator.generate(asn1ObjectIdentifier, digest, nonce);
        final byte[] requestBytes = request.getEncoded();

        // Call the communications layer
        byte[] respBytes;
        if (dataLoader != null) {

            respBytes = dataLoader.post(tspServer, requestBytes);
            //if ("base64".equalsIgnoreCase(encoding)) {
            //respBytes = DSSUtils.base64Decode(respBytes);
            //}
        } else {

            respBytes = getTSAResponse(requestBytes);
        }
        // Handle the TSA response
        final TimeStampResponse timeStampResponse = new TimeStampResponse(respBytes);
        LOG.info("Status: " + timeStampResponse.getStatusString());
        final TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
        if (timeStampToken != null) {

            LOG.info("SID: " + timeStampToken.getSID());
        }
        return timeStampToken;
    } catch (TSPException e) {
        throw new DSSException("Invalid TSP response", e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.esig.dss.client.tsp.OnlineTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {
    try {//from  w  w w  . j a va2  s  .c  o  m
        if (logger.isTraceEnabled()) {
            logger.trace("Timestamp digest algorithm: " + digestAlgorithm.getName());
            logger.trace("Timestamp digest value    : " + Hex.encodeHexString(digest));
        }

        // Setup the time stamp request
        final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (policyOid != null) {
            tsqGenerator.setReqPolicy(policyOid);
        }

        ASN1ObjectIdentifier asn1ObjectIdentifier = new ASN1ObjectIdentifier(digestAlgorithm.getOid());
        TimeStampRequest timeStampRequest = null;
        if (nonceSource == null) {
            timeStampRequest = tsqGenerator.generate(asn1ObjectIdentifier, digest);
        } else {
            timeStampRequest = tsqGenerator.generate(asn1ObjectIdentifier, digest, nonceSource.getNonce());
        }

        final byte[] requestBytes = timeStampRequest.getEncoded();

        // Call the communications layer
        if (dataLoader == null) {
            dataLoader = new NativeHTTPDataLoader();
        }
        byte[] respBytes = dataLoader.post(tspServer, requestBytes);

        // Handle the TSA response
        final TimeStampResponse timeStampResponse = new TimeStampResponse(respBytes);

        // Validates nonce, policy id, ... if present
        timeStampResponse.validate(timeStampRequest);

        String statusString = timeStampResponse.getStatusString();
        if (statusString != null) {
            logger.info("Status: " + statusString);
        }

        final TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();

        if (timeStampToken != null) {
            logger.info("TSP SID : SN " + timeStampToken.getSID().getSerialNumber() + ", Issuer "
                    + timeStampToken.getSID().getIssuer());
        }

        return timeStampToken;
    } catch (TSPException e) {
        throw new DSSException("Invalid TSP response", e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.esig.dss.cookbook.mock.MockTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {

    final String signatureAlgorithm = getSignatureAlgorithm(digestAlgorithm, digest);

    final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);// w ww  .  j av  a  2 s . c  om

    /**
     * The code below guarantee that the dates of the two successive
     * timestamps are different. This is activated only if timestampDate is provided at
     * construction time
     */
    Date timestampDate_ = new Date();

    if (policyOid != null) {
        tsqGenerator.setReqPolicy(policyOid);
    }

    TimeStampRequest tsRequest = null;
    if (useNonce) {
        final BigInteger nonce = BigInteger.valueOf(random.nextLong());
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest, nonce);
    } else {
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest);
    }

    try {
        final ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).build(key);
        final JcaX509CertificateHolder certHolder = new JcaX509CertificateHolder(cert.getCertificate());

        // that to make sure we generate the same timestamp data for the
        // same timestamp date
        AttributeTable signedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        signedAttributes = signedAttributes.add(PKCSObjectIdentifiers.pkcs_9_at_signingTime,
                new Time(timestampDate_));
        final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributes);
        AttributeTable unsignedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        final SimpleAttributeTableGenerator unsignedAttributeGenerator = new SimpleAttributeTableGenerator(
                unsignedAttributes);

        final DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();
        SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
                digestCalculatorProvider);
        sigInfoGeneratorBuilder.setSignedAttributeGenerator(signedAttributeGenerator);
        sigInfoGeneratorBuilder.setUnsignedAttributeGenerator(unsignedAttributeGenerator);
        final SignerInfoGenerator sig = sigInfoGeneratorBuilder.build(sigGen, certHolder);

        final DigestCalculator sha1DigestCalculator = DSSRevocationUtils.getSHA1DigestCalculator();

        final TimeStampTokenGenerator tokenGenerator = new TimeStampTokenGenerator(sig, sha1DigestCalculator,
                policyOid);
        final Set<X509Certificate> singleton = new HashSet<X509Certificate>();
        singleton.add(cert.getCertificate());
        tokenGenerator.addCertificates(new JcaCertStore(singleton));
        final TimeStampResponseGenerator generator = new TimeStampResponseGenerator(tokenGenerator,
                TSPAlgorithms.ALLOWED);

        Date responseDate = new Date();
        TimeStampResponse tsResponse = generator.generate(tsRequest, BigInteger.ONE, responseDate);
        final TimeStampToken timeStampToken = tsResponse.getTimeStampToken();
        return timeStampToken;
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    } catch (CertificateEncodingException e) {
        throw new DSSException(e);
    } catch (TSPException e) {
        throw new DSSException(e);
    }
}

From source file:net.jsign.timestamp.RFC3161Timestamper.java

License:Apache License

protected CMSSignedData timestamp(DigestAlgorithm algo, byte[] encryptedDigest)
        throws IOException, TimestampingException {
    TimeStampRequestGenerator reqgen = new TimeStampRequestGenerator();
    reqgen.setCertReq(true);//from  w  w  w.  ja v a 2s.c o m
    TimeStampRequest req = reqgen.generate(algo.oid, algo.getMessageDigest().digest(encryptedDigest));
    byte request[] = req.getEncoded();

    HttpURLConnection conn = (HttpURLConnection) tsaurl.openConnection();
    conn.setConnectTimeout(10000);
    conn.setReadTimeout(10000);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-type", "application/timestamp-query");
    conn.setRequestProperty("Content-length", String.valueOf(request.length));
    conn.setRequestProperty("Accept", "application/timestamp-query");
    conn.setRequestProperty("User-Agent", "Transport");

    conn.getOutputStream().write(request);
    conn.getOutputStream().flush();

    if (conn.getResponseCode() >= 400) {
        throw new IOException("Unable to complete the timestamping due to HTTP error: " + conn.getResponseCode()
                + " - " + conn.getResponseMessage());
    }

    try {
        TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(conn.getInputStream()).readObject());
        TimeStampResponse response = new TimeStampResponse(resp);
        response.validate(req);
        if (response.getStatus() != 0) {
            throw new IOException("Unable to complete the timestamping due to an invalid response ("
                    + response.getStatusString() + ")");
        }

        return response.getTimeStampToken().toCMSSignedData();

    } catch (Exception e) {
        throw new TimestampingException("Unable to complete the timestamping", e);
    }
}