Java Examples for javax.net.ssl.SSLSocketFactory

The following java examples will help you to understand the usage of javax.net.ssl.SSLSocketFactory. These source code samples are taken from different open source projects.

Example 1
Project: android-libcore64-master  File: SSLSocketFactoryTest.java View source code
/**
     * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
     */
public void test_createSocket() {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    int sport = startServer("test_createSocket()");
    int[] invalid = { Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE };
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, false);
        assertFalse(s.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, true);
        s.close();
        assertTrue(st.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        sf.createSocket(null, "localhost", sport, true);
        fail("IOException wasn't thrown");
    } catch (IOException ioe) {
    } catch (NullPointerException e) {
    }
    for (int i = 0; i < invalid.length; i++) {
        try {
            Socket s = sf.createSocket(new Socket(), "localhost", 1080, false);
            fail("IOException wasn't thrown");
        } catch (IOException ioe) {
        }
    }
    try {
        Socket st = new Socket("bla-bla", sport);
        Socket s = sf.createSocket(st, "bla-bla", sport, false);
        fail("UnknownHostException wasn't thrown: " + "bla-bla");
    } catch (UnknownHostException uhe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of UnknownHostException");
    }
}
Example 2
Project: android-sdk-sources-for-api-level-23-master  File: SSLSocketFactoryTest.java View source code
/**
     * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
     */
public void test_createSocket() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    int sport = startServer("test_createSocket()");
    int[] invalid = { Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE };
    Socket st = new Socket("localhost", sport);
    Socket s = sf.createSocket(st, "localhost", sport, false);
    assertFalse(s.isClosed());
    st = new Socket("localhost", sport);
    s = sf.createSocket(st, "localhost", sport, true);
    s.close();
    assertTrue(st.isClosed());
    try {
        sf.createSocket(null, "localhost", sport, true);
        fail();
    } catch (NullPointerException expected) {
    }
    for (int i = 0; i < invalid.length; i++) {
        try {
            s = sf.createSocket(new Socket(), "localhost", 1080, false);
            fail();
        } catch (IOException expected) {
        }
    }
    try {
        st = new Socket("1.2.3.4hello", sport);
        s = sf.createSocket(st, "1.2.3.4hello", sport, false);
        fail();
    } catch (UnknownHostException expected) {
    }
}
Example 3
Project: android_platform_libcore-master  File: SSLSocketFactoryTest.java View source code
/**
     * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
     */
public void test_createSocket() {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    int sport = startServer("test_createSocket()");
    int[] invalid = { Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE };
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, false);
        assertFalse(s.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, true);
        s.close();
        assertTrue(st.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        sf.createSocket(null, "localhost", sport, true);
        fail("IOException wasn't thrown");
    } catch (IOException ioe) {
    } catch (NullPointerException e) {
    }
    for (int i = 0; i < invalid.length; i++) {
        try {
            Socket s = sf.createSocket(new Socket(), "localhost", 1080, false);
            fail("IOException wasn't thrown");
        } catch (IOException ioe) {
        }
    }
    try {
        Socket st = new Socket("bla-bla", sport);
        Socket s = sf.createSocket(st, "bla-bla", sport, false);
        fail("UnknownHostException wasn't thrown: " + "bla-bla");
    } catch (UnknownHostException uhe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of UnknownHostException");
    }
}
Example 4
Project: ARTPart-master  File: SSLSocketFactoryTest.java View source code
/**
     * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
     */
public void test_createSocket() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    int sport = startServer("test_createSocket()");
    int[] invalid = { Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE };
    Socket st = new Socket("localhost", sport);
    Socket s = sf.createSocket(st, "localhost", sport, false);
    assertFalse(s.isClosed());
    st = new Socket("localhost", sport);
    s = sf.createSocket(st, "localhost", sport, true);
    s.close();
    assertTrue(st.isClosed());
    try {
        sf.createSocket(null, "localhost", sport, true);
        fail();
    } catch (NullPointerException expected) {
    }
    for (int i = 0; i < invalid.length; i++) {
        try {
            s = sf.createSocket(new Socket(), "localhost", 1080, false);
            fail();
        } catch (IOException expected) {
        }
    }
    try {
        st = new Socket("1.2.3.4hello", sport);
        s = sf.createSocket(st, "1.2.3.4hello", sport, false);
        fail();
    } catch (UnknownHostException expected) {
    }
}
Example 5
Project: robovm-master  File: SSLSocketFactoryTest.java View source code
/**
     * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
     */
public void test_createSocket() {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    int sport = startServer("test_createSocket()");
    int[] invalid = { Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE };
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, false);
        assertFalse(s.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, true);
        s.close();
        assertTrue(st.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        sf.createSocket(null, "localhost", sport, true);
        fail("IOException wasn't thrown");
    } catch (IOException ioe) {
    } catch (NullPointerException e) {
    }
    for (int i = 0; i < invalid.length; i++) {
        try {
            Socket s = sf.createSocket(new Socket(), "localhost", 1080, false);
            fail("IOException wasn't thrown");
        } catch (IOException ioe) {
        }
    }
    try {
        Socket st = new Socket("bla-bla", sport);
        Socket s = sf.createSocket(st, "bla-bla", sport, false);
        fail("UnknownHostException wasn't thrown: " + "bla-bla");
    } catch (UnknownHostException uhe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of UnknownHostException");
    }
}
Example 6
Project: android_libcore-master  File: SSLSocketFactoryTest.java View source code
/**
     * @tests javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
     */
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "createSocket", args = { java.net.Socket.class, java.lang.String.class, int.class, boolean.class })
public void test_createSocket() {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    int sport = startServer("test_createSocket()");
    int[] invalid = { Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE };
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, false);
        assertFalse(s.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        Socket st = new Socket("localhost", sport);
        Socket s = sf.createSocket(st, "localhost", sport, true);
        s.close();
        assertTrue(st.isClosed());
    } catch (Exception ex) {
        fail("Unexpected exception " + ex);
    }
    try {
        sf.createSocket(null, "localhost", sport, true);
        fail("IOException wasn't thrown");
    } catch (IOException ioe) {
    } catch (NullPointerException e) {
    }
    for (int i = 0; i < invalid.length; i++) {
        try {
            Socket s = sf.createSocket(new Socket(), "localhost", 1080, false);
            fail("IOException wasn't thrown");
        } catch (IOException ioe) {
        }
    }
    try {
        Socket st = new Socket("bla-bla", sport);
        Socket s = sf.createSocket(st, "bla-bla", sport, false);
        fail("UnknownHostException wasn't thrown: " + "bla-bla");
    } catch (UnknownHostException uhe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of UnknownHostException");
    }
}
Example 7
Project: activemq-master  File: HttpsClientTransport.java View source code
private SchemeRegistry createSchemeRegistry() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    try {
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(createSocketFactory(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme("https", getRemoteUrl().getPort(), sslSocketFactory));
        return schemeRegistry;
    } catch (Exception e) {
        throw new IllegalStateException("Failure trying to create scheme registry", e);
    }
}
Example 8
Project: manifold-master  File: TrustingSSLSocketFactoryProducer.java View source code
/** Build a secure socket factory based on this producer.
  */
