Java Code Examples for javax.net.ssl.SSLSocketFactory.getDefault()

The following are Jave code examples for showing how to use getDefault() of the javax.net.ssl.SSLSocketFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: OASP   File: OASPVerify.java   View Source Code Vote up 6 votes
@Override
protected Boolean doInBackground(Void... params) {
    try {
        // TODO: support self-defined ports instead of 443 only
        SocketFactory factory = SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) factory.createSocket();
        socket.connect(new InetSocketAddress(oasp_url.substring(8), 443), CON_TIMEOUT);
        socket.startHandshake();
        Certificate[] certs = socket.getSession().getPeerCertificates();
        socket.close();
        if (certs == null)
            return false;

        for (Certificate cert : certs) {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA256");
            messageDigest.update(cert.getEncoded());
            oasp_url_certs.add(convertToHex(messageDigest.digest()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
 
Example 2
Project: JRediClients   File: SSLJedisTest.java   View Source Code Vote up 6 votes
/**
 * Tests opening an SSL/TLS connection to redis with a custom hostname
 * verifier.
 */
@Test
public void connectWithShardInfoAndCustomHostnameVerifier() {
  final URI uri = URI.create("rediss://localhost:6390");
  final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  final SSLParameters sslParameters = new SSLParameters();

  HostnameVerifier hostnameVerifier = new BasicHostnameVerifier();
  JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, hostnameVerifier);
  shardInfo.setPassword("foobared");

  Jedis jedis = new Jedis(shardInfo);
  jedis.get("foo");
  jedis.disconnect();
  jedis.close();
}
 
Example 3
Project: hotelApp   File: TouristAttractionFinder.java   View Source Code Vote up 6 votes
/**
 * Creates a secure socket to communicate with Google's API.
 *
 * @param path
 * @return String - html response from Google's API
 * @throws IOException
 */
private static String getHtmlResponse(String path) throws IOException {
    // connect with host
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = (SSLSocket) factory.createSocket(HOST, PORT);

    // send a request to the server through output stream
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
    String requestString = getRequest(HOST, path);
    pw.println(requestString);

    // use input stream to read server's response
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    StringBuilder sb = new StringBuilder();

    String str;
    while ((str = in.readLine()) != null) {
        sb.append(str).append(" ");
    }

    // take the body part
    return sb.toString();
}
 
Example 4
Project: dev-courses   File: HsqlSocketFactorySecure.java   View Source Code Vote up 6 votes
/**
 * Retrieves the underlying javax.net.ssl.SSLSocketFactory.
 *
 * @throws Exception if there is a problem retrieving the
 *      underlying factory
 * @return the underlying javax.net.ssl.SSLSocketFactory
 */
protected SSLSocketFactory getSocketFactoryImpl() throws Exception {

    Object factory;

    synchronized (socket_factory_mutex) {
        factory = socketFactory;

        if (factory == null) {
            factory       = SSLSocketFactory.getDefault();
            socketFactory = factory;
        }
    }

    return (SSLSocketFactory) factory;
}
 
Example 5
Project: parabuild-ci   File: HsqlSocketFactorySecure.java   View Source Code Vote up 6 votes
/**
 * Retrieves the underlying javax.net.ssl.SSLSocketFactory.
 *
 * @throws Exception if there is a problem retrieving the
 *      underlying factory
 * @return the underlying javax.net.ssl.SSLSocketFactory
 */
protected SSLSocketFactory getSocketFactoryImpl() throws Exception {

    Object factory;

    synchronized (socket_factory_mutex) {
        factory = socketFactory;

        if (factory == null) {
            factory       = SSLSocketFactory.getDefault();
            socketFactory = factory;
        }
    }

    return (SSLSocketFactory) factory;
}
 
Example 6
Project: parabuild-ci   File: HsqlSocketFactorySecure.java   View Source Code Vote up 6 votes
/**
 * Retrieves the underlying javax.net.ssl.SSLSocketFactory.
 *
 * @throws Exception if there is a problem retrieving the
 *      underlying factory
 * @return the underlying javax.net.ssl.SSLSocketFactory
 */
protected SSLSocketFactory getSocketFactoryImpl() throws Exception {

    Object factory;

    synchronized (socket_factory_mutex) {
        factory = socketFactory;

        if (factory == null) {
            factory       = SSLSocketFactory.getDefault();
            socketFactory = factory;
        }
    }

    return (SSLSocketFactory) factory;
}
 
Example 7
Project: parabuild-ci   File: HsqlSocketFactorySecure.java   View Source Code Vote up 6 votes
/**
 * Retrieves the underlying javax.net.ssl.SSLSocketFactory.
 *
 * @throws Exception if there is a problem retrieving the
 *      underlying factory
 * @return the underlying javax.net.ssl.SSLSocketFactory
 */
protected SSLSocketFactory getSocketFactoryImpl() throws Exception {

    Object factory;

    synchronized (socket_factory_mutex) {
        factory = socketFactory;

        if (factory == null) {
            factory       = SSLSocketFactory.getDefault();
            socketFactory = factory;
        }
    }

    return (SSLSocketFactory) factory;
}
 
Example 8
Project: RLibrary   File: SocketFactorySettings.java   View Source Code Vote up 6 votes
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 9
Project: jdk8u-jdk   File: Fix5070632.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 10
Project: openjdk-jdk10   File: Fix5070632.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 11
Project: pcloud-networking-java   File: PCloudAPIClient.java   View Source Code Vote up 5 votes
private PCloudAPIClient(Builder builder) {
    this.connectTimeoutMs = builder.connectTimeoutMs;
    this.writeTimeoutMs = builder.writeTimeoutMs;
    this.readTimeoutMs = builder.readTimeoutMs;

    this.socketFactory = builder.socketFactory != null ? builder.socketFactory : SocketFactory.getDefault();

    this.sslSocketFactory = builder.sslSocketFactory != null ?
                    builder.sslSocketFactory : (SSLSocketFactory) SSLSocketFactory.getDefault();

    this.hostnameVerifier = builder.hostnameVerifier != null ?
                    builder.hostnameVerifier : DefaultHostnameVerifier.INSTANCE;

    this.connectionPool = builder.connectionPool != null ? builder.connectionPool : new ConnectionPool();
    this.endpointProvider = builder.endpointProvider != null ? builder.endpointProvider : EndpointProvider.DEFAULT;

    ConnectionFactory connectionFactory = new ConnectionFactory(socketFactory, sslSocketFactory, hostnameVerifier);
    this.connectionProvider = new ConnectionProvider(connectionPool, endpointProvider, connectionFactory,
            connectTimeoutMs, readTimeoutMs, writeTimeoutMs, false);

    ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "PCloud API Client");
        }
    };
    this.callExecutor = builder.callExecutor != null ?
            builder.callExecutor : new ThreadPoolExecutor(0,
            Integer.MAX_VALUE,
            DEFAULT_KEEP_ALIVE_TIME_MS,
            TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(),
            threadFactory);

    this.interceptors = Collections.unmodifiableList(new ArrayList<>(builder.interceptors));
}
 
