Example usage for org.bouncycastle.tsp TimeStampResponse validate

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

Introduction

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

Prototype

public void validate(TimeStampRequest request) throws TSPException 

Source Link

Document

Check this response against to see if it a well formed response for the passed in request.

Usage

From source file:ec.rubrica.pdf.tsa.TSAClientBouncyCastleWithOid.java

License:Open Source License

/**
 * Se reimplementa este metodo para establecer un OID mediante el metodo
 * tsqGenerator.setReqPolicy()//from  w  w  w  .ja  va2 s.c  o m
 */
public byte[] getTimeStampToken54(byte[] imprint) throws IOException, TSPException {
    byte[] respBytes = null;
    // Setup the time stamp request
    TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);

    // Se agrega una PID Policy:
    if (policy != null && policy.length() > 0) {
        tsqGenerator.setReqPolicy(new ASN1ObjectIdentifier(policy));
    }

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    TimeStampRequest request = tsqGenerator.generate(
            new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigests(digestAlgorithm)), imprint, nonce);
    byte[] requestBytes = request.getEncoded();

    // Call the communications layer
    respBytes = getTSAResponse(requestBytes);

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

    // validate communication level attributes (RFC 3161 PKIStatus)
    response.validate(request);
    PKIFailureInfo failure = response.getFailInfo();
    int value = (failure == null) ? 0 : failure.intValue();
    if (value != 0) {
        // @todo: Translate value of 15 error codes defined by
        // PKIFailureInfo to string
        throw new IOException(MessageLocalization.getComposedMessage("invalid.tsa.1.response.code.2", tsaURL,
                String.valueOf(value)));
    }
    // @todo: validate the time stap certificate chain (if we want
    // assure we do not sign using an invalid timestamp).

    // extract just the time stamp token (removes communication status info)
    TimeStampToken tsToken = response.getTimeStampToken();
    if (tsToken == null) {
        throw new IOException(MessageLocalization.getComposedMessage(
                "tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString()));
    }
    TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo(); // to view
    // details
    byte[] encoded = tsToken.getEncoded();

    LOGGER.info("Timestamp generated: " + tsTokenInfo.getGenTime());

    // QUITAR COMENTARIO:
    // if (tsaInfo != null) {
    // tsaInfo.inspectTimeStampTokenInfo(tsTokenInfo);
    // }
    // Update our token size estimate for the next call (padded to be safe)
    this.tokenSizeEstimate = encoded.length + 32;
    return encoded;
}

From source file:ee.ria.xroad.proxy.messagelog.AbstractTimestampRequest.java

License:Open Source License

protected void verify(TimeStampRequest request, TimeStampResponse response) throws Exception {
    response.validate(request);

    TimeStampToken token = response.getTimeStampToken();
    TimestampVerifier.verify(token, GlobalConf.getTspCertificates());
}

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   ww w. j a v a  2  s .c o  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 genera el Sello de Tiempo//  w ww  . ja va  2s. c o  m
 * @param binarioaSellar fichero binario que se va a sellar
 * @return TimeStampToken en formato binario
 * @throws TSClienteError
 */
public byte[] generarSelloTiempo(byte[] binarioaSellar) throws TSClienteError {

    if (binarioaSellar == null) {
        log.error(MENSAJE_NO_DATOS_SELLO_TIEMPO);
        throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_1));
    } else {
        log.info(MENSAJE_GENERANDO_SELLO_TIEMPO);
        TimeStampRequestGenerator generadorPeticion = new TimeStampRequestGenerator();
        TimeStampRequest peticion = null;
        TimeStampResponse respuesta = null;

        try {
            MessageDigest resumen = MessageDigest.getInstance(algoritmoHash);
            resumen.update(binarioaSellar);
            peticion = generadorPeticion.generate(TSPAlgoritmos.getOID(algoritmoHash), resumen.digest());
            log.info(MENSAJE_PETICION_TSA_GENERADA);
        } catch (Exception e) {
            log.error(MENSAJE_ERROR_PETICION_TSA);
            throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_10));
        }

        cliente.getParams().setParameter(HttpClientParams.SO_TIMEOUT, INT5000);

        // Comprueba si hay configurado un proxy
        String servidorProxy = System.getProperty("http.proxyHost");
        if (servidorProxy != null && !servidorProxy.trim().equals(CADENA_VACIA)) {
            int puertoProxy = 80;
            try {
                puertoProxy = Integer.parseInt(System.getProperty("http.proxyPort"));
            } catch (NumberFormatException ex) {
            }
            cliente.getHostConfiguration().setProxy(servidorProxy, puertoProxy);

            Credentials defaultcreds = new AuthenticatorProxyCredentials(servidorProxy, CADENA_VACIA);
            cliente.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
        }

        PostMethod metodo = new PostMethod(servidorTSA);
        metodo.addRequestHeader(CONTENT_TYPE, APPLICATION_TIMESTAMP_QUERY);
        ByteArrayInputStream datos = null;
        try {
            datos = new ByteArrayInputStream(peticion.getEncoded());
        } catch (IOException e) {
            log.error(MENSAJE_ERROR_PETICION + e.getMessage());
            throw new TSClienteError(
                    I18n.getResource(LIBRERIA_TSA_ERROR_11) + DOS_PUNTOS_ESPACIO + e.getMessage());
        }

        InputStreamRequestEntity rq = new InputStreamRequestEntity(datos);
        metodo.setRequestEntity(rq);

        metodo.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        byte[] cuerpoRespuesta = null;
        try {
            int estadoCodigo = cliente.executeMethod(metodo);
            log.info(MENSAJE_PETICION_TSA_ENVIADA);

            if (estadoCodigo != HttpStatus.SC_OK) {

                log.error(MENSAJE_FALLO_EJECUCION_METODO + metodo.getStatusLine());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_12) + DOS_PUNTOS_ESPACIO + metodo.getStatusLine());
            }

            cuerpoRespuesta = metodo.getResponseBody();
            log.info(MENSAJE_RESPUESTA_TSA_OBTENIDA);

            try {
                respuesta = new TimeStampResponse(cuerpoRespuesta);
                try {

                    respuesta.validate(peticion);

                    log.info(MENSAJE_RESPUESTA_TSA_VALIDADA_OK);
                    // Para solucionar bug en libreria bouncycastle
                    //return respuesta.getTimeStampToken().getEncoded();
                    //AppPerfect: Falso positivo
                    ASN1InputStream is = new ASN1InputStream(cuerpoRespuesta);
                    ASN1Sequence seq = ASN1Sequence.getInstance(is.readObject());
                    DEREncodable enc = seq.getObjectAt(1);
                    if (enc == null)
                        return null;
                    return enc.getDERObject().getEncoded();
                    //Fin Para solucionar bug en libreria bouncycastle
                } catch (TSPException e) {
                    log.error(MENSAJE_RESPUESTA_NO_VALIDA + e.getMessage());
                    throw new TSClienteError(
                            I18n.getResource(LIBRERIA_TSA_ERROR_9) + DOS_PUNTOS_ESPACIO + e.getMessage());
                }
            } catch (TSPException e) {
                log.error(MENSAJE_RESPUESTA_MAL_FORMADA + e.getMessage());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_8) + DOS_PUNTOS_ESPACIO + e.getMessage());
            } catch (IOException e) {

                log.error(MENSAJE_SECUENCIA_BYTES_MAL_CODIFICADA + e.getMessage());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_7) + DOS_PUNTOS_ESPACIO + e.getMessage());
            }
        } catch (HttpException e) {
            log.error(MENSAJE_VIOLACION_PROTOCOLO_HTTP + e.getMessage());
            throw new TSClienteError(
                    I18n.getResource(LIBRERIA_TSA_ERROR_6) + DOS_PUNTOS_ESPACIO + e.getMessage());
        } catch (IOException e) {
            String mensajeError = I18n.getResource(LIBRERIA_TSA_ERROR_4) + DOS_PUNTOS_ESPACIO + servidorTSA;
            log.error(MENSAJE_ERROR_CONEXION_SERVIDOR_OCSP + e.getMessage());

            throw new TSClienteError(mensajeError);
        } finally {
            // Termina la conexin
            metodo.releaseConnection();
        }
    }
}

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 {/*w  w  w .  j a v a2  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: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);/* w w  w .  j av a2  s . 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);
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.TimeStampingClient.java

License:Open Source License

/**
 * Get RFC 3161 timeStampToken./*  w  w  w.ja va 2  s.  co m*/
 *
 * @param tsaUrl Location of TSA
 * @param data The data to be time-stamped
 * @param hashAlg The algorithm used for generating a hash value of the data to be time-stamped
 * @return encoded, TSA signed data of the timeStampToken
 * @throws IOException
 */
public static byte[] getTimeStampToken(String tsaUrl, byte[] data, DigestType hashAlg) throws IOException {

    TimeStampResponse response = null;
    try {

        // calculate hash value
        MessageDigest digest = MessageDigest.getInstance(hashAlg.jce());
        byte[] hashValue = digest.digest(data);

        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(new ASN1ObjectIdentifier(hashAlg.oid()), hashValue,
                nonce);
        byte[] requestBytes = request.getEncoded();

        // send http request
        byte[] respBytes = queryServer(tsaUrl, requestBytes);

        // process response
        response = new TimeStampResponse(respBytes);

        // validate communication level attributes (RFC 3161 PKIStatus)
        response.validate(request);
        PKIFailureInfo failure = response.getFailInfo();
        int value = failure == null ? 0 : failure.intValue();
        if (value != 0) {
            throw new IOException("Server returned error code: " + String.valueOf(value));
        }
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    }

    // extract the time stamp token
    TimeStampToken tsToken = response.getTimeStampToken();
    if (tsToken == null) {
        throw new IOException("TSA returned no time stamp token: " + response.getStatusString());
    }

    return tsToken.getEncoded();
}

From source file:org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService.java

License:Apache License

@SuppressWarnings("unchecked")
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo());
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*from   w w  w  .  j av  a2 s .  c o  m*/
    String requestPolicy = signatureConfig.getTspRequestPolicy();
    if (requestPolicy != null) {
        requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy));
    }
    ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo());
    TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP POST request
    Proxy proxy = Proxy.NO_PROXY;
    if (signatureConfig.getProxyUrl() != null) {
        URL proxyUrl = new URL(signatureConfig.getProxyUrl());
        String host = proxyUrl.getHost();
        int port = proxyUrl.getPort();
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, (port == -1 ? 80 : port)));
    }

    HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy);

    if (signatureConfig.getTspUser() != null) {
        String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass();
        String encoding = DatatypeConverter
                .printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1")));
        huc.setRequestProperty("Authorization", "Basic " + encoding);
    }

    huc.setRequestMethod("POST");
    huc.setConnectTimeout(20000);
    huc.setReadTimeout(20000);
    huc.setDoOutput(true); // also sets method to POST.
    huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent());
    huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request"
            : "application/timestamp-query"); // "; charset=ISO-8859-1");

    OutputStream hucOut = huc.getOutputStream();
    hucOut.write(encodedRequest);

    // invoke TSP service
    huc.connect();

    int statusCode = huc.getResponseCode();
    if (statusCode != 200) {
        LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl());
        throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl());
    }

    // HTTP input validation
    String contentType = huc.getHeaderField("Content-Type");
    if (null == contentType) {
        throw new RuntimeException("missing Content-Type header");
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(huc.getInputStream(), bos);
    LOG.log(POILogger.DEBUG, "response content: ", bos.toString());

    if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response"
            : "application/timestamp-reply")) {
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }

    if (bos.size() == 0) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray());
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus());
        LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue());
            if (/*PKIFailureInfo.unacceptedPolicy*/(1 << 8) == failInfo.intValue()) {
                LOG.log(POILogger.DEBUG, "unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Name signerCertIssuer = signerId.getIssuer();
    LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber);
    LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null);

    X509CertificateHolder signerCert = null;
    Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>();
    for (X509CertificateHolder certificate : certificates) {
        if (signerCertIssuer.equals(certificate.getIssuer())
                && signerCertSerialNumber.equals(certificate.getSerialNumber())) {
            signerCert = certificate;
        }
        certificateMap.put(certificate.getSubject(), certificate);
    }

    // TSP signer cert path building
    if (signerCert == null) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>();
    JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter();
    x509converter.setProvider("BC");
    X509CertificateHolder certificate = signerCert;
    do {
        LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject());
        tspCertificateChain.add(x509converter.getCertificate(certificate));
        if (certificate.getSubject().equals(certificate.getIssuer())) {
            break;
        }
        certificate = certificateMap.get(certificate.getIssuer());
    } while (null != certificate);

    // verify TSP signer signature
    X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded());
    DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator();
    DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder();
    BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider();
    BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder,
            hashAlgoFinder, calculator);
    SignerInformationVerifier verifier = verifierBuilder.build(holder);

    timeStampToken.validate(verifier);

    // verify TSP signer certificate
    if (signatureConfig.getTspValidator() != null) {
        signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData);
    }

    LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:org.digidoc4j.SkDataLoaderTest.java