@Override
public javax.net.ssl.SSLSocketFactory getSecureSocketFactory() throws ManifoldCFException {
    try {
        final TrustManager tm = new X509TrustManager() {

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

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { tm }, null);
        return sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        throw new ManifoldCFException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        throw new ManifoldCFException(e.getMessage(), e);
    }
}
Example 9
Project: cyrille-leclerc-master  File: AcceptAllSslSocketFactoryPlainJavaConfiguratorTest.java View source code
@Test
public void test() throws Exception {
    SSLSocketFactory initialDefaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    try {
        String sslUrlWithUntrustedCertificate = "https://localhost";
        {
            // UNTRUSTED CERTIFICATE + DEFAULT SSL_SOCKET_FACTORY : MUST RAISE AN SSL EXCEPTION
            URL url = new URL(sslUrlWithUntrustedCertificate);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            try {
                connection.getResponseCode();
                fail("an exception should have been raised");
            } catch (SSLHandshakeException e) {
            }
        }
        // register the AcceptAllSslSocketFactory
        new AcceptAllSslSocketFactoryPlainJavaConfigurator();
        {
            // UNTRUSTED CERTIFICATE + ACCEPT_ALL SSL_SOCKET_FACTORY : OK
            URL url = new URL(sslUrlWithUntrustedCertificate);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.getResponseCode();
        }
    } finally {
        // restore JVM defaults
        HttpsURLConnection.setDefaultSSLSocketFactory(initialDefaultSSLSocketFactory);
    }
}
Example 10
Project: email-master  File: TestTrustedSocketFactory.java View source code
@Override
public Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException {
    TrustManager[] trustManagers = new TrustManager[] { new VeryTrustingTrustManager() };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
}
Example 11
Project: k-9-master  File: TestTrustedSocketFactory.java View source code
@Override
public Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException {
    TrustManager[] trustManagers = new TrustManager[] { new VeryTrustingTrustManager() };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
}
Example 12
Project: agile4techos-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws CommunicationsException {
    javax.net.ssl.SSLSocketFactory sslFact = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw new CommunicationsException(mysqlIO.connection, mysqlIO.lastPacketSentTimeMs, ioEx);
    }
}
Example 13
Project: GestionBibliotheque-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws CommunicationsException {
    javax.net.ssl.SSLSocketFactory sslFact = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw new CommunicationsException(mysqlIO.connection, mysqlIO.lastPacketSentTimeMs, ioEx);
    }
}
Example 14
Project: StreamFS-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws CommunicationsException {
    javax.net.ssl.SSLSocketFactory sslFact = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw new CommunicationsException(mysqlIO.connection, mysqlIO.lastPacketSentTimeMs, ioEx);
    }
}
Example 15
Project: ant-master  File: TrustManager.java View source code
public static SSLSocketFactory getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final X509TrustManager[] trustAllCerts = new X509TrustManager[] { new X509TrustManager() {

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

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return sslSocketFactory;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 16
Project: AsyncOkHttp-master  File: CustomSSLSocketFactoryCreator.java View source code
public SSLSocketFactory create() {
    SSLSocketFactory sslSocketFactory = null;
    X509TrustManager tm = new X509TrustManager() {

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

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[] { tm }, null);
        sslSocketFactory = sc.getSocketFactory();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return sslSocketFactory;
}
Example 17
Project: bc-java-master  File: DefaultESTHttpClientProvider.java View source code
public ESTClient makeClient() throws ESTException {
    try {
        SSLSocketFactory socketFactory = socketFactoryCreator.createFactory();
        return new DefaultESTClient(new DefaultESTClientSourceProvider(socketFactory, hostNameAuthorizer, timeout, bindingProvider, cipherSuites, absoluteLimit, filterCipherSuites));
    } catch (Exception e) {
        throw new ESTException(e.getMessage(), e.getCause());
    }
}
Example 18
Project: bnd-master  File: HttpsUtil.java View source code
static void disableServerVerification(URLConnection connection) throws GeneralSecurityException {
    if (!(connection instanceof HttpsURLConnection))
        return;
    HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
    } };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsConnection.setSSLSocketFactory(sslSocketFactory);
    HostnameVerifier trustAnyHost = new HostnameVerifier() {

        public boolean verify(String string, SSLSession session) {
            return true;
        }
    };
    httpsConnection.setHostnameVerifier(trustAnyHost);
}
Example 19
Project: Froyo_Email-master  File: SSLUtils.java View source code
/**
     * Returns a {@link SSLSocketFactory}.  Optionally bypass all SSL certificate checks.
     *
     * @param insecure if true, bypass all SSL certificate checks
     */
public static final synchronized SSLSocketFactory getSSLSocketFactory(boolean insecure) {
    if (insecure) {
        if (sInsecureFactory == null) {
            sInsecureFactory = SSLCertificateSocketFactory.getInsecure(0, null);
        }
        return sInsecureFactory;
    } else {
        if (sSecureFactory == null) {
            sSecureFactory = SSLCertificateSocketFactory.getDefault(0, null);
        }
        return sSecureFactory;
    }
}
Example 20
Project: GeoKnowGeneratorUI-master  File: SSLEmailSender.java View source code
public void send(String toEmail, String msgSubject, String msgText) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.socketFactory.port", smtpPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", smtpPort);
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUsername, emailPassword);
        }
    });
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(fromEmail));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
    message.setSubject(msgSubject);
    message.setText(msgText);
    Transport.send(message);
}
Example 21
Project: IEmail-master  File: SSLUtils.java View source code
/**
     * Returns a {@link SSLSocketFactory}.  Optionally bypass all SSL certificate checks.
     *
     * @param insecure if true, bypass all SSL certificate checks
     */
