Example usage for javax.net.ssl SSLSocket getSupportedCipherSuites

List of usage examples for javax.net.ssl SSLSocket getSupportedCipherSuites

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket getSupportedCipherSuites.

Prototype

public abstract String[] getSupportedCipherSuites();

Source Link

Document

Returns the names of the cipher suites which could be enabled for use on this connection.

Usage

From source file:MyHandshakeListener.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = (SSLSocket) factory.createSocket("127.0.0.1", 8080);
    String[] suites = socket.getSupportedCipherSuites();
    socket.setEnabledCipherSuites(suites);
    socket.addHandshakeCompletedListener(new MyHandshakeListener());
    socket.startHandshake();//from   www  .j  av  a  2s .  co m
    System.out.println("Just connected to " + socket.getRemoteSocketAddress());
}

From source file:MainClass.java

public static void main(String[] args) {
    String host = args[0];/*from   w  w w.  j  a  va2s.co  m*/
    int port = Integer.parseInt(args[1]);

    try {
        System.out.println("Locating socket factory for SSL...");
        SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

        System.out.println("Creating secure socket to " + host + ":" + port);
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

        System.out.println("Enabling all available cipher suites...");
        String[] suites = socket.getSupportedCipherSuites();
        socket.setEnabledCipherSuites(suites);

        System.out.println("Registering a handshake listener...");
        socket.addHandshakeCompletedListener(new MyHandshakeListener());

        System.out.println("Starting handshaking...");
        socket.startHandshake();

        System.out.println("Just connected to " + socket.getRemoteSocketAddress());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.tc.simple.apn.quicktests.Test.java

/**
 * @param args/*from  w  w w . ja  va  2  s .  co  m*/
 */

public static void main(String[] args) {
    SSLSocket socket = null;

    try {
        String host = "gateway.sandbox.push.apple.com";
        int port = 2195;

        String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f";
        System.out.println(token.toCharArray().length);

        //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223";

        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray());
        KeyManagerFactory keyMgrFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
        SSLSocketFactory socketFactory = sslContext.getSocketFactory();

        socket = (SSLSocket) socketFactory.createSocket(host, port);
        String[] cipherSuites = socket.getSupportedCipherSuites();
        socket.setEnabledCipherSuites(cipherSuites);
        socket.startHandshake();

        char[] t = token.toCharArray();
        byte[] b = Hex.decodeHex(t);

        OutputStream outputstream = socket.getOutputStream();

        String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}";

        int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        DataOutputStream dos = new DataOutputStream(bout);

        //command
        dos.writeByte(1);

        //id
        dos.writeInt(900);

        //expiry
        dos.writeInt(expiry);

        //token length.
        dos.writeShort(b.length);

        //token
        dos.write(b);

        //payload length
        dos.writeShort(payload.length());

        //payload.
        dos.write(payload.getBytes());

        byte[] byteMe = bout.toByteArray();

        socket.getOutputStream().write(byteMe);

        socket.setSoTimeout(900);
        InputStream in = socket.getInputStream();

        System.out.println(APNErrors.getError(in.read()));

        in.close();

        outputstream.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:edu.cmu.cylab.starslinger.exchange.CheckedSSLSocketFactory.java

public static SSLSocket limitEnabledCipherSuites(SSLSocket sslEngine) {
    String[] supportedCipherSuites = sslEngine.getSupportedCipherSuites();
    List<String> favoredCipherSuites = new ArrayList<String>();

    /*/*from  ww w .  jav  a  2 s .  c om*/
     * We don't want anonymous Diffie Hellman and no DES or 40 or 56 bit
     * keys and no null-md5 or null-sha.
     */
    String[] unwantedCipherSuites = new String[] { "_dh_anon", "_des", "_40", "_56", "_null_md5", "_null_sha" };
    for (String cs : supportedCipherSuites) {
        boolean isCSok = true;
        for (String ucs : unwantedCipherSuites)
            if (cs.toLowerCase(Locale.US).contains(ucs))
                isCSok = false;

        if (isCSok)
            favoredCipherSuites.add(cs);
    }

    sslEngine.setEnabledCipherSuites(favoredCipherSuites.toArray(new String[favoredCipherSuites.size()]));
    return sslEngine;
}

From source file:net.i2p.util.I2PSSLSocketFactory.java

/**
 * Select protocols and cipher suites to be used
 * based on configured inclusion and exclusion lists
 * as well as enabled and supported protocols and cipher suites.
 *
 * Adapted from Jetty SslContextFactory.java
 *
 * @since 0.9.16/*from  ww  w. j a  v a2s  .c  om*/
 */
public static void setProtocolsAndCiphers(SSLSocket socket) {
    socket.setEnabledProtocols(selectProtocols(socket.getEnabledProtocols(), socket.getSupportedProtocols()));
    socket.setEnabledCipherSuites(
            selectCipherSuites(socket.getEnabledCipherSuites(), socket.getSupportedCipherSuites()));
}

From source file:com.apporiented.hermesftp.cmd.impl.FtpCmdAuth.java

/**
 * Enables the configured cipher suites in the passed socket.
 * //from   w  w w .  j a v a  2s . com
 * @param sslSocket The socket.
 */
private void enableCipherSuites(SSLSocket sslSocket) {
    String[] cipherSuites = getCtx().getOptions().getStringArray(OPT_SSL_CIPHER_SUITES, null);
    if (cipherSuites != null) {
        if (cipherSuites.length == 1 && WILDCARD.equals(cipherSuites[0])) {
            sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
        } else {
            sslSocket.setEnabledCipherSuites(cipherSuites);
        }
    }
}

From source file:it.jnrpe.client.JNRPEClient.java

/**
 * Inovoke a command installed in JNRPE.
 * /*from w  w  w .  j  a v  a2  s . c  om*/
 * @param sCommandName
 *            The name of the command to be invoked
 * @param arguments
 *            The arguments to pass to the command (will substitute the
 *            $ARGSx$ parameters)
 * @return The value returned by the server
 * @throws JNRPEClientException
 *             Thrown on any communication error.
 */
public final ReturnValue sendCommand(final String sCommandName, final String... arguments)
        throws JNRPEClientException {
    SocketFactory socketFactory;

    Socket s = null;
    try {
        if (!useSSL) {
            socketFactory = SocketFactory.getDefault();
        } else {
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

            sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom());

            socketFactory = sslContext.getSocketFactory();
        }

        s = socketFactory.createSocket();
        if (weakCipherSuitesEnabled) {
            SSLSocket ssl = (SSLSocket) s;
            ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        }

        s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout));
        s.connect(new InetSocketAddress(serverIPorURL, serverPort));
        JNRPERequest req = new JNRPERequest(sCommandName, arguments);

        s.getOutputStream().write(req.toByteArray());

        InputStream in = s.getInputStream();
        JNRPEResponse res = new JNRPEResponse(in);

        return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage());
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new JNRPEClientException(e);
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:immf.MyWiser.java

