Example usage for java.security GeneralSecurityException getMessage

List of usage examples for java.security GeneralSecurityException getMessage

Introduction

In this page you can find the example usage for java.security GeneralSecurityException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.openhab.binding.tesla.internal.handler.TeslaHandler.java

private ThingStatusDetail authenticate(String username, String password) {
    TokenRequest token = null;/*from  w ww. j  av a2  s. c om*/
    try {
        token = new TokenRequestPassword(username, password);
    } catch (GeneralSecurityException e) {
        logger.error("An exception occurred while building a password request token : '{}'", e.getMessage(), e);
    }

    if (token != null) {
        String payLoad = gson.toJson(token);

        Response response = tokenTarget.request().post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));

        if (response != null) {
            logger.debug("Authenticating : Response : {}:{}", response.getStatus(), response.getStatusInfo());

            if (response.getStatus() == 200 && response.hasEntity()) {
                String responsePayLoad = response.readEntity(String.class);
                TokenResponse tokenResponse = gson.fromJson(responsePayLoad.trim(), TokenResponse.class);

                if (StringUtils.isNotEmpty(tokenResponse.access_token)) {
                    Storage<Object> storage = storageService.getStorage(TeslaBindingConstants.BINDING_ID);
                    storage.put(getStorageKey(), gson.toJson(tokenResponse));
                    this.logonToken = tokenResponse;
                    return ThingStatusDetail.NONE;
                }
            } else if (response.getStatus() == 401) {
                return ThingStatusDetail.CONFIGURATION_ERROR;
            } else if (response.getStatus() == 503 || response.getStatus() == 502) {
                return ThingStatusDetail.COMMUNICATION_ERROR;
            }
        }
    }
    return ThingStatusDetail.CONFIGURATION_ERROR;
}

From source file:org.openhab.binding.tesla.internal.handler.TeslaHandler.java

private ThingStatusDetail authenticate() {
    Storage<Object> storage = storageService.getStorage(TeslaBindingConstants.BINDING_ID);

    String storedToken = (String) storage.get(getStorageKey());
    TokenResponse token = storedToken == null ? null : gson.fromJson(storedToken, TokenResponse.class);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    boolean hasExpired = true;

    if (token != null) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(token.created_at * 1000);
        logger.info("Found a request token created at {}", dateFormatter.format(calendar.getTime()));
        calendar.setTimeInMillis(token.created_at * 1000 + 60 * token.expires_in);

        Date now = new Date();

        if (calendar.getTime().before(now)) {
            logger.info("The token has expired at {}", dateFormatter.format(calendar.getTime()));
            hasExpired = true;/*ww  w . j av  a 2 s . c  om*/
        } else {
            hasExpired = false;
        }
    }

    String username = (String) getConfig().get(USERNAME);

    if (!StringUtils.isEmpty(username) && hasExpired) {
        String password = (String) getConfig().get(PASSWORD);
        return authenticate(username, password);
    }

    if (token == null || StringUtils.isEmpty(token.refresh_token)) {
        return ThingStatusDetail.CONFIGURATION_ERROR;
    }

    TokenRequestRefreshToken tokenRequest = null;
    try {
        tokenRequest = new TokenRequestRefreshToken(token.refresh_token);
    } catch (GeneralSecurityException e) {
        logger.error("An exception occurred while requesting a new token : '{}'", e.getMessage(), e);
    }

    String payLoad = gson.toJson(tokenRequest);

    Response response = tokenTarget.request().post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));

    if (response == null) {
        logger.debug("Authenticating : Response was null");
    } else {
        logger.debug("Authenticating : Response : {}:{}", response.getStatus(), response.getStatusInfo());

        if (response.getStatus() == 200 && response.hasEntity()) {
            String responsePayLoad = response.readEntity(String.class);
            TokenResponse tokenResponse = gson.fromJson(responsePayLoad.trim(), TokenResponse.class);

            if (tokenResponse != null && !StringUtils.isEmpty(tokenResponse.access_token)) {
                storage.put(getStorageKey(), gson.toJson(tokenResponse));
                this.logonToken = tokenResponse;
                if (logger.isTraceEnabled()) {
                    logger.trace("Access Token is {}", logonToken.access_token);
                }
                return ThingStatusDetail.NONE;
            }

            return ThingStatusDetail.NONE;
        } else if (response.getStatus() == 401) {
            if (!StringUtils.isEmpty(username)) {
                String password = (String) getConfig().get(PASSWORD);
                return authenticate(username, password);
            } else {
                return ThingStatusDetail.CONFIGURATION_ERROR;
            }
        } else if (response.getStatus() == 503 || response.getStatus() == 502) {
            return ThingStatusDetail.COMMUNICATION_ERROR;
        }
    }
    return ThingStatusDetail.CONFIGURATION_ERROR;
}