Example 12
Project: dtp   File: DTPSecureConnector.java   View Source Code Vote up 5 votes
@Override
public DTunnel connect() throws IOException {
    SocketFactory ssf = SSLSocketFactory.getDefault(); 
    SSLSocket socket = (SSLSocket) ssf.createSocket(this.getHost(), DTP_PORT);
    socket.startHandshake();
    return this.connect(socket);
}
 
Example 13
Project: lib-commons-httpclient   File: StrictSSLProtocolSocketFactory.java   View Source Code Vote up 5 votes
/**
 * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
 */
public Socket createSocket(Socket socket, String host, int port, 
                           boolean autoClose)
    throws IOException, UnknownHostException {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, 
                                                      port, autoClose);
    verifyHostname(sslSocket);

    return sslSocket;
}
 
Example 14
Project: file-transfer   File: FileTransmission.java   View Source Code Vote up 5 votes
/**
 * Helper for file transmission operations
 * @param path - Path of the file to be sent/received
 */
public FileTransmission (String path) {
    if (path.isEmpty()) {
        throw new IllegalArgumentException("Empty file path");
    }
    this.file = new File(path);
    canceled = false;
    try {
        SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        sslSocket = (SSLSocket) sslSocketFactory.createSocket(SERVER_IP, SERVER_PORT);
    } catch (IOException ex) {
        if (!canceled) throw new UnreachableHostException("Unreachable Host.");
    }
}
 
