Example usage for org.bouncycastle.tsp TimeStampResponse getEncoded

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

Introduction

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

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Document

return the ASN.1 encoded representation of this object.

Usage

From source file:eu.europa.ec.markt.dss.applet.service.TimestampRequestHandler.java

License:Open Source License

@Override
protected TimestampResponseMessage handleRequest(TimestampRequestMessage message) throws IOException {

    TimeStampResponse resp = tspSource.getTimeStampResponse(DigestAlgorithm.valueOf(message.getAlgorithm()),
            message.getDigest());/*w ww  .  j  a  v a 2  s .c  o m*/

    TimestampResponseMessage response = new TimestampResponseMessage();
    response.setTimestampResponse(resp.getEncoded());
    return response;
}

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

License:Open Source License

@Override
public byte[] getTimeStamp(String fileName, File tempFile, String timeStampingUrl) throws BusinessException {
    if (timeStampingUrl == null) {
        return null;
    }/* w ww.  j a  v  a2s.  c  o m*/

    byte[] timestampToken = null;
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(tempFile);
        TimeStampResponse resp = timeStampingService.getTimeStamp(timeStampingUrl, fis);
        timestampToken = resp.getEncoded();
    } catch (TSPException e) {
        logger.error(e.toString());
        throw new BusinessException(BusinessErrorCode.FILE_TIMESTAMP_NOT_COMPUTED,
                "TimeStamp on file is not computed", new String[] { fileName });
    } catch (FileNotFoundException e) {
        logger.error(e.toString());
        throw new BusinessException(BusinessErrorCode.FILE_TIMESTAMP_NOT_COMPUTED,
                "TimeStamp on file is not computed", new String[] { fileName });
    } catch (IOException e) {
        logger.error(e.toString());
        throw new BusinessException(BusinessErrorCode.FILE_TIMESTAMP_NOT_COMPUTED,
                "TimeStamp on file is not computed", new String[] { fileName });
    } catch (URISyntaxException e) {
        logger.error(e.toString());
        throw new BusinessException(BusinessErrorCode.FILE_TIMESTAMP_WRONG_TSA_URL,
                "The Tsa Url is empty or invalid", new String[] { fileName });
    } finally {
        try {
            if (fis != null)
                fis.close();
            fis = null;
        } catch (IOException e) {
            logger.error(e.toString());
        }
    }

    return timestampToken;
}

From source file:org.signserver.module.tsa.RequestedPolicyDispatcher.java

License:Open Source License

