Skip to content

Instantly share code, notes, and snippets.

@caseydunham
Created June 7, 2016 20:17
Show Gist options
  • Save caseydunham/df0a4b10bce13149ea0d784ce154e38b to your computer and use it in GitHub Desktop.
Save caseydunham/df0a4b10bce13149ea0d784ce154e38b to your computer and use it in GitHub Desktop.
Example of setting the SSLSocket Endpoint Identification Algorithm to Prevent MiTM Attacks
import javax.net.ssl.*;
import java.io.InputStream;
import java.io.PrintWriter;
public class SSLTest {
public static void main(String[] args) throws Exception {
// Just create standard SSLSocket to an HTTPS enabled website
SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket)sslsocketfactory.createSocket("www.wikipedia.org", 443);
// Configure SSLParameters for Hostname verification
SSLParameters sslParams = new SSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
sslSocket.setSSLParameters(sslParams);
// Simple GET Request to create the connection
// This SHOULD fail if someone is intercepting traffic
PrintWriter out = new PrintWriter(sslSocket.getOutputStream());
out.write("GET / HTTP/1.1\n" +
"User-Agent: Java/1.8.0_45\n" +
"Host: www.wikipedia.org:443\n" +
"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\n" +
"Connection: close\n\n");
out.flush();
// Just read some data from the response
InputStream in = sslSocket.getInputStream();
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
System.out.write(buffer, 0, len);
len = in.read(buffer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment