Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

HOW TO : by pass a server certificate with HTTPConnection / Proxy

  Asked By: Marty    Date: Dec 18    Category: Java    Views: 1925
  

I'm a true beginner with Java and I was wondering if someone could
give a hand?

WHAT I WANT TO DO :
- connect to a remote HTTPS site.
- autenticate (with IE, that is a popup login window, not some html
form).
- post datas (that is outputstrzeam post AND/OR regular html get/post)
- read inputstream

WHAT I DID TEST :
+--------+-------+-----------+----------+-----------------...
|site | Prot. | via Proxy | WWW Auth | Read InputStream?
+--------+-------+-----------+----------+-----------------...
|My PC | HTTP | -- | yes | yes (http 403, SSL
requiered)
|My PC | HTTPS | -- | yes | yes (http 200)
| | | | |
+--------+-------+-----------+----------+-----------------...
|Verisign| HTTP | y + auten| -- | yes (http 200)
|Verisign| HTTPS | y + auten| -- | javax.net.ssl.SSLException:
Received fatal alert:
| | | | | handshake_failure (no
cipher suites in common)
+--------+-------+-----------+----------+-----------------...
|Thawte | HTTP | y + auten| -- | yes (http 200)
|Thawte | HTTPS | y + auten| -- | javax.net.ssl.SSLException:
Received fatal alert:
| | | | | handshake_failure (no
cipher suites in common)
+--------+-------+-----------+----------+-----------------...

notas :
. my cacerts contains all Verign and Thawte Root CA's
. all certs have been added without "-keyalg RSA", then with "-keyalg
RSA"


From the above chart you can see I'm not able to connect to HTTPS,
even without WWW-autentication.

WHAT I'D LIKE TO DO :
1/ - be abble, to connect to HTTPS remote site, through my PROXY,
then AUTENTICATE to remote site ?
2/ - I saw some coding with SSLSocket, would it be easier ?
3/ - How to choose between regular "GET"/"POST" html method and the
outputstream "POST" method ?
I could figure out what I should change in my code...

My code is here below along with a properties files that is used by
the class,

/**********************START
HttpsConnexionTester.java****************************/

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.Security;
import java.util.Properties;

import sun.net.www.protocol.http.HttpURLConnection;