Example 15
Project: jdk8u-jdk   File: CipherTestUtils.java   View Source Code Vote up 5 votes
private CipherTestUtils()
        throws IOException, FileNotFoundException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeySpecException {
    factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    KeyStore serverKeyStore = createServerKeyStore(SERVER_PUBLIC_KEY,
            SERVER_PRIVATE_KEY);
    KeyStore serverTrustStore = createServerKeyStore(CA_PUBLIC_KEY,
            CA_PRIVATE_KEY);

    if (serverKeyStore != null) {
        KeyManagerFactory keyFactory1
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory1.init(serverKeyStore, PASSWORD);
        serverKeyManager = (X509ExtendedKeyManager) keyFactory1.
                getKeyManagers()[0];
    } else {
        serverKeyManager = null;
    }
    serverTrustManager = serverTrustStore != null
            ? new AlwaysTrustManager(serverTrustStore) : null;

    KeyStore clientKeyStore, clientTrustStore;
    clientTrustStore = serverTrustStore;
    clientKeyStore =
            createServerKeyStore(CLIENT_PUBLIC_KEY,CLIENT_PRIVATE_KEY);
    if (clientKeyStore != null) {
        KeyManagerFactory keyFactory
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(clientKeyStore, PASSWORD);
        clientKeyManager = (X509ExtendedKeyManager) keyFactory.
                getKeyManagers()[0];
    } else {
        clientKeyManager = null;
    }
    clientTrustManager = (clientTrustStore != null)
            ? new AlwaysTrustManager(clientTrustStore) : null;
}
 
Example 16
Project: LightSIP   File: DefaultNetworkLayer.java   View Source Code Vote up 4 votes
private DefaultNetworkLayer() {
    sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory
            .getDefault();
    sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
}
 
Example 17
Project: openjdk-jdk10   File: SslRMIClientSocketFactory.java   View Source Code Vote up 4 votes
private static synchronized SocketFactory getDefaultClientSocketFactory() {
    if (defaultSocketFactory == null)
        defaultSocketFactory = SSLSocketFactory.getDefault();
    return defaultSocketFactory;
}
 
Example 18
Project: openjdk-jdk10   File: ExportableStreamCipher.java   View Source Code Vote up 4 votes
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a exportable stream cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"SSL_RSA_EXPORT_WITH_RC4_40_MD5"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        boolean interrupted = false;
        try {
            sslOS.write('B');
            sslOS.flush();
            sslIS.read();
        } catch (SSLException ssle) {
            // get the expected exception
            interrupted = true;
        } finally {
            sslSocket.close();
        }

        if (!interrupted) {
            throw new SSLHandshakeException(
                "A weak cipher suite is negotiated, " +
                "TLSv1.1 must not negotiate the exportable cipher suites.");
        }
    }
 
Example 19
Project: openjdk-jdk10   File: SSLSessionFinalizeTest.java   View Source Code Vote up 4 votes
SBListener doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();

        try {
                SSLSocket sslSocket = (SSLSocket)
                    sslsf.createSocket("localhost", serverPort);
                InputStream sslIS = sslSocket.getInputStream();
                OutputStream sslOS = sslSocket.getOutputStream();

            sslOS.write(280);
            sslOS.flush();
            sslIS.read();

            sslOS.close();
            sslIS.close();

            SSLSession sslSession = sslSocket.getSession();
            System.out.printf(" sslSession: %s %n   %s%n", sslSession, sslSession.getClass());
            SBListener sbListener = new SBListener(sslSession);

            sslSession.putValue("x", sbListener);

            sslSession.invalidate();

            sslSocket.close();

            sslOS = null;
            sslIS = null;
            sslSession = null;
            sslSocket = null;
            Reference.reachabilityFence(sslOS);
            Reference.reachabilityFence(sslIS);
            Reference.reachabilityFence(sslSession);
            Reference.reachabilityFence(sslSocket);

            return sbListener;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
 
Example 20
Project: hotelApp   File: Expedia.java   View Source Code Vote up 4 votes
/**
 * Creates a secure socket to communicate with Expedia.
 *
 * @return String - html response from Expedia
 */
private String getHtmlResponse(String path) {

    try {
        // connect with host -Expedia
        SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        Socket socket = factory.createSocket(HOST, PORT);

        // send a request to the server through output stream
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
        String requestString = getRequest(path);
        pw.println(requestString);

        // use input stream to read server's response
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        StringBuilder sb = new StringBuilder();

        String str;
        while ((str = in.readLine()) != null) {
            sb.append(str);
        }

        if (sb.toString().startsWith("HTTP/1.1 301 Moved")) {
            Pattern p = Pattern.compile(".*?https://www.expedia.com([^\\s:]*):\\s");
            Matcher m = p.matcher(sb.toString());
            if (m.find()) {
                String newPath = m.group(1).replaceAll("Server", "");
                return getHtmlResponse(newPath);
            }
            else {
                return "";
            }
        }
        else if (sb.toString().startsWith("HTTP/1.1 404 Not Found")) {
            return "";
        }

        // take the body part
        return sb.substring(sb.indexOf("<body"));
    }
    catch (IOException e) {
        System.out.println(e);
    }

    return "";
}