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:org.signserver.test.random.impl.Sign.java

License:Open Source License

private void process(final WorkerSpec signer, final int reqid)
        throws FailedException, IllegalRequestException, CryptoTokenOfflineException, SignServerException {
    final ProcessResponse result;
    final RequestContext requestContext = new RequestContext();
    if (preProcessor != null) {
        preProcessor.preProcess(requestContext);
    }// ww w.  ja v a  2 s. co  m
    switch (signer.getWorkerType()) {
    case xml: {
        // Process
        final GenericSignRequest signRequest = new GenericSignRequest(reqid, TESTXML1.getBytes());
        final ProcessResponse response = workerSession.process(signer.getWorkerId(), signRequest,
                requestContext);

        // Check result
        GenericSignResponse res = (GenericSignResponse) response;
        final byte[] data = res.getProcessedData();
        // Check that we got a signed XML back
        String xml = new String(data);
        if (!xml.contains("xmldsig")) {
            throw new FailedException("Response was not signed: \"" + xml + "\"");
        }
        validateXMLSignature(xml);
        break;
    }
    case tsa: {
        try {
            // Process
            final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
            final int nonce = random.nextInt();
            final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1,
                    new byte[20], BigInteger.valueOf(nonce));
            byte[] requestBytes = timeStampRequest.getEncoded();

            GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);
            final GenericSignResponse res = (GenericSignResponse) workerSession.process(signer.getWorkerId(),
                    signRequest, requestContext);

            // Check result
            if (reqid != res.getRequestID()) {
                throw new FailedException("Expected request id: " + reqid + " but was " + res.getRequestID());
            }

            final Certificate signercert = res.getSignerCertificate();
            if (signercert == null) {
                throw new FailedException("No certificate returned");
            }

            final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
            timeStampResponse.validate(timeStampRequest);

            if (timeStampResponse.getStatus() != PKIStatus.GRANTED) {
                throw new FailedException("Token was not granted: " + timeStampResponse.getStatus());
            }

            if (timeStampResponse.getTimeStampToken() == null) {
                throw new FailedException("No token returned");
            }
            break;
        } catch (TSPException ex) {
            LOG.error("Verification error", ex);
            throw new FailedException("Response could not be verified: " + ex.getMessage());
        } catch (IOException ex) {
            LOG.error("Could not create request", ex);
            throw new FailedException("Could not create request: " + ex.getMessage());
        }
    }
    default:
        throw new IllegalRequestException("Unsupported workerType: " + signer.getWorkerType());
    }
}

From source file:org.votingsystem.timestampserver.jaxrs.TimeStampResourceEJB.java

License:Open Source License

private void processTimestampRequest(@Context HttpServletRequest req, @Context HttpServletResponse res,
        boolean isDiscrete) throws ServletException, IOException {
    PrintWriter writer = null;/*from   w  ww  .ja  v  a 2s  .  c o m*/
    String contentEncoding = req.getHeader("Content-Encoding");
    try {
        TimeStampResponseGeneratorHelper responseGenerator = null;
        InputStream requestInputStream = null;
        if ("base64".equals(contentEncoding)) {
            byte[] requestBytesBase64 = FileUtils.getBytesFromStream(req.getInputStream());
            byte[] requestBytes = Base64.getDecoder().decode(requestBytesBase64);
            requestInputStream = new ByteArrayInputStream(requestBytes);
        } else
            requestInputStream = req.getInputStream();
        if (isDiscrete)
            responseGenerator = getResponseGeneratorDiscrete(requestInputStream);
        else
            responseGenerator = getResponseGenerator(requestInputStream);

        TimeStampResponse timeStampResponse = responseGenerator.getTimeStampResponse();
        em.persist(new TimeStamp(responseGenerator.getSerialNumber().longValue(),
                timeStampResponse.getTimeStampToken().getEncoded(), TimeStamp.State.OK));
        res.setContentType(ContentType.TIMESTAMP_RESPONSE.getName());
        final ServletOutputStream out = res.getOutputStream();

        if ("base64".equals(contentEncoding)) {
            out.write(Base64.getEncoder().encode(timeStampResponse.getTimeStampToken().getEncoded()));
        } else
            out.write(timeStampResponse.getEncoded());
        out.flush();
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
        res.setContentType(MediaType.TEXT_PLAIN);
        res.setStatus(ResponseDto.SC_ERROR_REQUEST);
        if (writer == null)
            writer = res.getWriter();
        writer.println(ex.getMessage());
    }
    if (writer != null)
        writer.close();
}

From source file:test.integ.be.fedict.trust.TSATest.java

License:Open Source License

private void testTimestampServerTrust(String tsaLocation) throws Exception {
    // setup/*from   ww  w .  j  av  a 2  s.c  o m*/
    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();
    requestGen.setCertReq(true);
    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));
    byte[] requestData = request.getEncoded();

    DefaultHttpClient httpClient = new DefaultHttpClient();
    // HttpHost proxy = new HttpHost("proxy.yourict.net", 8080);
    // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
    // proxy);
    HttpPost postMethod = new HttpPost(tsaLocation);
    ContentType contentType = ContentType.create("application/timestamp-query");
    HttpEntity requestEntity = new ByteArrayEntity(requestData, contentType);
    postMethod.addHeader("User-Agent", "jTrust TSP Client");
    postMethod.setEntity(requestEntity);

    // operate
    long t0 = System.currentTimeMillis();
    HttpResponse httpResponse = httpClient.execute(postMethod);
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    long t1 = System.currentTimeMillis();
    LOG.debug("dt TSP: " + (t1 - t0) + " ms");
    if (statusCode != HttpURLConnection.HTTP_OK) {
        LOG.error("Error contacting TSP server " + TSA_LOCATION);
        throw new Exception("Error contacting TSP server " + TSA_LOCATION);
    }

    HttpEntity httpEntity = httpResponse.getEntity();
    TimeStampResponse tspResponse = new TimeStampResponse(httpEntity.getContent());
    postMethod.releaseConnection();

    TimeStampToken timeStampToken = tspResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    Store certificatesStore = timeStampToken.getCertificates();
    Collection<X509CertificateHolder> signerCollection = certificatesStore.getMatches(signerId);

    Iterator<X509CertificateHolder> signerCollectionIterator = signerCollection.iterator();
    X509CertificateHolder signerCertificateHolder = signerCollectionIterator.next();

    // TODO: check time-stamp token signature

    List<X509Certificate> certificateChain = getCertificateChain(signerCertificateHolder, certificatesStore);

    for (X509Certificate cert : certificateChain) {
        LOG.debug("certificate subject: " + cert.getSubjectX500Principal());
        LOG.debug("certificate issuer: " + cert.getIssuerX500Principal());
    }

    CertificateRepository certificateRepository = BelgianTrustValidatorFactory.createTSACertificateRepository();
    TrustValidator trustValidator = new TrustValidator(certificateRepository);
    // NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net",
    // 8080);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(null);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    trustValidator.isTrusted(certificateChain);
}

From source file:xades4j.providers.impl.DefaultTimeStampTokenProvider.java

License:Open Source License

@Override
public final TimeStampTokenRes getTimeStampToken(byte[] tsDigestInput, String digestAlgUri)
        throws TimeStampTokenGenerationException {
    try {/*from w  ww .ja v  a 2s  .c  o m*/
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        byte[] digest = md.digest(tsDigestInput);

        TimeStampRequest tsRequest = this.tsRequestGenerator.generate(identifierForDigest(digestAlgUri), digest,
                BigInteger.valueOf(System.currentTimeMillis()));
        InputStream responseStream = getResponse(tsRequest.getEncoded());
        TimeStampResponse tsResponse = new TimeStampResponse(responseStream);

        if (tsResponse.getStatus() != PKIStatus.GRANTED
                && tsResponse.getStatus() != PKIStatus.GRANTED_WITH_MODS) {
            throw new TimeStampTokenGenerationException(
                    "Time stamp token not granted. " + tsResponse.getStatusString());
        }
        tsResponse.validate(tsRequest);

        TimeStampToken tsToken = tsResponse.getTimeStampToken();
        return new TimeStampTokenRes(tsToken.getEncoded(), tsToken.getTimeStampInfo().getGenTime());
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenGenerationException("Digest algorithm not supported", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenGenerationException("Invalid time stamp response", ex);
    } catch (IOException ex) {
        throw new TimeStampTokenGenerationException("Encoding error", ex);
    }
}

From source file:xmlgenerator.SignDispatch.java

public boolean signTimeStamp() throws SAXException, ParserConfigurationException, IOException {
    byte[] digest = getSignature().getBytes();

    try {/*from  w w w  .  j  av  a 2  s . c om*/
        String str = getTimestamp(new String(Base64.encode(digest)));
        byte[] out = Base64.decode(str.getBytes());
        TimeStampResponse tsResponse = new TimeStampResponse(out);
        TimeStampToken tsToken = tsResponse.getTimeStampToken();
        signWithTimeStamp(new String(Base64.encode(tsToken.getEncoded())));
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}