public class HttpsConnexionTester {

private final String propertiesFilesPath
= "c:/HttpsConnexionTester.properties";
private String urlhttp;
private String proxyHost;
private String proxyPort;
private String proxyUser;
private String proxyPwd;
private String wwwAuthUser;
private String wwwAuthPwd;
private String wwwAuthRealm;
private String httpsKeystorePath;
private String httpsKeystorePwd;
private String httpsCacertPath;
private String httpsCacertPwd;
private String sendMethod;
private String sendDatas;


public static void main(String args[]) {
HttpsConnexionTester thc = new HttpsConnexionTester();
System.out.println("============================");
System.out.println("Test result = ");
System.out.println(thc.testConnection());
}

public boolean testConnection() {
boolean testHasPassed = true;
java.net.URL url = null;
HttpURLConnection conn = null;
String serverStatus = "";
//debugger("testConnection() : entering...",false);
System.out.println( "urlhttp = " +
(this.urlhttp = getPropertyFromFile
(propertiesFilesPath,"urlhttp") ) );
System.out.println( "proxyHost = " +
(this.proxyHost = getPropertyFromFile
(propertiesFilesPath,"proxyHost") ) );
System.out.println( "proxyPort = " +
(this.proxyPort = getPropertyFromFile
(propertiesFilesPath,"proxyPort") ) );
System.out.println( "proxyUser = " +
(this.proxyUser = getPropertyFromFile
(propertiesFilesPath,"proxyUser") ) );
System.out.println( "proxyPwd = " +
(this.proxyPwd = getPropertyFromFile
(propertiesFilesPath,"proxyPwd") ) );
System.out.println( "wwwAuthUser = " +
(this.wwwAuthUser = getPropertyFromFile
(propertiesFilesPath,"wwwAuthUser") ) );
System.out.println( "wwwAuthPwd = " +
(this.wwwAuthPwd = getPropertyFromFile
(propertiesFilesPath,"wwwAuthPwd") ) );
System.out.println( "wwwAuthRealm = " +
(this.wwwAuthRealm = getPropertyFromFile
(propertiesFilesPath,"wwwAuthRealm") ) );
System.out.println( "httpsKeystorePath = " +
(this.httpsKeystorePath = getPropertyFromFile
(propertiesFilesPath,"httpsKeystorePath") ) );
System.out.println( "httpsKeystorePwd = " +
(this.httpsKeystorePwd = getPropertyFromFile
(propertiesFilesPath,"httpsKeystorePwd") ) );
System.out.println( "httpsCacertPath = " +
(this.httpsCacertPath = getPropertyFromFile
(propertiesFilesPath,"httpsCacertPath") ) );
System.out.println( "httpsCacertPwd = " +
(this.httpsCacertPwd = getPropertyFromFile
(propertiesFilesPath,"httpsCacertPwd") ) );
System.out.println( "sendMethod = " +
(this.sendMethod = getPropertyFromFile
(propertiesFilesPath,"sendMethod") ) );
System.out.println( "sendDatas = " +
(this.sendDatas = getPropertyFromFile
(propertiesFilesPath,"sendDatas") ) );
System.out.println( "---------------------------------
-----------------");
try {
System.out.println("testConnection() : " + urlhttp);
//creation de l'objet URL
url = new java.net.URL(urlhttp);

if( url.getProtocol().equalsIgnoreCase
("https")){
System.out.println("testConnection
() : connection HTTPS détected");
System.out.println("testConnection() : SSL :
addind SLL support");
Security.addProvider(new
com.sun.net.ssl.internal.ssl.Provider());

System.out.println("testConnection() : Declaring
security packages");
System.setProperty
("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"
);

if (httpsCacertPath != "" && httpsCacertPwd != "") {
System.out.println("testConnection() :
CACERT : validating site Root Certificate Authorities");
System.setProperty("javax.net.ssl.trustStore",
httpsCacertPath);
System.setProperty
("javax.net.ssl.trustStorePassword", httpsCacertPwd);
}


if (httpsKeystorePath != "" && httpsKeystorePwd !
= "") {
System.out.println("testConnection() :
KEYSTORE : validating site certificate");
System.setProperty("keyStore", httpsKeystorePath);
System.setProperty
("javax.net.ssl.keyStorePassword", httpsKeystorePwd);
}
}



if (proxyHost != "" && proxyPort != "") {
System.out.println("testConnection() : PROXY :
server " + proxyHost + ":" + proxyPort);
System.setProperty("proxySet", "true");
System.setProperty("proxyHost",
proxyHost);
System.setProperty("proxyPort",
proxyPort);
System.setProperty
("http.proxySet", "true");
System.setProperty("http.proxyHost",
proxyHost);
System.setProperty("http.proxyPort",
proxyPort );
System.setProperty
("https.proxySet", "true");
System.setProperty("https.proxyHost",
proxyHost);
System.setProperty("https.proxyPort",
proxyPort );
}


System.out.println("testConnection() : CONNEXION :
opening");
conn = (HttpURLConnection) url.openConnection();
System.out.println("testConnection() :
CONNEXION : Using proxy = " + conn.usingProxy());


if (proxyUser != "" && proxyPwd != "") {
System.out.println("testConnection() : PROXY :
autentication " + proxyUser + "/" + proxyPwd);
// (doit se faire après l'ouverture de la connection)
String password = proxyUser + ":" + proxyPwd;
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
String encodedPassword = enc.encode((password).getBytes
());
conn.setRequestProperty("Proxy-Authorization",
encodedPassword);
}


if (wwwAuthUser != "" && wwwAuthPwd != "") {
System.out.println("testConnection
() : WWW-AUTH : activting " + wwwAuthUser + "/" + wwwAuthPwd);
// (doit se faire après l'envoi de la
requete)
String authCredentials = wwwAuthUser
+ ":" + wwwAuthPwd;
String authEncoded = "Basic " + new
sun.misc.BASE64Encoder().encode(authCredentials.getBytes());
//conn.setRequestProperty("Content-
Type", "text/xml");
conn.setRequestProperty
("Authorization", authEncoded);
}


System.out.println("testConnection() : CONNEXION :
method " + sendMethod + " ; datas '" + sendDatas + "'");
conn.setRequestMethod(sendMethod);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty(
"user-agent",
"HttpsConnexionTester ["
+ this.getClass().getName()
+ ";"
+ System.getProperty
("os.name")
+ ";"
+ System.getProperty
("os.version")
+ ";"
+ System.getProperty
("java.version")
+ ";"
+ "]");


if(sendDatas!=""){
System.out.println("testConnection
() : --- SENDING OUTPUT STREAM ---");
try {
String content = sendDatas;

// creation du flux de sortie
java.io.DataOutputStream sortie =
new java.io.DataOutputStream(conn.getOutputStream());

System.out.println("testConnection
() : envoi de l'OutputStream...");
sortie.writeBytes(content);
sortie.flush();

sortie.close();
System.out.println
("testConnection() : ...OutputStream sent");
}
catch (Exception e) {
System.out.println
("testConnection() : Error while sending OutputStream");
e.printStackTrace();
}
System.out.println("testConnection
() : /--- SENDING OUTPUT STREAM ---");
}


System.out.println("testConnection() : ---
READING INPUT STREAM ---");
try {
System.out.println("testConnection() : reading
InputStream ...");
String inputStreamRead = "";
inputStreamRead = readFromInputstream
(conn.getInputStream(),1000);
System.out.println("testConnection
() : ...InputStream read");
System.out.println("testConnection
() : ...InputStream string built");
System.out.println("testConnection() : received
message from remote host :");
System.out.println("================");
System.out.println(inputStreamRead.trim());
System.out.println("================");
}
catch (Exception e) {
System.err.println("testConnection() : Error reading
InputStream...");
e.printStackTrace();
}
System.out.println("testConnection() : /---
READING INPUT STREAM ---");


System.out.println("testConnection() : ---
connection informations ---");
System.out.println("testConnection() :
conn : " + conn);
System.out.println("testConnection() :
conn.getResponseCode() : " + serverStatus);
System.out.println("testConnection() :
conn.getResponseMessage() : " + conn.getResponseMessage());
System.out.println("testConnection() :
conn.userAgent() : " + HttpURLConnection.userAgent);
System.out.println("testConnection() :
conn.usingProxy() : " + conn.usingProxy());
System.out.println("testConnection() :
conn.getRequestMethod() : " + conn.getRequestMethod());
System.out.println("testConnection() :
conn.getPermission() : " + conn.getPermission());
System.out.println("testConnection() :
url.getProtocol : " + url.getProtocol());
System.out.println("testConnection() :
url.getPort : " + url.getPort());
System.out.println("testConnection() : /---
connection informations ---");


}
catch (java.net.MalformedURLException e) {
System.err.println("testConnection() : ERROR : url
malformed");
testHasPassed = false;
e.printStackTrace();
}
catch (Exception e) {
System.err.println("testConnection() : ERROR : other
errors");
testHasPassed = false;
e.printStackTrace();
}
finally {
System.out.println("testConnection() : disconnecting");
conn.disconnect();
}
return testHasPassed;
}

public class SimpleAuthenticator extends Authenticator {
private String username;
private String password;

public SimpleAuthenticator(String username, String
password) {
this.username = username;
this.password = password;
}

protected PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(username,
password.toCharArray());
}
}





public String readFromInputstream(InputStream is, int
nbLignesALire)
{
String thisLine;
String result = "";
System.out.println("Reading inputStream");
try
{
BufferedReader in1 = new BufferedReader(new
InputStreamReader(is));
String line;
String lineBuff="";
for (int i = 1; (i < nbLignesALire) ; i++)
{
if((lineBuff=in1.readLine())!=null)
result += "\n" + (lineBuff
+ "").trim();
}
}
catch (java.io.IOException e)
{
System.out.println(e);
}
System.out.println("Read " + result.length()
+ "octets from inputStream");
return result;
}

private static String getPropertyFromFile(String
pathToPropertyFile,String propertyName)
{
String propertyValue = "";
// Property file read to get the path where the invoice
files are to be saved -> invoicePathSauv
Properties defaultProps = new Properties();
try {
java.io.FileInputStream in = new
java.io.FileInputStream(pathToPropertyFile);
defaultProps.load(in);
in.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
propertyValue = defaultProps.getProperty(propertyName);
if( propertyValue==null || propertyValue.equals("null") )
propertyValue="";
return propertyValue;
}
}
/**********************END
HttpsConnexionTester.java****************************/



/**********************START HttpsConnexionTester.properties (plain
text file)****************************/
======================= URL ===========================
urlhttp=https://www.thawte.com

====================== PROXY ==========================
proxyHost=192.168.100.200
proxyPort=888
# proxyUser=myProxyUser
# proxyPwd=myProxyPwd

==================== WWW-AUTH =========================
# wwwAuthUser=wwwUser
# wwwAuthPwd=wwwPwd
# wwwAuthRealm=wwwRealm

==================== KEYSTRORES ========================
# httpsKeystorePath=C:\\my-pc.keystore
# httpsKeystorePwd=123abc

====================== CACERTS =========================
httpsCacertPath=C:\\tom32\\certificats\\cacerts
httpsCacertPwd=changeit

======================= HTTP ===========================
sendMethod=GET
# sendDatas=GET default.htm

/**********************END HttpsConnexionTester.properties (plain
text file)****************************/

Share: 

 

No Answers Found. Be the First, To Post Answer.

 




Tagged: