Making an HTTPS request and opening an SSL socket in JAVA

I am trying to create a login page. To do this, I want to open an SSL socket and execute an HTTPS request, but I'm m getting Unknown Host Exception in line-- SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443); Could someone please tell me what I m getting Unknown Host Exception in line-- SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443); Could someone please tell me what I m doing wrong? In addition, I turned off host verification because it is not needed in my program.

 `public void clickLogin() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { URL url = new URL ("https://31.21.18.222/room_info/x.txt"); HttpsURLConnection connection = null; KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); //Make an empty store InputStream fis = new FileInputStream("C:/Documents and Settings/user/Desktop/PK/localhost.crt"); BufferedInputStream bis = new BufferedInputStream(fis); CertificateFactory cf = CertificateFactory.getInstance("X.509"); while (bis.available() > 0) { java.security.cert.Certificate cert = cf.generateCertificate(bis); keyStore.setCertificateEntry("localhost", cert); } // write code for turning off client verification TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(keyStore); SSLContext context = SSLContext.getInstance("SSL"); context.init(null, tmf.getTrustManagers() , null); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); SSLSocketFactory sslsf = context.getSocketFactory(); SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443); skt.setUseClientMode(true); SSLSession s = skt.getSession(); // handshake implicitly done skt.setKeepAlive(true); connection = (HttpsURLConnection) url.openConnection(); // Host name verification off connection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); ` 
+4
source share
1 answer

If you want to open a socket with createSocket , you need to use the host name (or IP address), and not the full URL:

 example : sslsf.createSocket("31.21.18.222" , 443); 

Besides:

  • Do not use Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()) (it is there by default).
  • It is probably better to use TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) instead of X.509 , especially because the default algorithm for TMF is PKIX , not X.509 .
  • createSocket will verify the certificate on a trust binding, but will not verify the host name (which is also necessary to prevent MITM attacks). For this, it is usually better to use the host name instead of the IP address.
+2
source

Source: https://habr.com/ru/post/1488242/


All Articles