License:GNU General Public License

@Test
public void getTimestampViaSpy() throws Exception {
    stubFor(post(urlEqualTo("/")).willReturn(aResponse().proxiedFrom(configuration.getTspSource())));

    byte[] tsRequest = new byte[] { 48, 57, 2, 1, 1, 48, 49, 48, 13, 6, 9, 96, -122, 72, 1, 101, 3, 4, 2, 1, 5,
            0, 4, 32, 2, 91, 64, 111, 35, -23, -19, -46, 57, -80, -63, -80, -74, 100, 72, 97, -47, -17, -35,
            -62, 102, 52, 116, 73, -10, -120, 115, 62, 2, 87, -29, -21, 1, 1, -1 };
    SkDataLoader dataLoader = SkDataLoader.createTimestampDataLoader(configuration);
    dataLoader.setUserAgentSignatureProfile(SignatureProfile.LT);
    byte[] response = dataLoader.post(MOCK_PROXY_URL, tsRequest);
    assertNotNull(response);/*from w  ww .j  a  v a  2  s  .c o  m*/
    TimeStampResponse timeStampResponse = new TimeStampResponse(response);
    assertEquals(0, timeStampResponse.getStatus());
    timeStampResponse.validate(new TimeStampRequest(tsRequest));

    verify(postRequestedFor(urlMatching("/"))
            .withHeader("Content-Type", containing("application/timestamp-query"))
            .withHeader("User-Agent", containing("LIB DigiDoc4j")));
}