public static final synchronized SSLSocketFactory getSSLSocketFactory(boolean insecure) {
    if (insecure) {
        if (sInsecureFactory == null) {
            sInsecureFactory = SSLCertificateSocketFactory.getInsecure(0, null);
        }
        return sInsecureFactory;
    } else {
        if (sSecureFactory == null) {
            sSecureFactory = SSLCertificateSocketFactory.getDefault(0, null);
        }
        return sSecureFactory;
    }
}
Example 22
Project: javacuriosities-master  File: Step2SSLClient.java View source code
public static void main(String[] args) {
    try {
        System.setProperty("javax.net.ssl.trustStore", "MyClientTrustStore");
        System.setProperty("javax.net.ssl.trustStorePassword", "123456");
        SocketFactory socketFactory = SSLSocketFactory.getDefault();
        Socket socketToConnect = socketFactory.createSocket(InetAddress.getLocalHost(), 4000);
        // Obtenemos el input stream para leer datos
        InputStream is = socketToConnect.getInputStream();
        DataInputStream dis = new DataInputStream(is);
        String dataFromServer = new String(dis.readUTF());
        System.out.println(dataFromServer);
        // Luego cerramos los stream y el socket
        dis.close();
        is.close();
        socketToConnect.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 23
Project: kaleido-repository-master  File: LocalMailSessionServiceTest.java View source code
@Test
public void provideLocalSession() {
    assertNotNull(mailSessionService);
    assertTrue(mailSessionService instanceof LocalMailSessionService);
    LocalMailSessionService localMailSession = ((LocalMailSessionService) mailSessionService);
    assertEquals("smtp.gmail.com", localMailSession.context.getString("smtp.host"));
    assertEquals(Integer.valueOf(465), localMailSession.context.getInteger("smtp.port"));
    assertEquals(true, localMailSession.context.getBoolean("smtp.auth.enable"));
    assertEquals(true, localMailSession.context.getBoolean("smtp.ssl"));
    assertEquals("javax.net.ssl.SSLSocketFactory", localMailSession.context.getString("smtp.socketFactory.class"));
    assertEquals(Integer.valueOf(465), localMailSession.context.getInteger("smtp.socketFactory.port"));
}
Example 24
Project: maven-confluence-plugin-master  File: Issue130IntegrationTest.java View source code
@Before
@Override
public void initService() throws Exception {
    super.initService();
    try {
        // SSL Implementation
        final SSLSocketFactory sslSocketFactory = SSLFactories.newInstance(new YesTrustManager());
        Assert.assertThat(sslSocketFactory, IsNull.notNullValue());
        final X509TrustManager trustManager = new YesTrustManager();
        final HostnameVerifier hostnameVerifier = new YesHostnameVerifier();
        service.client.hostnameVerifier(hostnameVerifier).sslSocketFactory(sslSocketFactory, trustManager);
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}
Example 25
Project: mobicents-master  File: TLSTransportClient.java View source code
public void initialize() throws IOException, NotInitializedException {
    if (destAddress == null)
        throw new NotInitializedException("Destination address is not set");
    SSLSocketFactory cltFct = parentConnection.getSSLFactory();
    SSLSocket sck = (SSLSocket) cltFct.createSocket(destAddress.getAddress(), destAddress.getPort());
    sck.setEnableSessionCreation(parentConnection.getSSLConfig().getBooleanValue(SDEnableSessionCreation.ordinal(), true));
    sck.setUseClientMode(!parentConnection.getSSLConfig().getBooleanValue(SDUseClientMode.ordinal(), true));
    if (parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), "") != null) {
        sck.setEnabledCipherSuites(parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), "").split(","));
    }
    socketChannel = sck.getChannel();
    socketChannel.connect(destAddress);
    socketChannel.configureBlocking(true);
    parentConnection.onConnected();
}
Example 26
Project: MVP-master  File: TrustManager.java View source code
public static SSLSocketFactory getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final X509TrustManager[] trustAllCerts = new X509TrustManager[] { new X509TrustManager() {

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

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return sslSocketFactory;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 27
Project: themes-platform-packages-apps-Email-master  File: SSLUtils.java View source code
/**
     * Returns a {@link SSLSocketFactory}.  Optionally bypass all SSL certificate checks.
     *
     * @param insecure if true, bypass all SSL certificate checks
     */
public static final synchronized SSLSocketFactory getSSLSocketFactory(boolean insecure) {
    if (insecure) {
        if (sInsecureFactory == null) {
            sInsecureFactory = SSLCertificateSocketFactory.getInsecure(0, null);
        }
        return sInsecureFactory;
    } else {
        if (sSecureFactory == null) {
            sSecureFactory = SSLCertificateSocketFactory.getDefault(0, null);
        }
        return sSecureFactory;
    }
}
Example 28
Project: VVM_OMTP_stack-master  File: SSLUtils.java View source code
/**
     * Returns a {@link SSLSocketFactory}.  Optionally bypass all SSL certificate checks.
     *
     * @param insecure if true, bypass all SSL certificate checks
     */
public static final synchronized SSLSocketFactory getSSLSocketFactory(boolean insecure) {
    if (insecure) {
        if (sInsecureFactory == null) {
            sInsecureFactory = SSLCertificateSocketFactory.getInsecure(0, null);
        }
        return sInsecureFactory;
    } else {
        if (sSecureFactory == null) {
            sSecureFactory = SSLCertificateSocketFactory.getDefault(0, null);
        }
        return sSecureFactory;
    }
}
Example 29
Project: red5-client-master  File: SslSocketFactory.java View source code
private static javax.net.ssl.SSLSocketFactory getSSLFactory() {
    if (sslFactory == null) {
        try {
            sslFactory = BogusSslContextFactory.getInstance(false).getSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("could not create SSL socket", e);
        }
    }
    return sslFactory;
}
Example 30
Project: aperte-workflow-core-master  File: TSLSendNotificationTests.java View source code
public void test_1() {
    final String userName = "axa-mail";
    final String password = "Blue105";
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", "192.168.2.12");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.user", userName);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", "588");
    props.put("mail.smtp.auth.plain.disable", "true");
    //		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    //		props.put("ssl.SocketFactory.provider", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.class", "pl.net.bluesoft.rnd.pt.ext.bpmnotifications.socket.ExchangeSSLSocketFactory");
    props.put("ssl.SocketFactory.provider", "pl.net.bluesoft.rnd.pt.ext.bpmnotifications.socket.ExchangeSSLSocketFactory");
    try {
        Authenticator auth = new Authenticator() {

            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };
        Session session = Session.getInstance(props, auth);
        session.setDebug(true);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("axa-mail@bluesoft.net.pl"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("axa-mail@bluesoft.net.pl"));
        message.setSubject("test");
        message.setSentDate(new Date());
        //body
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent("test <br><b>test gruby</b><br> test żołądków", (true ? "text/html" : "text/plain") + "; charset=\"UTF-8\"");
        Multipart multipart = new MimeMultipart("alternative");
        multipart.addBodyPart(messagePart);
        //zalaczniki
        int counter = 0;
        URL url;
        message.setContent(multipart);
        message.setSentDate(new Date());
        Transport.send(message);
    //            Transport transport = session.getTransport("smtp");
    //            transport.connect(secureHost, Integer.parseInt(securePort), userName, userPassword);
    //            transport.sendMessage(msg, msg.getAllRecipients());
    //            transport.close();
    } catch (Exception mex) {
        mex.printStackTrace();
        fail();
    }
}
Example 31
Project: Android-tcp-long-connection-based-on-Apache-mina-master  File: SslSocketFactory.java View source code
private javax.net.ssl.SSLSocketFactory getSSLFactory() {
    if (sslFactory == null) {
        try {
            sslFactory = BogusSslContextFactory.getInstance(false).getSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("could not create SSL socket", e);
        }
    }
    return sslFactory;
}
Example 32
Project: asyn4j-master  File: SslSocketFactory.java View source code
private javax.net.ssl.SSLSocketFactory getSSLFactory() {
    if (sslFactory == null) {
        try {
            sslFactory = BogusSslContextFactory.getInstance(false).getSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("could not create SSL socket", e);
        }
    }
    return sslFactory;
}
Example 33
Project: directory-server-master  File: SSLSocketFactory.java View source code
private javax.net.ssl.SSLSocketFactory getSSLFactory() {
    if (sslFactory == null) {
        try {
            sslFactory = BogusSSLContextFactory.getInstance(false).getSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("could not create SSL socket", e);
        }
    }
    return sslFactory;
}
Example 34
Project: keycloak-master  File: JSSETruststoreConfigurator.java View source code
public javax.net.ssl.SSLSocketFactory getSSLSocketFactory() {
    if (provider == null) {
        return null;
    }
    if (sslFactory == null) {
        synchronized (this) {
            if (sslFactory == null) {
                try {
                    SSLContext sslctx = SSLContext.getInstance("TLS");
                    sslctx.init(null, getTrustManagers(), null);
                    sslFactory = sslctx.getSocketFactory();
                } catch (Exception e) {
                    throw new RuntimeException("Failed to initialize SSLContext: ", e);
                }
            }
        }
    }
    return sslFactory;
}
Example 35
Project: Leboncoin-master  File: MailManager.java View source code
public static synchronized boolean doActionGmail(MessageProcess f, int attempts) {
    try {
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.port", "465");
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("smtp.gmail.com", DefaultUserConf.EMAIL, DefaultUserConf.PASSWORD);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        // Get directory
        Flags seen = new Flags(Flags.Flag.SEEN);
        FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
        Message messages[] = inbox.search(unseenFlagTerm);
        for (int i = 0; i < messages.length; i++) {
            f.treatMessage(messages[i]);
        }
        // Close connection
        inbox.close(true);
        store.close();
        return true;
    } catch (Exception e) {
        Logger.traceERROR(e);
        Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
        if (attempts > MAX_ATTEMPS) {
            return false;
        } else {
            doActionGmail(f, attempts++);
        }
    }
    return false;
}
Example 36
Project: mina-ja-master  File: SslSocketFactory.java View source code
private javax.net.ssl.SSLSocketFactory getSSLFactory() {
    if (sslFactory == null) {
        try {
            sslFactory = BogusSslContextFactory.getInstance(false).getSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("could not create SSL socket", e);
        }
    }
    return sslFactory;
}
Example 37
Project: pircbotx-master  File: UtilSSLSocketFactoryTest.java View source code
/**
	 * Ghetto diff by converting all signatures to Strings and replacing
	 * SSLSocketFactory with UtilSSLSocketFactory
	 */
@Test
public void delegatesAllMethods() {
    Set<String> implMethodSignatures = new HashSet<String>();
    for (Method curMethod : findPublicMethods(UtilSSLSocketFactory.class.getMethods())) {
        implMethodSignatures.add(curMethod.toGenericString());
        log.debug("added " + curMethod.toGenericString());
    }
    log.debug("");
    int failCount = 0;
    for (Method curMethod : findPublicMethods(SSLSocketFactory.class.getMethods())) {
        String newMethodSignature = curMethod.toGenericString().replace("javax.net.ssl.SSLSocketFactory", "org.pircbotx.UtilSSLSocketFactory").replace("javax.net.SocketFactory", "org.pircbotx.UtilSSLSocketFactory").replace(" java.net.Socket", " javax.net.ssl.SSLSocket").replace("abstract ", "");
        if (!implMethodSignatures.contains(newMethodSignature)) {
            log.debug(curMethod.toGenericString());
            log.debug("(expected) " + newMethodSignature);
            failCount++;
        }
    }
    assertEquals(failCount, 0, "UtilSSLSocketFactory fails to implement methods");
}
Example 38
Project: AFBaseLibrary-master  File: AFCertificateUtil.java View source code
public static SSLSocketFactory setCertificates(Context context, String... certificateNames) {
    InputStream[] certificates = getCertificatesByAssert(context, certificateNames);
    if (certificates == null) {
        return null;
    }
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 39
Project: Airscribe-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 40
Project: ambry-master  File: SSLFactoryTest.java View source code
@Test
public void testSSLFactory() throws Exception {
    File trustStoreFile = File.createTempFile("truststore", ".jks");
    SSLConfig sslConfig = new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.SERVER, trustStoreFile, "server"));
    SSLConfig clientSSLConfig = new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.CLIENT, trustStoreFile, "client"));
    SSLFactory sslFactory = new SSLFactory(sslConfig);
    SSLContext sslContext = sslFactory.getSSLContext();
    SSLSocketFactory socketFactory = sslContext.getSocketFactory();
    Assert.assertNotNull(socketFactory);
    SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
    Assert.assertNotNull(serverSocketFactory);
    SSLEngine serverSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.SERVER);
    TestSSLUtils.verifySSLConfig(sslContext, serverSideSSLEngine, false);
    //client
    sslFactory = new SSLFactory(clientSSLConfig);
    sslContext = sslFactory.getSSLContext();
    socketFactory = sslContext.getSocketFactory();
    Assert.assertNotNull(socketFactory);
    serverSocketFactory = sslContext.getServerSocketFactory();
    Assert.assertNotNull(serverSocketFactory);
    SSLEngine clientSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.CLIENT);
    TestSSLUtils.verifySSLConfig(sslContext, clientSideSSLEngine, true);
}
Example 41
Project: Android-Backup-master  File: AllTrustedSocketFactory.java View source code
@Override
public Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException {
    TrustManager[] trustManagers = new TrustManager[] { new InsecureX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, null);
    SSLSocketFactory socketFactory = sslContext.getSocketFactory();
    Socket trustedSocket;
    if (socket == null) {
        trustedSocket = socketFactory.createSocket();
    } else {
        trustedSocket = socketFactory.createSocket(socket, host, port, true);
    }
    return trustedSocket;
}
Example 42
Project: android-tutorials-glide-master  File: UnsafeOkHttpClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 43
Project: ant-ldap-master  File: LdapTask.java View source code
protected void connectLdapWith(Runnable runnable) throws BuildException {
    log("Connecting to LDAP " + getUri(), 3);
    try {
        if (ssl) {
            SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
            SSLSocketFactory socketFactory = sslUtil.createSSLSocketFactory();
            connection = new LDAPConnection(socketFactory, host, getPort());
        } else {
            connection = new LDAPConnection(host, getPort());
        }
        try {
            try {
                connection.bind(bindDn, password);
            } catch (LDAPException e) {
                throw new BuildException("Cannot bind to " + getUri() + " using DN " + bindDn, e);
            }
            runnable.run();
        } finally {
            connection.close();
        }
    } catch (LDAPException e) {
        throw new BuildException("Cannot connect to LDAP Server " + getUri(), e);
    } catch (GeneralSecurityException e) {
        throw new BuildException("Cannot create SSL Socket Factory", e);
    }
}
Example 44
Project: AppWorkUtils-master  File: TrustALLSSLFactory.java View source code
public static SSLSocketFactory getSSLFactoryTrustALL() throws IOException {
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, TrustALLSSLFactory.trustAllCerts, new java.security.SecureRandom());
        return sc.getSocketFactory();
    } catch (final NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (final KeyManagementException e) {
        throw new IOException(e);
    }
}
Example 45
Project: aramis-build-toolkit-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 46
Project: BansheeCore-master  File: JAXWSDispatcherImpl.java View source code
@Override
public void setCertificateSelectors(String reference, InputStream keyStoreData, String keyStorePassword, InputStream trustStoreData, String trustStorePassword, CertificateCallback callback) throws GeneralSecurityException, IOException {
    SSLSocketFactoryGenerator generator = new SSLSocketFactoryGenerator();
    SSLSocketFactory socketFactory = generator.getSSLSocketFactoryInstance(reference, keyStoreData, keyStorePassword, trustStoreData, trustStorePassword, callback);
    getDelegate().getRequestContext().put("com.sun.xml.ws.transport.https.client.SSLSocketFactory", socketFactory);
}
Example 47
Project: Bescrewed-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 48
Project: betsy-master  File: TrustModifier.java View source code
/** Call this with any HttpURLConnection, and it will
         modify the trust settings if it is an HTTPS connection. */
public static void relaxHostChecking(HttpURLConnection conn) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection httpsConnection = (HttpsURLConnection) conn;
        SSLSocketFactory factory = prepFactory(httpsConnection);
        httpsConnection.setSSLSocketFactory(factory);
        httpsConnection.setHostnameVerifier(TRUSTING_HOSTNAME_VERIFIER);
    }
}
Example 49
Project: Bingo-master  File: HttpsCoder.java View source code
private static SSLSocketFactory getSSLSocketFactory(InputStream keyStoreInputStream, String password) throws Exception {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore keyStore = getKeyStore(keyStoreInputStream, password);
    keyManagerFactory.init(keyStore, password.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    SSLContext context = SSLContext.getInstance(PROTOCOL);
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    keyStoreInputStream.close();
    return context.getSocketFactory();
}
Example 50
Project: BitTorrentApp-master  File: TrustALLSSLFactory.java View source code
public static SSLSocketFactory getSSLFactoryTrustALL() throws IOException {
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, TrustALLSSLFactory.trustAllCerts, new java.security.SecureRandom());
        return sc.getSocketFactory();
    } catch (final NoSuchAlgorithmException e) {
        throw new IOException(e.toString());
    } catch (final KeyManagementException e) {
        throw new IOException(e.toString());
    }
}
Example 51
Project: cirmlive-master  File: AllowAnySSL.java View source code
public void installPermissiveTrustmanager() {
    // Imports: javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
Example 52
Project: cloudbees-api-client-master  File: TrustAllSocketFactory.java View source code
public static SSLSocketFactory create() {
    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException {
                if (LOGGER.isLoggable(FINE)) {
                    LOGGER.fine("Got the certificate: " + Arrays.asList(x509Certificates));
                }
            // TODO: define a mechanism for users to accept a certificate from UI
            //                    try {
            //                        CertificateUtil.validatePath(Arrays.asList(x509Certificates));
            //                    } catch (GeneralSecurityException e) {
            //                        e.printStackTrace();
            //                    }
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());
        return context.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        throw new Error(e);
    } catch (KeyManagementException e) {
        throw new Error(e);
    }
}
Example 53
Project: commons-eid-master  File: BeIDSocketFactory.java View source code
public static SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    if (BeIDSocketFactory.socketFactorSingleton == null) {
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");
        sslContext.init(keyManagerFactory.getKeyManagers(), null, SecureRandom.getInstance("BeID"));
        socketFactorSingleton = sslContext.getSocketFactory();
    }
    return socketFactorSingleton;
}
Example 54
Project: constellio-master  File: SmtpServerTestConfig.java View source code
@Override
public Map<String, String> getProperties() {
    Map<String, String> properties = new HashMap<>();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.port", "465");
    /*
		properties.put("mail.smtp.host", "smtp.mandrillapp.com");//-relay
		properties.put("mail.smtp.port", "587");
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
*/
    return properties;
}
Example 55
Project: digits-android-master  File: DigitsApiClientTests.java View source code
@Before
public void setUp() throws Exception {
    authConfig = new TwitterAuthConfig(TestConstants.CONSUMER_SECRET, TestConstants.CONSUMER_KEY);
    twitterCore = new TwitterCore(authConfig);
    guestSession = DigitsSession.create(DigitsSessionTests.getNewLoggedOutUser(), TestConstants.PHONE);
    activityClassManagerFactory = new ActivityClassManagerFactory();
    prefManager = mock(ContactsPreferenceManager.class);
    digitsApiClient = new DigitsApiClient(guestSession, twitterCore, mock(SSLSocketFactory.class), mock(ExecutorService.class), mock(DigitsRequestInterceptor.class), mock(ApiInterface.class));
}
Example 56
Project: ecf-master  File: ECFURLConnectionModifier.java View source code
private SSLSocketFactory getSSLSocketFactory() {
    if (context == null)
        return null;
    if (sslSocketFactoryTracker == null) {
        sslSocketFactoryTracker = new ServiceTracker(this.context, SSLSocketFactory.class.getName(), null);
        sslSocketFactoryTracker.open();
    }
    return (SSLSocketFactory) sslSocketFactoryTracker.getService();
}
Example 57
Project: egdownloader-master  File: HttpsUtils.java View source code
private static HttpsURLConnection getHttpsConnection(String urlStr, Proxy proxy) throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URL url = new URL(urlStr);
    HttpsURLConnection conn = null;
    if (proxy != null) {
        conn = (HttpsURLConnection) url.openConnection(proxy);
    } else {
        conn = (HttpsURLConnection) url.openConnection();
    }
    // ä¸?验è¯?æœ?务器主机å??å’Œè¯?书
    conn.setHostnameVerifier(new IgnoreHostnameVerifier());
    TrustManager[] tm = { new X509TrustManager4Portal() };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tm, null);
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    conn.setSSLSocketFactory(ssf);
    return conn;
}
Example 58
Project: fluxtream-app-master  File: MailUtils.java View source code
public static Store getGmailImapStore(String emailuser, String emailpassword) throws MessagingException {
    Session session;
    String emailserver = "imap.gmail.com";
    String emailprovider = "imaps";
    Store store = null;
    Properties props = System.getProperties();
    props.setProperty("mail.pop3s.rsetbeforequit", "true");
    props.setProperty("mail.pop3.rsetbeforequit", "true");
    props.setProperty("mail.imaps.port", "993");
    props.setProperty("mail.imaps.host", "imap.gmail.com");
    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.imap.socketFactory.fallback", "false");
    session = Session.getInstance(props, null);
    store = session.getStore(emailprovider);
    store.connect(emailserver, emailuser, emailpassword);
    return store;
}
Example 59
Project: frostwire-common-master  File: TrustALLSSLFactory.java View source code
public static SSLSocketFactory getSSLFactoryTrustALL() throws IOException {
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, TrustALLSSLFactory.trustAllCerts, new java.security.SecureRandom());
        return sc.getSocketFactory();
    } catch (final NoSuchAlgorithmException e) {
        throw new IOException(e.toString());
    } catch (final KeyManagementException e) {
        throw new IOException(e.toString());
    }
}
Example 60
Project: gestion_autoecole_xelais-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 61
Project: gngr-master  File: TrustManager.java View source code
public static SSLSocketFactory makeSSLSocketFactory(final InputStream extraCertsStream) {
    final String sep = File.separator;
    final String hardDefaultPath = System.getProperty("java.home") + sep + "lib" + sep + "security" + sep + "cacerts";
    final String defaultStorePath = System.getProperty("javax.net.ssl.trustStore", hardDefaultPath);
    try (final FileInputStream defaultIS = new FileInputStream(defaultStorePath)) {
        final KeyStore defKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        defKeyStore.load(defaultIS, "changeit".toCharArray());
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(extraCertsStream, null);
        // final KeyStore keyStore =  KeyStore.Builder.newInstance(defKeyStore, null).getKeyStore();
        final Enumeration<String> aliases = defKeyStore.aliases();
        while (aliases.hasMoreElements()) {
            final String alias = aliases.nextElement();
            if (defKeyStore.isCertificateEntry(alias)) {
                final Entry entry = defKeyStore.getEntry(alias, null);
                keyStore.setEntry(alias, entry, null);
            }
        }
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        final SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, tmf.getTrustManagers(), null);
        return sc.getSocketFactory();
    } catch (KeyManagementExceptionKeyStoreException | NoSuchAlgorithmException | IOException | CertificateException | UnrecoverableEntryException |  e) {
        throw new RuntimeException(e);
    }
}
Example 62
Project: gocd-master  File: GoSSLConfigTest.java View source code
@Test
public void shouldUseWeakConfigWhenSslConfigFlagTurnedOff() {
    when(systemEnvironment.get(SystemEnvironment.GO_SSL_CONFIG_ALLOW)).thenReturn(false);
    GoSSLConfig goSSLConfig = new GoSSLConfig(mock(SSLSocketFactory.class), systemEnvironment);
    SSLConfig config = (SSLConfig) ReflectionUtil.getField(goSSLConfig, "config");
    assertThat(config instanceof WeakSSLConfig, is(true));
}
Example 63
Project: Gruppe34-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 64
Project: hairy-robot-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 65
Project: i-Prog-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 66
Project: interactivespaces-master  File: XmlRpcSun14HttpTransport.java View source code
protected URLConnection newURLConnection(URL pURL) throws IOException {
    final URLConnection conn = super.newURLConnection(pURL);
    final SSLSocketFactory sslSockFactory = getSSLSocketFactory();
    if ((sslSockFactory != null) && (conn instanceof HttpsURLConnection))
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSockFactory);
    return conn;
}
Example 67
Project: iOS-Automation-master  File: EmailReport.java View source code
public static void sendMail() {
    Properties props = new Properties();
    props.put("mail.smtp.from", Constants.EMAIL_FROM);
    props.put("mail.smtp.host", Constants.EMAIL_HOST);
    props.put("mail.smtp.port", Constants.EMAIL_PORT);
    props.put("mail.smtp.auth", Constants.EMAIL_SMTP_AUTH);
    props.put("mail.smtp.socketFactory.port", Constants.EMAIL_PORT);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.starttls.enable", "true");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(Constants.EMAIL_USERNAME, Constants.EMAIL_PASSWORD);
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(Constants.EMAIL_FROM));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Constants.EMAIL_TO));
        message.setSubject("Testing Report");
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(Constants.REPORT_FILEPATH);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(Constants.REPORT_FILENAME);
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);
        System.out.println("Sending Email...");
        Transport.send(message);
        System.out.println("Email sent.");
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
Example 68
Project: JAVA_ISDS-master  File: ClientCertAuthentication.java View source code
@Override
protected SSLSocketFactory createSSLSocketFactory() throws DataBoxException {
    try {
        // System.setProperty("https.protocols", "SSLv3");
        // System.setProperty("javax.net.debug", "all");
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // KeyStore keyStore = Utils.createTrustStore();
        InputStream keyInput = new FileInputStream(certFile);
        keyStore.load(keyInput, certPassword.toCharArray());
        keyInput.close();
        keyManagerFactory.init(keyStore, certPassword.toCharArray());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new DataBoxException("Can't create SSLSocketFactory.", ex);
        }
    }
}
Example 69
Project: keratin-irc-master  File: TrustAllTrustManager.java View source code
/**
     * Get a SSLSocketFactory using this X509TrustManager.
     */
