Example usage for java.security.cert CertificateException getLocalizedMessage

List of usage examples for java.security.cert CertificateException getLocalizedMessage

Introduction

In this page you can find the example usage for java.security.cert CertificateException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.ejbca.core.protocol.cmp.authentication.EndEntityCertificateAuthenticationModule.java

private Certificate getExtraCert(final PKIMessage msg) {
    final CMPCertificate[] extraCerts = msg.getExtraCerts();
    if ((extraCerts == null) || (extraCerts.length == 0)) {
        if (log.isDebugEnabled()) {
            log.debug("There is no certificate in the extraCert field in the PKIMessage");
        }//from ww w .jav a 2 s  . c o m
        return null;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("A certificate is found in the extraCert field in the CMP message");
        }
    }

    //Read the extraCert
    CMPCertificate cmpcert = extraCerts[0];
    Certificate excert = null;
    try {
        excert = CertTools.getCertfromByteArray(cmpcert.getEncoded());
        if (log.isDebugEnabled()) {
            log.debug("Obtaning the certificate from extraCert field was done successfully");
        }
    } catch (CertificateException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage(), e);
        }
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage(), e);
        }
    }
    return excert;
}

From source file:org.signserver.web.GenericProcessServlet.java

private void processRequest(final HttpServletRequest req, final HttpServletResponse res, final int workerId,
        final byte[] data, String fileName, final String pdfPassword, final ProcessType processType,
        final MetaDataHolder metadataHolder) throws java.io.IOException, ServletException {
    final String remoteAddr = req.getRemoteAddr();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Recieved HTTP process request for worker " + workerId + ", from ip " + remoteAddr);
    }//from  w w  w .j  a  va  2  s.c o  m

    // Client certificate
    Certificate clientCertificate = null;
    Certificate[] certificates = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
    if (certificates != null) {
        clientCertificate = certificates[0];
    }

    // Create request context and meta data
    final RequestContext context = new RequestContext(clientCertificate, remoteAddr);
    RequestMetadata metadata = RequestMetadata.getInstance(context);

    IClientCredential credential;

    if (clientCertificate instanceof X509Certificate) {
        final X509Certificate cert = (X509Certificate) clientCertificate;
        LOG.debug("Authentication: certificate");
        credential = new CertificateClientCredential(cert.getSerialNumber().toString(16),
                cert.getIssuerDN().getName());
    } else {
        // Check is client supplied basic-credentials
        final String authorization = req.getHeader(HTTP_AUTH_BASIC_AUTHORIZATION);
        if (authorization != null) {
            LOG.debug("Authentication: password");

            final String decoded[] = new String(Base64.decode(authorization.split("\\s")[1])).split(":", 2);

            credential = new UsernamePasswordClientCredential(decoded[0], decoded[1]);
        } else {
            LOG.debug("Authentication: none");
            credential = null;
        }
    }
    context.put(RequestContext.CLIENT_CREDENTIAL, credential);

    // Create log map
    LogMap logMap = LogMap.getInstance(context);

    final String xForwardedFor = req.getHeader(RequestContext.X_FORWARDED_FOR);

    // Add HTTP specific log entries
    logMap.put(IWorkerLogger.LOG_REQUEST_FULLURL,
            req.getRequestURL().append("?").append(req.getQueryString()).toString());
    logMap.put(IWorkerLogger.LOG_REQUEST_LENGTH, String.valueOf(data.length));
    logMap.put(IWorkerLogger.LOG_FILENAME, fileName);
    logMap.put(IWorkerLogger.LOG_XFORWARDEDFOR, xForwardedFor);
    logMap.put(IWorkerLogger.LOG_WORKER_NAME,
            getWorkerSession().getCurrentWorkerConfig(workerId).getProperty(PropertiesConstants.NAME));

    if (xForwardedFor != null) {
        context.put(RequestContext.X_FORWARDED_FOR, xForwardedFor);
    }

    // Store filename for use by archiver etc
    if (fileName != null) {
        fileName = stripPath(fileName);
    }
    context.put(RequestContext.FILENAME, fileName);
    context.put(RequestContext.RESPONSE_FILENAME, fileName);

    // PDF Password
    if (pdfPassword != null) {
        metadata.put(RequestContext.METADATA_PDFPASSWORD, pdfPassword);
    }

    addRequestMetaData(metadataHolder, metadata);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Received bytes of length: " + data.length);
    }

    final int requestId = random.nextInt();

    try {
        String responseText;

        switch (processType) {
        case signDocument:
            final GenericServletResponse servletResponse = (GenericServletResponse) getWorkerSession().process(
                    new AdminInfo("Client user", null, null), workerId,
                    new GenericServletRequest(requestId, data, req), context);

            if (servletResponse.getRequestID() != requestId) { // TODO: Is this possible to get at all?
                LOG.error("Response ID " + servletResponse.getRequestID() + " not matching request ID "
                        + requestId);
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Request and response ID missmatch");
                return;
            }

            byte[] processedBytes = (byte[]) servletResponse.getProcessedData();

            res.setContentType(servletResponse.getContentType());
            Object responseFileName = context.get(RequestContext.RESPONSE_FILENAME);
            if (responseFileName instanceof String) {
                res.setHeader("Content-Disposition", "attachment; filename=\"" + responseFileName + "\"");
            }
            res.setContentLength(processedBytes.length);
            res.getOutputStream().write(processedBytes);
            break;
        case validateDocument:
            final GenericValidationResponse validationResponse = (GenericValidationResponse) getWorkerSession()
                    .process(new AdminInfo("Client user", null, null), workerId,
                            new GenericValidationRequest(requestId, data), context);

            responseText = validationResponse.isValid() ? "VALID" : "INVALID";

            if (LOG.isDebugEnabled()) {
                final Validation validation = validationResponse.getCertificateValidation();

                if (validation != null) {
                    LOG.debug("Cert validation status: "
                            + validationResponse.getCertificateValidation().getStatusMessage());
                }
            }

            res.setContentType("text/plain");
            res.setContentLength(responseText.getBytes().length);
            res.getOutputStream().write(responseText.getBytes());
            break;
        case validateCertificate:
            final Certificate cert;
            try {
                cert = CertTools.getCertfromByteArray(data);

                final String certPurposes = req.getParameter(CERT_PURPOSES_PROPERTY_NAME);
                final ValidateResponse certValidationResponse = (ValidateResponse) getWorkerSession().process(
                        new AdminInfo("Client user", null, null), workerId,
                        new ValidateRequest(cert, certPurposes), context);
                final Validation validation = certValidationResponse.getValidation();

                final StringBuilder sb = new StringBuilder(validation.getStatus().name());

                sb.append(";");

                final String validPurposes = certValidationResponse.getValidCertificatePurposes();

                if (validPurposes != null) {
                    sb.append(certValidationResponse.getValidCertificatePurposes());
                }
                sb.append(";");
                sb.append(certValidationResponse.getValidation().getStatusMessage());
                sb.append(";");
                sb.append(certValidationResponse.getValidation().getRevokationReason());
                sb.append(";");

                final Date revocationDate = certValidationResponse.getValidation().getRevokedDate();

                if (revocationDate != null) {
                    sb.append(certValidationResponse.getValidation().getRevokedDate().getTime());
                }

                responseText = sb.toString();

                res.setContentType("text/plain");
                res.setContentLength(responseText.getBytes().length);
                res.getOutputStream().write(responseText.getBytes());
            } catch (CertificateException e) {
                LOG.error("Invalid certificate: " + e.getMessage());
                sendBadRequest(res, "Invalid certificate: " + e.getMessage());
                return;
            }
            break;
        }
        ;

        res.getOutputStream().close();

    } catch (AuthorizationRequiredException e) {
        LOG.debug("Sending back HTTP 401: " + e.getLocalizedMessage());

        final String httpAuthBasicRealm = "SignServer Worker " + workerId;

        res.setHeader(HTTP_AUTH_BASIC_WWW_AUTHENTICATE, "Basic realm=\"" + httpAuthBasicRealm + "\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
    } catch (AccessDeniedException e) {
        LOG.debug("Sending back HTTP 403: " + e.getLocalizedMessage());
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
    } catch (NoSuchWorkerException ex) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Worker Not Found");
    } catch (IllegalRequestException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (CryptoTokenOfflineException e) {
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
    } catch (ServiceUnavailableException e) {
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
    } catch (NotGrantedException e) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
    } catch (SignServerException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}