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:com.itextpdf.text.pdf.TSAClientBouncyCastle.java

License:Open Source License

/**
 * Get timestamp token - Bouncy Castle request encoding / decoding layer
 *//*  w  w w. ja  va  2 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(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 {//from   ww  w  .ja  va 2  s.  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  a  v a 2  s. c om*/
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:controller.Controller.java

private void getap() throws IOException, ParserConfigurationException, SAXException, TSPException {
    String xmlFilePath = "sign.xml";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    Document document = docBuilder.parse(new File(xmlFilePath));

    Node signatureValueElement = document.getElementsByTagName("ds:SignatureValue").item(0);

    String out = signatureValueElement.getChildNodes().item(0).getNodeValue();

    byte[] signatureValue = out.getBytes();

    TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
    reqGen.setCertReq(true);/*from ww w .j  a va  2s .c  o  m*/
    TimeStampRequest tsReq = reqGen.generate(TSPAlgorithms.SHA1, signatureValue);

    byte[] tsData = tsReq.getEncoded();

    String base64data = Base64.toBase64String(tsData);

    TS ts = new TS();
    TSSoap soap = ts.getTSSoap();
    String timestamp = soap.getTimestamp(base64data);
    if (timestamp == null)
        throw new WebServiceException("Webov sluba nedostupn");

    byte[] responseB64 = timestamp.getBytes();

    TimeStampResponse tsRes = new TimeStampResponse(Base64.decode(responseB64));

    String decodedTimestamp = Base64.toBase64String(tsRes.getTimeStampToken().getEncoded());
    System.out.println(decodedTimestamp);

}

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 v  a  2 s . c  o  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  w ww . ja  va2s. com*/
 */
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 byte[] getTimestampDer(TimeStampResponse tsResponse) throws Exception {
    X509Certificate signerCertificate = TimestampVerifier.getSignerCertificate(tsResponse.getTimeStampToken(),
            GlobalConf.getTspCertificates());
    if (signerCertificate == null) {
        throw new CodedException(X_INTERNAL_ERROR, "Could not find signer certificate");
    }/*from ww  w.  j  a v a2s  .  c om*/

    TimeStampToken token = addSignerCertificate(tsResponse, signerCertificate);
    return token.getEncoded();
}

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);/*from  ww w  . ja  v a2s  .c  om*/

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

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

License:Open Source License

@Override
protected AbstractTimestampRequest createSingleTimestampRequest(Long logRecord) {
    return new SingleTimestampRequest(logRecord) {
        @Override//w  w  w  .j a  v  a 2s . com
        protected AbstractTimestampRequest.TsRequest makeTsRequest(TimeStampRequest req, List<String> tspUrls)
                throws Exception {
            synchronized (shouldFail) {
                if (shouldFail) {
                    shouldFail = false;
                    throw new RuntimeException("time-stamping failed");
                }
            }

            return DummyTSP.makeRequest(req);
        }

        @Override
        protected void verify(TimeStampRequest request, TimeStampResponse response) throws Exception {
            // do not validate against request

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

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

License:Open Source License

@Override
protected AbstractTimestampRequest createBatchTimestampRequest(Long[] logRecords, String[] signatureHashes) {
    return new BatchTimestampRequest(logRecords, signatureHashes) {
        @Override//from  w  ww  .  j  a v  a  2  s. c  o  m
        protected AbstractTimestampRequest.TsRequest makeTsRequest(TimeStampRequest req, List<String> tspUrls)
                throws Exception {
            synchronized (shouldFail) {
                if (shouldFail) {
                    shouldFail = false;
                    throw new RuntimeException("time-stamping failed");
                }
            }

            return DummyTSP.makeRequest(req);
        }

        @Override
        protected void verify(TimeStampRequest request, TimeStampResponse response) throws Exception {
            // do not validate against request

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