@Override
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext context)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {
    final GenericSignResponse result;

    // Log values
    final LogMap logMap = LogMap.getInstance(context);

    // Check context
    final RequestContext nextContext = context;
    if (context.get(this.getClass().getName()) != null) {
        throw new SignServerException("Dispatcher called more then one time for the same request. Aborting.");
    } else {/*from   w  w w.j av a 2  s  .  c  o m*/
        context.put(this.getClass().getName(), "called");
    }

    // Check that the request contains a valid TimeStampRequest object.
    if (!(signRequest instanceof GenericSignRequest)) {
        throw new IllegalRequestException("Recieved request wasn't a expected GenericSignRequest.");
    }
    final ISignRequest sReq = (ISignRequest) signRequest;

    // Get TimeStampRequest
    final TimeStampRequest timeStampRequest;
    if (sReq.getRequestData() instanceof TimeStampRequest) {
        timeStampRequest = (TimeStampRequest) sReq.getRequestData();
    } else if (sReq.getRequestData() instanceof byte[]) {
        try {
            timeStampRequest = new TimeStampRequest((byte[]) sReq.getRequestData());
        } catch (IOException ex) {
            throw new IllegalRequestException("Could not parse TimeStampRequest", ex);
        }
    } else {
        throw new IllegalRequestException("Expected a TimeStampRequest");
    }

    try {
        // Add to context
        if (timeStampRequest.getReqPolicy() != null) {
            nextContext.put(TSA_REQUESTEDPOLICYOID, timeStampRequest.getReqPolicy().getId());
        }

        // Find to which worker the request should be dispatched
        final String toWorker = lookupWorkerToDispatchTo(timeStampRequest, context);
        if (toWorker == null) {
            final TimeStampResponseGenerator gen = new TimeStampResponseGenerator(null, null);
            final String statusString = includeStatusString ? "request contains unknown policy." : null;
            final TimeStampResponse resp = gen.generateFailResponse(PKIStatus.REJECTION,
                    PKIFailureInfo.unacceptedPolicy, statusString);

            // Auditlog
            logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED, "false");
            logMap.put(IWorkerLogger.LOG_EXCEPTION, "requested policy not supported");

            result = new GenericServletResponse(sReq.getRequestID(), resp.getEncoded(), null, null, null,
                    RESPONSE_CONTENT_TYPE);
        } else {
            int toWorkerId = 0;
            try {
                toWorkerId = Integer.parseInt(toWorker);
            } catch (NumberFormatException ignored) {
            }
            if (toWorkerId < 1) {
                toWorkerId = getWorkerSession().getWorkerId(toWorker);
            }

            // Mark request comming from a dispatcher so the DispatchedAuthorizer can be used
            context.put(RequestContext.DISPATCHER_AUTHORIZED_CLIENT, true);

            HttpServletRequest httpRequest = null;
            if (sReq instanceof GenericServletRequest) {
                httpRequest = ((GenericServletRequest) sReq).getHttpServletRequest();
            }
            ProcessRequest newRequest = new GenericServletRequest(sReq.getRequestID(),
                    (byte[]) sReq.getRequestData(), httpRequest);

            result = (GenericSignResponse) getWorkerSession().process(toWorkerId, newRequest, context);
        }
    } catch (IOException e) {
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, e.getMessage());
        throw new SignServerException("Response message could not be constructed", e);
    } catch (TSPException e) {
        throw new SignServerException("Response message could not be constructed", e);
    }
    return result;
}

From source file:org.signserver.module.tsa.TimeStampSigner.java

License:Open Source License

/**
 * The main method performing the actual timestamp operation.
 * Expects the signRequest to be a GenericSignRequest contining a
 * TimeStampRequest// w ww.  ja  v a 2  s  . co m
 *
 * @param signRequest
 * @param requestContext
 * @return the sign response
 * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext)
 */