public static synchronized SSLSocketFactory getSSLSocketFactory() {
    if (trustAllSocketFactory == null) {
        try {
            KeyManager[] km = new KeyManager[0];
            TrustManager[] tm = new TrustManager[] { new TrustAllTrustManager() };
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(km, tm, new SecureRandom());
            trustAllSocketFactory = (SSLSocketFactory) context.getSocketFactory();
        } catch (KeyManagementExceptionNoSuchAlgorithmException |  e) {
            Logger.error(e, "Error creating custom SSLSocketFactory");
            throw new RuntimeException("Error creating custom SSLSocketFactory", e);
        }
    }
    return trustAllSocketFactory;
}
Example 70
Project: KolabDroid-master  File: ImapClient.java View source code
public static Session getDefaultImapSession(int port, boolean useSsl) {
    java.util.Properties props = new java.util.Properties();
    if (useSsl) {
        props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }
    props.setProperty("mail.imap.socketFactory.fallback", "false");
    props.setProperty("mail.imap.socketFactory.port", Integer.toString(port));
    Session session = Session.getDefaultInstance(props);
    return session;
}
Example 71
Project: LakeBase-parsing-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 72
Project: liqui-cap-online-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 73
Project: mireka-master  File: JsseDefaultTlsConfiguration.java View source code
@Override
public SSLSocket createSSLSocket(Socket socket) throws IOException {
    SSLSocketFactory socketFactory = ((SSLSocketFactory) SSLSocketFactory.getDefault());
    InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
    SSLSocket sslSocket = (SSLSocket) (socketFactory.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));
    // we are a server
    sslSocket.setUseClientMode(false);
    return sslSocket;
}
Example 74
Project: mobilecloud-15-master  File: UnsafeHttpsClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 75
Project: MPF_Portal-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 76
Project: mysql-connector-java-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 77
Project: NemoVelo-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 78
Project: Netuno-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 79
Project: netx-master  File: HttpOriginSecurityImpl.java View source code
@Override
protected Socket createSocket0(URL url) throws IOException {
    String protocol = url.getProtocol();
    String host = url.getHost();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
    }
    if ("http".equalsIgnoreCase(protocol)) {
        SocketFactory socketFactory = SocketFactory.getDefault();
        return socketFactory.createSocket(host, port);
    } else if ("https".equalsIgnoreCase(protocol)) {
        SocketFactory socketFactory = SSLSocketFactory.getDefault();
        return socketFactory.createSocket(host, port);
    } else {
        throw new IllegalStateException(format("Unexpected protocol: %s", protocol));
    }
}
Example 80
Project: nv-websocket-client-master  File: SocketFactorySettings.java View source code
public SocketFactory selectSocketFactory(boolean secure) {
    if (secure) {
        if (mSSLContext != null) {
            return mSSLContext.getSocketFactory();
        }
        if (mSSLSocketFactory != null) {
            return mSSLSocketFactory;
        }
        return SSLSocketFactory.getDefault();
    }
    if (mSocketFactory != null) {
        return mSocketFactory;
    }
    return SocketFactory.getDefault();
}
Example 81
Project: ofbiz-master  File: SSLClientSocketFactory.java View source code
public Socket createSocket(String host, int port) throws IOException {
    try {
        SSLSocketFactory factory = SSLUtil.getSSLSocketFactory();
        return factory.createSocket(host, port);
    } catch (GeneralSecurityException e) {
        Debug.logError(e, module);
        throw new IOException(e.getMessage());
    } catch (GenericConfigException e) {
        throw new IOException(e.getMessage());
    }
}
Example 82
Project: ogham-master  File: BasicGmailSSLSample.java View source code
public static void main(String[] args) throws MessagingException {
    // configure properties (could be stored in a properties file or defined
    // in System properties)
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.host", "smtp.gmail.com");
    properties.setProperty("mail.smtp.port", "465");
    properties.setProperty("mail.smtp.socketFactory.port", "465");
    properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("ogham.email.authenticator.username", "<your gmail username>");
    properties.setProperty("ogham.email.authenticator.password", "<your gmail password>");
    properties.setProperty("ogham.email.from", "<your gmail address>");
    // Instantiate the messaging service using default behavior and
    // provided properties
    MessagingService service = new MessagingBuilder().useAllDefaults(properties).build();
    // send the email
    service.send(new Email("subject", "email content", "<recipient address>"));
    // or using fluent API
    service.send(new Email().subject("subject").content("email content").to("<recipient address>"));
}
Example 83
Project: OpenMapKit-master  File: NetworkUtils.java View source code
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
    OkHttpClient client = new OkHttpClient();
    if (cache != null) {
        client.setCache(cache);
    }
    if (sslSocketFactory != null) {
        client.setSslSocketFactory(sslSocketFactory);
    }
    HttpURLConnection connection = new OkUrlFactory(client).open(url);
    connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
    return connection;
}
Example 84
Project: osgi-maven-master  File: SendMailApp.java View source code
/**
	 * @param args
	 */
public static void main(final String[] args) {
    final Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    props.put("mail.debug", "false");
    props.put("mail.debug.auth", "false");
    // final MailHandler h = new MailHandler(props);
    // h.setLevel(Level.OFF);
    final Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("max@onedb.de", "");
        }
    });
    try {
        final Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("max@onedb.de"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("max@onedb.de"));
        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse("max@onedb.de"));
        message.setSubject("Your onedb Api Key");
        message.setText("Dear User," + "\n\nThank you for getting an API key for onedb.de.\n\n" + "    Your key is: [ergjoerijwefjoiwef] (excluding [])\n\n" + "To get started, check out:\n\n" + "   http://missinglinkblog.com/2012/04/28/onedb-getting-started\n\n" + "Max");
        Transport.send(message);
        System.out.println("Done");
    } catch (final MessagingException e) {
        throw new RuntimeException(e);
    }
}
Example 85
Project: osm-contributor-master  File: FlickrUploadUtils.java View source code
public static RestAdapter getRestAdapter(final Map<String, String> oAuthParams) {
    if (adapter == null) {
        OkHttpClient okHttpClient = new OkHttpClient();
        try {
            SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(new URL("https://up.flickr.com/services"));
            okHttpClient.setSslSocketFactory(NoSSLv3Factory);
            adapter = new RestAdapter.Builder().setConverter(new StringConverter()).setEndpoint("https://up.flickr.com/services").setClient(new OkClient(okHttpClient)).setRequestInterceptor(new RequestInterceptor() {

                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Authorization", FlickrSecurityUtils.getAuthorizationHeader(oAuthParams));
                }
            }).build();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }
    return adapter;
}
Example 86
Project: owncloud-gallery-master  File: TrustModifier.java View source code
/**
	 * Call this with any HttpURLConnection, and it will modify the trust
	 * settings if it is an HTTPS connection.
	 */