/**
 * Create a new SMTP server with this class as the listener.
 * The default port is 25. Call setPort()/setHostname() before
 * calling start().//from  w w  w .j  a va2s .  com
 */
public MyWiser(UsernamePasswordValidator userPass, int port, MyWiserMailListener listener,
        final String tlsKeyStore, final String tlsKeyType, final String tlsKeyPasswd) {
    if (tlsKeyStore == null) {
        log.info("SMTP Server disable TLS");
        this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass));
        this.server.setHideTLS(true); // TLS?

    } else {
        // TLS
        log.info("SMTP Server enable TLS");
        this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass)) {
            public SSLSocket createSSLSocket(Socket socket) throws IOException {
                SSLSocketFactory sf = createSslSocketFactory(tlsKeyStore, tlsKeyType, tlsKeyPasswd);
                InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
                SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(),
                        socket.getPort(), true));

                s.setUseClientMode(false);

                s.setEnabledCipherSuites(s.getSupportedCipherSuites());

                return s;
            }
        };
        this.server.setRequireTLS(true); // TLS
    }
    this.server.setPort(port);
    this.listener = listener;
}

From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUIEasySSLProtocolSocketFactory.java

private synchronized Socket enableSocket(SSLSocket socket) {
    socket.getSession().invalidate();// w  ww  .j  a  va2s.c  om

    String protocols = System.getProperty("soapui.https.protocols");
    String ciphers = System.getProperty("soapui.https.ciphers");

    if (StringUtils.hasContent(protocols)) {
        socket.setEnabledProtocols(protocols.split(","));
    } else if (socket.getSupportedProtocols() != null) {
        socket.setEnabledProtocols(socket.getSupportedProtocols());
    }

    if (StringUtils.hasContent(ciphers)) {
        socket.setEnabledCipherSuites(ciphers.split(","));
    } else if (socket.getSupportedCipherSuites() != null) {
        socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());
    }
    return socket;
}

