Skip to content

Instantly share code, notes, and snippets.

@skanga
Created December 21, 2018 18:25
Show Gist options
  • Save skanga/b6cdc5a03993ac27cb2870df7565f235 to your computer and use it in GitHub Desktop.
Save skanga/b6cdc5a03993ac27cb2870df7565f235 to your computer and use it in GitHub Desktop.
Fetch an HTTPS URL with NO verification and BLINDLY trusting all hosts
// NOTE: It is IRRESPONSIBLE to use this in any production type environment or with even remotely valuable data
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.security.SecureRandom;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URL;
public class HttpsNoVerify
{
public static void main (String... args) throws Exception
{
// System.setProperty ("https.proxySet", "true");
// System.setProperty ("https.proxyHost", "my-proxy");
// System.setProperty ("https.proxyPort","80");
URL url = new URL (args[0]);
TrustManager[] trustAllCerts = new TrustManager[]
{
new X509TrustManager ()
{
public X509Certificate[] getAcceptedIssuers () {return null;}
public void checkClientTrusted (X509Certificate[] certs, String authType) {}
public void checkServerTrusted (X509Certificate[] certs, String authType) {}
}
};
SSLContext sc = SSLContext.getInstance ("SSL");
sc.init (null, trustAllCerts, new SecureRandom ());
HttpsURLConnection.setDefaultSSLSocketFactory (sc.getSocketFactory ());
copyStream (url.openStream (), System.out);
}
/**
* Copy the contents of the input stream to the output stream until EOF or exception.
*
* @param inStream the input stream to read from
* @param outStream the output stream to write to
* @throws IOException if something went wrong in the copy process
*/
public static void copyStream (InputStream inStream, OutputStream outStream) throws IOException
{
final int BLOCK_SIZE = 4 * 1024;
byte byteBuffer[] = new byte[BLOCK_SIZE];
int bytesRead;
while ((bytesRead = inStream.read (byteBuffer)) != -1)
{
outStream.write (byteBuffer, 0, bytesRead);
}
}
/**
* Read bytes from inputStream and return them as a byte array
*/
public static byte[] readStreamToByteArray (InputStream inStream) throws IOException
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
int numRead = inStream.read ();
while (numRead != -1)
{
outStream.write (numRead);
numRead = inStream.read ();
}
return outStream.toByteArray ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment