Java - Trying to log into website with invalid ssl certificate using httpclient
Posted
by PCBEEF
on Stack Overflow
See other posts from Stack Overflow
or by PCBEEF
Published on 2010-03-17T05:58:20Z
Indexed on
2010/03/17
6:01 UTC
Read the original article
Hit count: 699
I'm trying to log into site with invalid ssl certificate and I have the following code.
I bypass the the invalid cert by using my all certificate and then bypass the invalid Hostname by using hostnameverifier.
However, the hostnameverifier does not seem to work and I still get the error message
javax.net.ssl.SSLException: hostname in certificate didn't match:
The code is:
public static void main(String[] args) {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { }
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { }
}
};
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost());
return true;
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception e) {
}
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "user"));
formparams.add(new BasicNameValuePair("password", "pword"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("https://www.mysite.com/");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost, localContext);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
© Stack Overflow or respective owner