public static void relaxHostChecking(HttpURLConnection conn) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection httpsConnection = (HttpsURLConnection) conn;
        SSLSocketFactory factory = prepFactory(httpsConnection);
        httpsConnection.setSSLSocketFactory(factory);
        httpsConnection.setHostnameVerifier(TRUSTING_HOSTNAME_VERIFIER);
    }
}
Example 87
Project: POCenter-master  File: UnsafeOkHttpUtils.java View source code
/**
     * don't verify certificate
     * @return
     */
public static OkHttpClient getClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 88
Project: programming-cloud-services-for-android-master  File: UnsafeHttpsClient.java View source code
public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 89
Project: quitesleep-master  File: MailConfig.java View source code
//------------------------------------------------------------------------//
public static void initProperties() {
    try {
        properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.host", "smtp.gmail.com");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smpt.port", "465");
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.quitwait", "false");
    } catch (Exception e) {
        Log.e(CLASS_NAME, ExceptionUtils.getString(e));
    }
}
Example 90
Project: Reorder-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 91
Project: rosjava_core-master  File: XmlRpcSun14HttpTransport.java View source code
protected URLConnection newURLConnection(URL pURL) throws IOException {
    final URLConnection conn = super.newURLConnection(pURL);
    final SSLSocketFactory sslSockFactory = getSSLSocketFactory();
    if ((sslSockFactory != null) && (conn instanceof HttpsURLConnection))
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSockFactory);
    return conn;
}
Example 92
Project: Shuttle-Tracker-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 93
Project: sms-backup-plus-master  File: AllTrustedSocketFactory.java View source code
@Override
public Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException {
    TrustManager[] trustManagers = new TrustManager[] { new InsecureX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, null);
    SSLSocketFactory socketFactory = sslContext.getSocketFactory();
    Socket trustedSocket;
    if (socket == null) {
        trustedSocket = socketFactory.createSocket();
    } else {
        trustedSocket = socketFactory.createSocket(socket, host, port, true);
    }
    return trustedSocket;
}
Example 94
Project: sphere-snowflake-master  File: Email.java View source code
public static void send(String to, String subject, String body, String from, String host, int port, boolean auth) {
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", auth);
    properties.put("mail.smtp.socketFactory.port", port);
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    Authenticator authenticator = null;
    if (auth) {
        authenticator = new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(key, secret);
            }
        };
    }
    Session session = Session.getInstance(properties, authenticator);
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        MimeBodyPart mimeBody = new MimeBodyPart();
        mimeBody.setContent(body, "text/html");
        MimeMultipart mimeMulti = new MimeMultipart();
        mimeMulti.addBodyPart(mimeBody);
        message.setContent(mimeMulti);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Example 95