From source file:i2p.bote.imap.ImapService.java

public ImapService(Configuration configuration, final PasswordVerifier passwordVerifier,
        EmailFolderManager folderManager) throws ConfigurationException {
    this.folderManager = folderManager;

    setLog(LoggerFactory.getLogger(ImapService.class));

    // Set up the keystore for the SSL certificate
    sslKeyStore = configuration.getSSLKeyStoreFile();
    setFileSystem(new FileSystem() {
        @Override/*  w w w.  j a va  2  s  . com*/
        public InputStream getResource(String resource) throws IOException {
            return null;
        }

        @Override
        public File getFile(String fileURL) throws FileNotFoundException {
            if (fileURL.equals(SSL_KEYSTORE_FILE))
                return sslKeyStore;
            return null;
        }

        @Override
        public File getBasedir() throws FileNotFoundException {
            return null;
        }
    });

    HierarchicalConfiguration cfg = new HierarchicalConfiguration();
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket s = null;
    try {
        // Create an unconnected socket for getting supported cipher suites
        s = (SSLSocket) sf.createSocket();
        // enable STARTTLS using the above keystore
        cfg.setProperty("tls.[@startTLS]", true);
        cfg.setProperty("tls.keystore", SSL_KEYSTORE_FILE);
        cfg.setProperty("tls.secret", configuration.getSSLKeyStorePassword());
        // select strong cipher suites
        cfg.setProperty("tls.supportedCipherSuites.cipherSuite",
                StrongTls.getRecommendedCipherSuites(s.getSupportedCipherSuites()));
    } catch (IOException e) {
        log.error("Couldn't determine supported cipher suites", e);
    } finally {
        if (s != null)
            try {
                s.close();
            } catch (IOException e) {
            }
    }
    configure(cfg); // use the defaults for the rest

    setListenAddresses(new InetSocketAddress(configuration.getImapAddress(), configuration.getImapPort()));

    mailboxSessionMapperFactory = new MapperFactory(folderManager);
    MailboxACLResolver aclResolver = createMailboxACLResolver();
    GroupMembershipResolver groupMembershipResolver = new GroupMembershipResolver() {
        public boolean isMember(String user, String group) {
            return true;
        }
    };
    Authenticator authenticator = createAuthenticator(passwordVerifier);
    StoreMailboxManager<String> mailboxManager = new StoreMailboxManager<String>(mailboxSessionMapperFactory,
            authenticator, aclResolver, groupMembershipResolver);
    mailboxManager.setDelegatingMailboxListener(new HashMapDelegatingMailboxListener());
    mailboxManager.setMailboxSessionIdGenerator(new RandomMailboxSessionIdGenerator());

    SubscriptionManager subscriptionManager = createSubscriptionManager();

    ImapProcessor processor = DefaultImapProcessorFactory.createDefaultProcessor(mailboxManager,
            subscriptionManager);
    setImapProcessor(processor);

    setImapEncoder(DefaultImapEncoderFactory.createDefaultEncoder(new Localizer() {
        public String localize(HumanReadableText text, Locales locales) {
            return text.getDefaultValue();
        }
    }, true));
    setImapDecoder(DefaultImapDecoderFactory.createDecoder());
}