From source file:org.linagora.linshare.core.service.impl.TimeStampingServiceImpl.java

License:Open Source License

private TimeStampResponse getTimeStamp(URI uriTSA, byte[] sha1Digest) throws TSPException {
    TimeStampResponse response = null;

    ByteArrayInputStream bis = null;
    OutputStream out = null;/*  w  w w .  j a  va2 s. c  o  m*/

    try {

        TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

        SecureRandom randomGenerator = SecureRandom.getInstance("SHA1PRNG");
        long nonce = randomGenerator.nextLong();

        // request with digestAlgorithmOID, byte[] digest, java.math.BigInteger nonce
        TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, sha1Digest, BigInteger.valueOf(nonce));

        byte[] reqData = request.getEncoded();

        HttpURLConnection conn = (HttpURLConnection) uriTSA.toURL().openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Content-Type", "application/timestamp-query");
        conn.setRequestProperty("Content-Length", Long.toString(reqData.length));
        conn.setRequestMethod("POST");

        out = conn.getOutputStream();
        bis = new ByteArrayInputStream(reqData);

        byte[] tab = new byte[1024];

        int lu = bis.read(tab);

        while (lu >= 0) {
            out.write(tab, 0, lu);
            lu = bis.read(tab);
        }

        out.flush();

        int returnCode = conn.getResponseCode();

        if (returnCode == HttpURLConnection.HTTP_OK) {

            InputStream in = conn.getInputStream();
            response = new TimeStampResponse(in);

            response.validate(request); // if it fails a TSPException is raised
        } else {
            //404 or 500 ...
            throw new TSPException("service TSA is not available");
        }
    } catch (ProtocolException e) {
        throw new TSPException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TSPException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new TSPException(e.getMessage(), e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(e.toString());
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                logger.error(e.toString());
            }
        }
    }

    return response;
}