From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java

public void WriteCredentialsOnTagButtonClick(View view) {
    EditText userNameTextBox = (EditText) findViewById(R.id.fragmentAddUserNameTextBox);
    String userName = userNameTextBox.getText().toString();
    Log.i(nfcDebugTag, userName);//from   ww w . j av  a 2s  . c  om

    EditText passTextBox = (EditText) findViewById(R.id.fragmentAddWebPasswordTextBox);
    String pass = passTextBox.getText().toString();
    Log.i(nfcDebugTag, pass);

    EditText urlTextBox = (EditText) findViewById(R.id.fragmentAddWebUrlTextBox);
    String url = urlTextBox.getText().toString();
    Log.i(nfcDebugTag, url);

    if (!userName.equals("") && !pass.equals("") && !url.equals("")) {
        if (card != null) {
            try {
                //                    card.authenticate(DESFireEV1.AuthType.Native, 2, (byte) 0, 0,
                //                            (byte) 0, null);
                //                    Log.i(nfcDebugTag, "Applicatie authentificata");
                //                    card.selectApplication(0);
                //                    Log.i(nfcDebugTag, "Applicatia 0 selectata");
                //                    DesFireCreateApplication(card, 11);
                WebsitesCredentials credentials = new WebsitesCredentials();
                credentials.setUrl(url);
                credentials.setUserName(userName);
                credentials.setPassword(pass);
                WriteCredentials(credentials);
                Snackbar.make(view, "Tag Writen", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                Log.i(nfcDebugTag, "fisier scris");
                UpdatePageWithCredentials();

                //                    String textCard = "https://www.facebook.com" + "@@@" + userName + "@@@" + pass;
                //                    byte[] textBytes = textCard.getBytes();
                //
                //                    card.createFile(1, new DESFireFile.StdDataFileSettings(
                //                            DESFireEV1.CommunicationType.Plain, 0, 0, 0, 0, textBytes.length));
                //                    Log.i(nfcDebugTag, "fisier creat");
                //
                //                    // write data to file nr 1
                //                    card.authenticate(DESFireEV1.AuthType.Native, 2, (byte) 0, 0,
                //                            (byte) 0, null);
                //                    Log.i(nfcDebugTag, "Applicatie authentificata");
                //                    card.writeData(1, 0, textBytes);

            } catch (GeneralSecurityException e) {
                e.printStackTrace();
                Log.i(nfcDebugTag, "Create app security error" + e.getMessage());

            } catch (IOException e) {
                e.printStackTrace();
                Log.i(nfcDebugTag, "Create app io error" + e.getMessage());

            } catch (SmartCardException e) {
                e.printStackTrace();
                Log.i(nfcDebugTag, "Create app smart card error" + e.getMessage());

            }

        } else {
            Snackbar.make(view, "Tag not found", Snackbar.LENGTH_LONG).setAction("Action", null).show();
        }

    } else {
        Snackbar.make(view, "Campurile nu pot fi goale", Snackbar.LENGTH_LONG).setAction("Action", null).show();
    }

}

From source file:org.kuali.rice.kns.maintenance.KualiMaintainableImpl.java

/**
 * Special hidden parameters are set on the maintenance jsp starting with a
 * prefix that tells us which fields have been encrypted. This field finds
 * the those parameters in the map, whose value gives us the property name
 * that has an encrypted value. We then need to decrypt the value in the Map
 * before the business object is populated.
 *
 * @param fieldValues/*from w  w w  .ja v a 2 s.c o m*/
 *            - possibly with encrypted values
 * @return Map fieldValues - with no encrypted values
 */
protected Map<String, String> decryptEncryptedData(Map<String, String> fieldValues,
        MaintenanceDocument maintenanceDocument, String methodToCall) {
    try {
        MaintenanceDocumentRestrictions auths = KNSServiceLocator.getBusinessObjectAuthorizationService()
                .getMaintenanceDocumentRestrictions(maintenanceDocument,
                        GlobalVariables.getUserSession().getPerson());
        for (Iterator<String> iter = fieldValues.keySet().iterator(); iter.hasNext();) {
            String fieldName = iter.next();
            String fieldValue = (String) fieldValues.get(fieldName);

            if (fieldValue != null && !"".equals(fieldValue)
                    && fieldValue.endsWith(EncryptionService.ENCRYPTION_POST_PREFIX)) {
                if (shouldFieldBeEncrypted(maintenanceDocument, fieldName, auths, methodToCall)) {
                    String encryptedValue = fieldValue;

                    // take off the postfix
                    encryptedValue = StringUtils.stripEnd(encryptedValue,
                            EncryptionService.ENCRYPTION_POST_PREFIX);
                    if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
                        String decryptedValue = getEncryptionService().decrypt(encryptedValue);

                        fieldValues.put(fieldName, decryptedValue);
                    }
                } else
                    throw new RuntimeException(
                            "The field value for field name " + fieldName + " should not be encrypted.");
            } else if (fieldValue != null && !"".equals(fieldValue) && auths.hasRestriction(fieldName)
                    && shouldFieldBeEncrypted(maintenanceDocument, fieldName, auths, methodToCall))
                throw new RuntimeException(
                        "The field value for field name " + fieldName + " should be encrypted.");
        }
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Unable to decrypt secure data: " + e.getMessage());
    }

    return fieldValues;
}

