Example usage for javax.net.ssl SSLException printStackTrace

List of usage examples for javax.net.ssl SSLException printStackTrace

Introduction

In this page you can find the example usage for javax.net.ssl SSLException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * //from  ww w. j av  a 2s .  com
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:OfflineVerify.java

/**
 * Verifies that the certificate matches the specified hostname.
 * Uses the {@link DefaultHostnameVerifier} from the Apache HttpClient library
 * to confirm that the hostname matches the certificate.
 *
 * @param hostname/*from w  w  w  . j a  va  2 s.  com*/
 * @param leafCert
 * @return
 */
private static boolean verifyHostname(String hostname, X509Certificate leafCert) {
    try {
        // Check that the hostname matches the certificate. This method throws an exception if
        // the cert could not be verified.
        HOSTNAME_VERIFIER.verify(hostname, leafCert);
        return true;
    } catch (SSLException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:org.getcomposer.core.packagist.Downloader.java

public InputStream downloadResource() throws IOException {

    for (ProgressListener listener : listeners) {
        listener.setTotalWork(4);//from w  ww .  j a v a  2s .  c om
    }

    HttpClient client = new DefaultHttpClient();

    String url = getUrl();

    if (url.startsWith("https://packagist.org") || url.startsWith("https://getcomposer.org")) {
        registerSSLContext(client);
    }

    httpGet = new HttpGet(url);
    HttpResponse response = null;

    try {
        response = client.execute(httpGet);
    } catch (SSLException e) {
        e.printStackTrace();
        throw e;
    }

    for (ProgressListener listener : listeners) {
        listener.progressChanged(1);
    }

    try {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();

        for (ProgressListener listener : listeners) {
            listener.progressChanged(1);
        }

        for (ProgressListener listener : listeners) {
            listener.worked();
        }

        return content;

    } catch (Exception e) {
        //TODO: log
    } finally {
        for (ProgressListener listener : listeners) {
            listener.worked();
        }
    }

    throw new IOException("Error downloading resource");
}

From source file:com.googlecode.esms.provider.Tim.java

@Override
public Result login() {
    try {//w ww . java 2  s .  com

        if (loggedIn) {
            if (senderList.contains(username))
                return Result.SUCCESSFUL;
            else if (!doLogout())
                return Result.LOGOUT_ERROR;
        }

        if (doLogin()) {
            return Result.SUCCESSFUL;
        } else {
            return Result.LOGIN_ERROR;
        }

    } catch (SSLException s) {
        s.printStackTrace();
        return Result.PROVIDER_ERROR;
    } catch (Exception e) {
        e.printStackTrace();
        return Result.NETWORK_ERROR;
    }
}

From source file:co.elastic.tealess.SSLChecker.java

private void checkHandshake(SSLReport sslReport, SocketChannel socket) {
    final InetSocketAddress address = sslReport.getAddress();
    final String name = sslReport.getHostname();
    IOObserver ioObserver = new IOObserver();
    ObservingSSLEngine sslEngine = new ObservingSSLEngine(ctx.createSSLEngine(name, address.getPort()),
            ioObserver);//ww w .  jav a 2  s  . c  om
    sslReport.setIOObserver(ioObserver);
    sslEngine.setUseClientMode(true);

    try {
        sslEngine.beginHandshake();
    } catch (SSLException e) {
        sslReport.setFailed(e);
        Throwable cause = Blame.get(e);
        logger.warn("beginHandshake failed: [{}] {}", cause.getClass(), cause.getMessage());
    }

    // TODO: Is this enough bytes?
    int size = sslEngine.getSession().getApplicationBufferSize() * 2;
    ByteBuffer localText = ByteBuffer.allocate(size);
    ByteBuffer localWire = ByteBuffer.allocate(size);
    ByteBuffer peerText = ByteBuffer.allocate(size);
    ByteBuffer peerWire = ByteBuffer.allocate(size);

    // TODO: I wonder... do we need to send any data at all?
    localText.put("SSL TEST. HELLO.".getBytes());
    localText.flip();

    SSLEngineResult result;
    logger.info("Starting SSL handshake [{}] ", address);
    try {
        SSLEngineResult.HandshakeStatus state;
        state = sslEngine.getHandshakeStatus();
        while (state != FINISHED) {
            // XXX: Use a Selector to wait for data.
            //logger.trace("State: {} [{}]", state, address);
            switch (state) {
            case NEED_TASK:
                sslEngine.getDelegatedTask().run();
                state = sslEngine.getHandshakeStatus();
                break;
            case NEED_WRAP:
                localWire.clear();
                result = sslEngine.wrap(localText, localWire);
                state = result.getHandshakeStatus();
                localWire.flip();
                while (localWire.hasRemaining()) {
                    socket.write(localWire);
                    //logger.trace("Sent {} bytes [{}]", bytes, address);
                }
                localWire.compact();
                break;
            case NEED_UNWRAP:
                // Try reading until we get data.
                Selector selector = Selector.open();
                while (peerWire.position() == 0) {
                    socket.read(peerWire);
                    try {
                        Thread.currentThread().sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Read " + peerWire.position() + " bytes");
                peerWire.flip();
                result = sslEngine.unwrap(peerWire, peerText);
                state = result.getHandshakeStatus();
                peerWire.compact();
                break;
            }
        }
    } catch (IOException e) {
        sslReport.setFailed(e);
        sslReport.setSSLSession(sslEngine.getHandshakeSession());
        sslReport.setPeerCertificateDetails(peerCertificateDetails);
        logger.warn("beginHandshake failed", e);
        return;
    }

    logger.info("handshake completed [{}]", address);

    // Handshake OK!
    sslReport.setSSLSession(sslEngine.getSession());
}