Project: spring-data-mongodb-master  File: MongoOptionsFactoryBeanUnitTests.java View source code
// DATAMONGO-764
@Test
public void testSslConnection() throws Exception {
    MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
    bean.setSsl(true);
    bean.afterPropertiesSet();
    MongoClientOptions options = bean.getObject();
    assertNotNull(options.getSocketFactory());
    assertTrue(options.getSocketFactory() instanceof SSLSocketFactory);
}
Example 96
Project: SRS_CS_Project-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 97
Project: tinify-java-master  File: SSLContext.java View source code
public static SSLSocketFactory getSocketFactory() {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(certificateStream());
        KeyStore keyStore = newEmptyKeyStore();
        int index = 0;
        for (Certificate certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificate);
        }
        if (keyStore.size() == 0) {
            /* The resource stream was empty, no certificates were found. */
            throw new ConnectionException("Unable to load any CA certificates.", null);
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, null);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (GeneralSecurityExceptionIOException |  e) {
        throw new ConnectionException("Error while loading trusted CA certificates.", e);
    }
}
Example 98
Project: Tower-master  File: NetworkUtils.java View source code
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
    OkHttpClient client = new OkHttpClient();
    if (cache != null) {
        client.setCache(cache);
    }
    if (sslSocketFactory != null) {
        client.setSslSocketFactory(sslSocketFactory);
    }
    HttpURLConnection connection = new OkUrlFactory(client).open(url);
    connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
    return connection;
}
Example 99
Project: training-onb-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
    }
}
Example 100
Project: twiterra-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
    javax.net.ssl.SSLSocketFactory sslFact = getSSLSocketFactoryDefaultOrConfigured(mysqlIO);
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx);
    }
}
Example 101
Project: uc_pircbotx-master  File: IRCFactory.java View source code
/**
	 * Map our configuration file onto PIrcBotX's config builder
	 *
<<<<<<< HEAD
	 * @param cb PircBotX config builder
	 * @param config our configuration instance
=======
	 * @param config our configuration instance
	 * @param processor the processor to bind to
>>>>>>> master
	 */
public static Configuration.Builder<PircBotX> doConfig(LocalConfiguration config, CommandProcessor processor) {
    Configuration.Builder<PircBotX> cb = new Configuration.Builder<PircBotX>();
    cb.addListener(new CommandListener(processor, config.trigger));
    //build the bot
    cb.setName(config.nick);
    cb.setServer(config.host, config.port);
    if (config.sasl) {
        cb.setCapEnabled(true);
        cb.addCapHandler(new SASLCapHandler(config.username, config.password));
    }
    if (config.ssl) {
        cb.setSocketFactory(SSLSocketFactory.getDefault());
    }
    // setup automatic channel joins
    for (String channel : config.channels) {
        cb.addAutoJoinChannel(channel);
    }
    //Useful stuff to keep the bot running
    cb.setAutoNickChange(true);
    cb.setAutoReconnect(true);
    return cb;
}