From source file:jproxy.ProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {//from w  ww .j  ava 2s .  c  o m
            X509Certificate caCert = (X509Certificate) keyStore.getCertificate(KeyToolUtils.getRootCAalias());
            if (caCert == null) {
                return new String[] { "Could not find certificate" };
            }
            return new String[] { caCert.getSubjectX500Principal().toString(),
                    "Fingerprint(SHA1): "
                            + JOrphanUtils.baToHexString(DigestUtils.sha1(caCert.getEncoded()), ' '),
                    "Created: " + caCert.getNotBefore().toString() };
        } catch (GeneralSecurityException e) {
            log.error("Problem reading root CA from keystore", e);
            return new String[] { "Problem with root certificate", e.getMessage() };
        }
    }
    return null; // should not happen
}

From source file:org.glite.slcs.servlet.CertificateServlet.java

/**
 * Processes the certificate request.//w w w  .  j  a  va 2  s. co m
 * 
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void doProcess(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doProcess...");
    try {

        // get parameters
        String authorizationToken = getSLCSCertificateRequestParameter(request, "AuthorizationToken");
        String pemCertificateRequest = getSLCSCertificateRequestParameter(request, "CertificateSigningRequest");
        LOG.info("AuthorizationToken=" + authorizationToken);
        LOG.info("CertificateSigningRequest=\n" + pemCertificateRequest);

        // decode PEM certificate signing request
        CertificateRequest certificateRequest = null;
        try {
            StringReader reader = new StringReader(pemCertificateRequest);
            certificateRequest = CertificateRequest.readPEM(reader);
        } catch (GeneralSecurityException e) {
            LOG.error("Failed to rebuild the PEM CertificateSigningRequest", e);
            throw new SLCSException("Failed to decode PEM CertificateSigningRequest", e);
        }

        // check SLCS sessions
        Principal principal = certificateRequest.getPrincipal();
        String certificateSubject = principal.getName();
        LOG.debug("Subject=" + certificateSubject);

        AuditEvent newRequest = new CertificateEvent("New certificate request: " + certificateSubject);
        getAuditor().logEvent(newRequest);

        LOG.debug("check session...");
        SLCSSessions sessions = getSLCSSessions();
        SLCSSession session = sessions.getSession(authorizationToken, certificateSubject);
        if (session != null && session.isValid()) {
            LOG.debug(session + " is valid");

            // check certificate against policy
            LOG.debug("check certificate request against policy...");
            List userAttributes = session.getAttributes();
            CertificatePolicy policy = getCertificatePolicy();
            if (policy.isCertificateRequestValid(certificateRequest, userAttributes)) {

                // request certificate
                LOG.debug("get CA connection");
                CAClient onlineCA = getCAClient();
                CAConnection connection = onlineCA.getConnection();
                LOG.debug("create CA request");
                CARequest csrRequest = connection.createRequest(certificateRequest);
                LOG.info("send certificate request to CA server");
                connection.sendRequest(csrRequest);
                LOG.info("read CA server response");
                CAResponse csrResponse = connection.getResponse();
                LOG.debug("get certificate");
                Certificate cert = csrResponse.getCertificate(principal);

                // send response
                sendXMLCerfificateResponse(request, response, certificateSubject, cert);
            } else {
                throw new SLCSException("CertificateSigningRequest is not conform to CertificatePolicy");
            }
        } else {
            throw new SLCSException("SLCSSession: " + authorizationToken + "," + certificateSubject
                    + " does not exists or is expired");
        }

    } catch (SLCSException e) {
        LOG.error(e);

        //TODO: audit error

        sendXMLErrorResponse(request, response, "SLCSCertificateResponse", e.getMessage(), e);
    }

}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }//  w ww  . j  a v a2s . c o m
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}