Example usage for org.bouncycastle.tsp TimeStampResponse TimeStampResponse

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

Introduction

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

Prototype

TimeStampResponse(DLSequence dlSequence) 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 a2 s .co 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.io.RemoteTSPSource.java

License:Open Source License

@Override
public TimeStampResponse getTimeStampResponse(DigestAlgorithm algorithm, byte[] digest) throws IOException {

    try {//from w  w w.  ja va  2  s  .  co  m
        TimestampRequestMessage request = new TimestampRequestMessage();
        request.setAlgorithm(algorithm.toString());
        request.setDigest(digest);

        TimestampResponseMessage response = sendAndReceive(request);

        return new TimeStampResponse(response.getTimestampResponse());
    } catch (TSPException ex) {
        throw new IOException(ex);
    }
}

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

License:Open Source License

@Override
public TimeStampResponse getTimeStampResponse(DigestAlgorithm algorithm, byte[] digest) throws IOException {

    try {/*from  w w  w  . jav  a  2 s.c o m*/
        byte[] respBytes = null;

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

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

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

    } catch (TSPException ex) {
        throw new IOException("Invalid TSP response");
    }

}

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  w w w.j  av a2s.  co m

        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 {//w w  w.  ja v  a2s  .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);//from ww  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./*from w w  w . j  av  a2 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);/*  w  w w .jav  a 2 s .  c  om*/
    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.demoiselle.signer.timestamp.connector.TimeStampOperator.java

License:Open Source License

/**
 * Sends the time stamp request {@link createRequest} to a time stamp server
 *
 * @param request request to be sent//from w ww  .  j av a  2  s .c o  m
 * @return The time stamp returned by the server
 */
public byte[] invoke(byte[] request) throws CertificateCoreException {
    try {

        logger.info(timeStampMessagesBundle.getString("info.timestamp.init.request"));
        Connector connector = ConnectorFactory.buildConnector(ConnectionType.SOCKET);
        connector.setHostname(TimeStampConfig.getInstance().getTspHostname());
        connector.setPort(TimeStampConfig.getInstance().getTSPPort());

        logger.info(timeStampMessagesBundle.getString("info.timestamp.response"));
        inputStream = connector.connect(request);

        long tempo;
        // Valor do timeout da verificacao de dados disponiveis para leitura
        int timeOut = 3500;
        // Verificando se os 4 bytes iniciais estao disponiveis para leitura
        for (tempo = System.currentTimeMillis() + timeOut; inputStream.available() < 4
                && System.currentTimeMillis() < tempo;) {
            try {
                Thread.sleep(1L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // Lendo tamanho total
        byte[] tamanhoRetorno = new byte[4];
        inputStream.read(tamanhoRetorno, 0, 4);
        int tamanho = new BigInteger(tamanhoRetorno).intValue();

        // Verificando se os bytes na quantidade "tamanho" estao disponiveis
        if (System.currentTimeMillis() < tempo) {
            while (inputStream.available() < tamanho && System.currentTimeMillis() < tempo) {
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (System.currentTimeMillis() >= tempo) {
                logger.error(timeStampMessagesBundle.getString("info.timestamp.timeout"));
            }
        } else {
            logger.error(timeStampMessagesBundle.getString("info.timestamp.timeout"));
        }

        // Lendo flag
        byte[] retornoFlag = new byte[1];
        inputStream.read(retornoFlag, 0, 1);
        // tamanho total menos o tamanho da flag
        tamanho -= 1;

        // Lendo dados carimbo
        byte[] retornoCarimboDeTempo = new byte[tamanho];
        inputStream.read(retornoCarimboDeTempo, 0, tamanho);
        timeStampResponse = new TimeStampResponse(retornoCarimboDeTempo);

        logger.info(timeStampMessagesBundle.getString("info.timestamp.status", timeStampResponse.getStatus()));

        switch (timeStampResponse.getStatus()) {
        case 0: {
            logger.info(timeStampMessagesBundle.getString("info.pkistatus.granted"));
            break;
        }
        case 1: {
            logger.info(timeStampMessagesBundle.getString("info.pkistatus.grantedWithMods"));
            break;
        }
        case 2: {
            logger.info(timeStampMessagesBundle.getString("error.pkistatus.rejection"));
            throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.rejection"));
        }
        case 3: {
            logger.info(timeStampMessagesBundle.getString("error.pkistatus.waiting"));
            throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.waiting"));
        }
        case 4: {
            logger.info(timeStampMessagesBundle.getString("error.pkistatus.revocation.warn"));
            throw new CertificateCoreException(
                    timeStampMessagesBundle.getString("error.pkistatus.revocation.warn"));
        }
        case 5: {
            logger.info(timeStampMessagesBundle.getString("error.pkistatus.revocation.notification"));
            throw new CertificateCoreException(
                    timeStampMessagesBundle.getString("error.pkistatus.revocation.notification"));
        }
        default: {
            logger.info(timeStampMessagesBundle.getString("error.pkistatus.unknown"));
            throw new CertificateCoreException(timeStampMessagesBundle.getString("error.pkistatus.unknown"));
        }
        }

        // ok
        int failInfo = -1;

        if (timeStampResponse.getFailInfo() != null) {
            failInfo = Integer.parseInt(new String(timeStampResponse.getFailInfo().getBytes()));
        }

        logger.info(timeStampMessagesBundle.getString("info.timestamp.failinfo", failInfo));

        switch (failInfo) {
        case 0:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.badAlg"));
            break;
        case 2:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.badRequest"));
            break;
        case 5:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.badDataFormat"));
            break;
        case 14:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.timeNotAvailable"));
            break;
        case 15:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.unacceptedPolicy"));
            break;
        case 16:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.unacceptedExtension"));
            break;
        case 17:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.addInfoNotAvailable"));
            break;
        case 25:
            logger.info(timeStampMessagesBundle.getString("error.pkifailureinfo.systemFailure"));
            break;
        }

        timeStampResponse.validate(timeStampRequest);
        TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
        this.setTimestamp(new Timestamp(timeStampToken));

        if (timeStampToken == null) {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("error.timestamp.token.null"));
        }
        connector.close();

        //Imprime os dados do carimbo de tempo
        logger.info(timestamp.toString());

        //Retorna o carimbo de tempo gerado
        return timestamp.getEncoded();

    } catch (CertificateCoreException | TSPException | IOException e) {
        throw new CertificateCoreException(e.getMessage());
    }
}

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);/*  w  w  w  .j  ava2  s .co  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")));
}