@Override
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {

    // Log values
    final LogMap logMap = LogMap.getInstance(requestContext);

    final ISignRequest sReq = (ISignRequest) signRequest;

    // Check that the request contains a valid TimeStampRequest object.
    if (!(signRequest instanceof GenericSignRequest)) {
        final IllegalRequestException exception = new IllegalRequestException(
                "Recieved request wasn't a expected GenericSignRequest. ");
        throw exception;
    }

    if (!((sReq.getRequestData() instanceof TimeStampRequest) || (sReq.getRequestData() instanceof byte[]))) {
        final IllegalRequestException exception = new IllegalRequestException(
                "Recieved request data wasn't a expected TimeStampRequest. ");
        throw exception;
    }

    if (!validChain) {
        LOG.error("Certificate chain not correctly configured");
        throw new CryptoTokenOfflineException("Certificate chain not correctly configured");
    }

    final ITimeSource timeSrc = getTimeSource();
    if (LOG.isDebugEnabled()) {
        LOG.debug("TimeSource: " + timeSrc.getClass().getName());
    }
    final Date date = timeSrc.getGenTime();
    final BigInteger serialNumber = getSerialNumber();

    // Log values
    logMap.put(ITimeStampLogger.LOG_TSA_TIME, date == null ? null : String.valueOf(date.getTime()));
    logMap.put(ITimeStampLogger.LOG_TSA_SERIALNUMBER, serialNumber.toString(16));
    logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName());

    GenericSignResponse signResponse = null;
    ICryptoInstance crypto = null;
    try {
        crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext);
        final byte[] requestbytes = (byte[]) sReq.getRequestData();

        if (requestbytes == null || requestbytes.length == 0) {
            LOG.error("Request must contain data");
            throw new IllegalRequestException("Request must contain data");
        }

        final TimeStampRequest timeStampRequest = new TimeStampRequest(requestbytes);

        // Log values for timestamp request
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_CERTREQ,
                String.valueOf(timeStampRequest.getCertReq()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_CRITEXTOIDS,
                String.valueOf(timeStampRequest.getCriticalExtensionOIDs()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_ENCODED,
                new String(Base64.encode(requestbytes, false)));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_NONCRITEXTOIDS,
                String.valueOf(timeStampRequest.getNonCriticalExtensionOIDs()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_NOUNCE,
                String.valueOf(timeStampRequest.getNonce()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_VERSION,
                String.valueOf(timeStampRequest.getVersion()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_MESSAGEIMPRINTALGOID,
                timeStampRequest.getMessageImprintAlgOID().getId());
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_MESSAGEIMPRINTDIGEST,
                new String(Base64.encode(timeStampRequest.getMessageImprintDigest(), false)));

        final TimeStampTokenGenerator timeStampTokenGen = getTimeStampTokenGenerator(crypto, timeStampRequest,
                logMap);

        final TimeStampResponseGenerator timeStampResponseGen = getTimeStampResponseGenerator(
                timeStampTokenGen);

        final TimeStampResponse timeStampResponse = timeStampResponseGen.generate(timeStampRequest,
                serialNumber, date, includeStatusString);

        final TimeStampToken token = timeStampResponse.getTimeStampToken();
        final byte[] signedbytes = timeStampResponse.getEncoded();

        // Log values for timestamp response
        if (LOG.isDebugEnabled()) {
            LOG.debug("Time stamp response status: " + timeStampResponse.getStatus() + ": "
                    + timeStampResponse.getStatusString());
        }
        logMap.put(ITimeStampLogger.LOG_TSA_PKISTATUS, String.valueOf(timeStampResponse.getStatus()));
        if (timeStampResponse.getFailInfo() != null) {
            logMap.put(ITimeStampLogger.LOG_TSA_PKIFAILUREINFO,
                    String.valueOf(timeStampResponse.getFailInfo().intValue()));
        }
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED,
                new String(Base64.encode(signedbytes, false)));
        logMap.put(ITimeStampLogger.LOG_TSA_PKISTATUS_STRING, timeStampResponse.getStatusString());

        final String archiveId;
        if (token == null) {
            archiveId = serialNumber.toString(16);
        } else {
            archiveId = token.getTimeStampInfo().getSerialNumber().toString(16);
        }

        final Collection<? extends Archivable> archivables = Arrays.asList(
                new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId),
                new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId));

        if (signRequest instanceof GenericServletRequest) {
            signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables,
                    RESPONSE_CONTENT_TYPE);
        } else {
            signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables);
        }

        // Put in log values
        if (date == null) {
            logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, "timeSourceNotAvailable");
        }

        // We were able to fulfill the request so the worker session bean
        // can go on and charge the client
        if (timeStampResponse.getStatus() == PKIStatus.GRANTED) {
            // The client can be charged for the request
            requestContext.setRequestFulfilledByWorker(true);
        } else {
            logMap.put(IWorkerLogger.LOG_PROCESS_SUCCESS, String.valueOf(false));
        }

    } catch (InvalidAlgorithmParameterException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "InvalidAlgorithmParameterException: " + e.getMessage(), e);
        LOG.error("InvalidAlgorithmParameterException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (NoSuchAlgorithmException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "NoSuchAlgorithmException: " + e.getMessage(), e);
        LOG.error("NoSuchAlgorithmException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (NoSuchProviderException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "NoSuchProviderException: " + e.getMessage(), e);
        LOG.error("NoSuchProviderException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CertStoreException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "CertStoreException: " + e.getMessage(), e);
        LOG.error("CertStoreException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (IOException e) {
        final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(),
                e);
        LOG.error("IOException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (TSPException e) {
        final IllegalRequestException exception = new IllegalRequestException(e.getMessage(), e);
        LOG.error("TSPException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (OperatorCreationException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("OperatorCreationException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } finally {
        releaseCryptoInstance(crypto, requestContext);
    }

    return signResponse;
}

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  w w.  j  av a 2  s .  c  om
    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();
}