Example usage for org.bouncycastle.tsp TimeStampResponse getStatusString

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

Introduction

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

Prototype

public String getStatusString() 

Source Link

Usage

From source file:be.apsu.extremon.probes.tsp.TSPProbe.java

License:Open Source License

public void probe_forever() {
    double start = 0, end = 0;
    BigInteger requestNonce;/*from  w  w  w.jav  a 2s .  com*/
    byte[] requestHashedMessage = new byte[20];
    List<String> comments = new ArrayList<String>();
    STATE result = STATE.OK;

    log("running");

    this.running = true;
    while (this.running) {
        comments.clear();
        this.random.nextBytes(requestHashedMessage);
        requestNonce = new BigInteger(512, this.random);
        TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage,
                requestNonce);

        end = 0;
        start = System.currentTimeMillis();

        try {
            TimeStampResponse response = probe(request);

            switch (response.getStatus()) {
            case PKIStatus.GRANTED:
                comments.add("granted");
                result = STATE.OK;
                break;
            case PKIStatus.GRANTED_WITH_MODS:
                comments.add("granted with modifications");
                result = STATE.WARNING;
                break;
            case PKIStatus.REJECTION:
                comments.add("rejected");
                result = STATE.ALERT;
                break;
            case PKIStatus.WAITING:
                comments.add("waiting");
                result = STATE.ALERT;
                break;
            case PKIStatus.REVOCATION_WARNING:
                comments.add("revocation warning");
                result = STATE.WARNING;
                break;
            case PKIStatus.REVOCATION_NOTIFICATION:
                comments.add("revocation notification");
                result = STATE.ALERT;
                break;
            default:
                comments.add("response outside RFC3161");
                result = STATE.ALERT;
                break;
            }

            if (response.getStatus() >= 2)
                comments.add(response.getFailInfo() != null ? response.getFailInfo().getString()
                        : "(missing failinfo)");

            if (response.getStatusString() != null)
                comments.add(response.getStatusString());

            end = System.currentTimeMillis();
            TimeStampToken timestampToken = response.getTimeStampToken();

            timestampToken.validate(this.signerVerifier);
            comments.add("validated");

            AttributeTable table = timestampToken.getSignedAttributes();
            TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo();
            BigInteger responseNonce = tokenInfo.getNonce();
            byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest();
            long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000;
            long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000;

            put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000);

            if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) {
                comments.add("clock skew > 1s");
                result = STATE.ALERT;
            }

            Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates();
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null);
            for (X509CertificateHolder certificate : certs) {
                AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm();
                if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) {
                    String cleanDn = certificate.getSubject().toString().replace("=", ":");
                    comments.add("signature cert \"" + cleanDn + "\" signed using "
                            + getName(sigalg.getAlgorithm().getId()));
                    result = STATE.ALERT;
                }
            }

            if (!responseNonce.equals(requestNonce)) {
                comments.add("nonce modified");
                result = STATE.ALERT;
            }

            if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) {
                comments.add("hashed message modified");
                result = STATE.ALERT;
            }

            if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                comments.add("signingcertificate missing");
                result = STATE.ALERT;
            }
        } catch (TSPException tspEx) {
            comments.add("validation failed");
            comments.add("tspexception-" + tspEx.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (IOException iox) {
            comments.add("unable to obtain response");
            comments.add("ioexception-" + iox.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (Exception ex) {
            comments.add("unhandled exception");
            result = STATE.ALERT;
        } finally {
            if (end == 0)
                end = System.currentTimeMillis();
        }

        put(RESULT_SUFFIX, result);
        put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|"));
        put("responsetime", (end - start));

        try {
            Thread.sleep(this.delay);
        } catch (InterruptedException ex) {
            log("interrupted");
        }
    }
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

License:Open Source License

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    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  ava  2  s  .c om
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

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

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();
    X509Certificate certificate = signerCert;
    do {
        LOG.debug("adding to certificate chain: " + certificate.getSubjectX500Principal());
        tspCertificateChain.add(certificate);
        if (certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
            break;
        }
        String aki = Hex.encodeHexString(getAuthorityKeyId(certificate));
        certificate = certificateMap.get(aki);
    } while (null != certificate);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

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

From source file:com.itextpdf.signatures.TSAClientBouncyCastle.java

License:Open Source License

/**
 * Get RFC 3161 timeStampToken./* w  ww.ja v a2  s  .c  om*/
 * Method may return null indicating that timestamp should be skipped.
 * @param imprint data imprint to be time-stamped
 * @return encoded, TSA signed data of the timeStampToken
 * @throws IOException
 * @throws TSPException
 */
public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException {
    byte[] respBytes = null;
    // Setup the time stamp request
    TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);
    // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
    BigInteger nonce = BigInteger.valueOf(SystemUtil.getSystemTimeMillis());
    TimeStampRequest request = tsqGenerator.generate(
            new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigest(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 PdfException(PdfException.InvalidTsa1ResponseCode2).setMessageParams(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 PdfException(PdfException.Tsa1FailedToReturnTimeStampToken2).setMessageParams(tsaURL,
                response.getStatusString());
    }
    TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo(); // to view details
    byte[] encoded = tsToken.getEncoded();

    LOGGER.info("Timestamp generated: " + tsTokenInfo.getGenTime());
    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:com.itextpdf.text.pdf.security.TSAClientBouncyCastle.java

License:Open Source License

/**
 * Get RFC 3161 timeStampToken./*from   w  ww. j  a  v a2s  .  c om*/
 * Method may return null indicating that timestamp should be skipped.
 * @param imprint data imprint to be time-stamped
 * @return encoded, TSA signed data of the timeStampToken
 * @throws IOException
 * @throws TSPException 
 */
public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException {
    byte[] respBytes = null;
    // Setup the time stamp request
    TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);
    // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
    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());
    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:com.itextpdf.text.pdf.TSAClientBouncyCastle.java

License:Open Source License

/**
 * Get timestamp token - Bouncy Castle request encoding / decoding layer
 *///from w  w  w  .j  av  a  2s .  c o m
protected byte[] getTimeStampToken(byte[] imprint) throws Exception {
    byte[] respBytes = null;
    try {
        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(X509ObjectIdentifiers.id_SHA1.getId(), 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 Exception(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 Exception(MessageLocalization.getComposedMessage(
                    "tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString()));
        }
        TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view details
        byte[] encoded = tsToken.getEncoded();
        long stop = System.currentTimeMillis();

        // Update our token size estimate for the next call (padded to be safe)
        this.tokSzEstimate = encoded.length + 32;
        return encoded;
    } catch (Exception e) {
        throw e;
    } catch (Throwable t) {
        throw new Exception(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL),
                t);
    }
}

From source file:com.opentrust.spi.pdf.PDFEnvelopedSignature.java

License:Mozilla Public License

public static TimestampToken addTSToCMS(CMSSignedDataWrapper cmsSignature, String algoId, ITspClient tspClient)
        throws NoSuchAlgorithmException, IOException, NoSuchFieldException, TSPException, CMSException {
    //byte[] tsResponse = getTSResponse2(cmsSignature.getSignatureValue(), user, password, serverTimestamp, algoId, policyId, useNonce);
    byte[] tsResponse;
    try {/*  w  w  w  .  j  a  v a  2s .c  o  m*/
        byte[] digest = DigestHelper.getDigest(cmsSignature.getSignatureValue(), algoId);
        byte[] fullresponse = tspClient.getRawTsp(digest, algoId);

        TimeStampResponse response = new TimeStampResponse(fullresponse);
        int status = response.getStatus();
        if (status == GRANTED) {
            TimeStampToken tspValue = response.getTimeStampToken();
            tsResponse = tspValue.getEncoded();
        } else
            throw new RuntimeException(
                    "Timestamping failure, status " + status + ", " + response.getStatusString());

    } catch (Exception e) {
        throw new RuntimeException("Error getting timestamp from " + tspClient.getSource(), e);
    }
    TimestampToken timestampToken = new BCTimeStampToken(tsResponse);
    cmsSignature.appendSignatureTimeStamp(timestampToken.getEncoded());
    return timestampToken;
}

From source file:com.spilowagie.text.pdf.TSAClientBouncyCastle.java

License:Mozilla Public License

/**
 * Get timestamp token - Bouncy Castle request encoding / decoding layer
 *///from w  w  w . j ava2 s .c o m
protected byte[] getTimeStampToken(byte[] imprint) throws Exception {
    byte[] respBytes = null;
    try {
        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(X509ObjectIdentifiers.id_SHA1.getId(), 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 Exception("Invalid TSA '" + tsaURL + "' response, code " + 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 Exception(
                    "TSA '" + tsaURL + "' failed to return time stamp token: " + response.getStatusString());
        }
        TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view details
        byte[] encoded = tsToken.getEncoded();
        long stop = System.currentTimeMillis();

        // Update our token size estimate for the next call (padded to be safe)
        this.tokSzEstimate = encoded.length + 32;
        return encoded;
    } catch (Exception e) {
        throw e;
    } catch (Throwable t) {
        throw new Exception("Failed to get TSA response from '" + tsaURL + "'", t);
    }
}

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  ww .  j  a va  2  s .co m*/
 */
public byte[] getTimeStampToken(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(getDigestAlgorithm())), 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()));
    }
    tsToken.getTimeStampInfo(); // to view details
    byte[] encoded = tsToken.getEncoded();

    // Update our token size estimate for the next call (padded to be safe)
    this.tokenSizeEstimate = encoded.length + 32;
    return encoded;
}

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  ww  w .j  ava2 s .c om*/
 */
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: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 {/* ww  w . java 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);
    }
}