import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSL {
public static class SimpleAuthenticator extends Authenticator {
private final String username, password;
public SimpleAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
public static void main(String[] args) throws IOException,
NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// don't throw exception
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// don't throw exception
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager },
new java.security.SecureRandom());
HostnameVerifier hostNameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
java.net.URL url = new URL("https://hostname/stuff");
Authenticator.setDefault(new SimpleAuthenticator("username", "password"));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setHostnameVerifier(hostNameVerifier);
con.setSSLSocketFactory(sc.getSocketFactory());
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
isr.close();
is.close();
}
}
Tuesday, December 18, 2007
Simple authentication over https with invalid certificate
Here's the story for opening an input stream on a url via https when the site has an invalid certificate (e.g. expired). You could place the certificate in your trusted store but this is a useful shortcut!
Subscribe to:
Posts (Atom)