HttpsURLConnection

Problems with WiFi, SQLite ,Bluetooth, WiMax, Proxies, etc...

HttpsURLConnection

Postby darolla » Wed Apr 15, 2009 7:21 am

Hi,

I need to open a HttpsURLConnection with my own certificate. I've
found this for Java (not Android) on http://forums.sun.com/thread.jspa?threa ... ID=1886339

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.         public static String readFromURL( String httpsUrl, String login, String password ) throws NoSuchAlgorithmException,  KeyManagementException, MalformedURLException, UnknownHostException, IOException {
  3.  
  4.                
  5.  
  6.                 // Variabeln
  7.  
  8.                 TrustManager[]          trustAllCerts;
  9.  
  10.                 SSLContext                      sc;
  11.  
  12.                 URL                                     url;
  13.  
  14.                 HttpsURLConnection      connection;
  15.  
  16.                 String                          s;
  17.  
  18.                 String                          base64;
  19.  
  20.                 BufferedReader          reader;
  21.  
  22.                 StringBuffer            str;
  23.  
  24.                 String                          line;
  25.  
  26.                                                
  27.  
  28.                
  29.  
  30.                 trustAllCerts = new TrustManager[] { new X509TrustManagerImpl() };             
  31.  
  32.  
  33.  
  34.                 // Let us create the factory where we can set some parameters for the connection
  35.  
  36.                 sc = SSLContext.getInstance( "SSL" );
  37.  
  38.                 sc.init( null, trustAllCerts, new SecureRandom() );
  39.  
  40.  
  41.  
  42.                 // Create the socket connection and open it to the secure remote web server
  43.  
  44.                 url = new URL( httpsUrl );
  45.  
  46.                 HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory() );
  47.  
  48.                 connection = (HttpsURLConnection)url.openConnection();
  49.  
  50.  
  51.  
  52.                 // Once the connection is open to the remote server we have to replace the default HostnameVerifier
  53.  
  54.                 // with one of our own since we want the client to bypass the peer and submitted host checks even
  55.  
  56.                 // if they are not equal. If this routine were not here, then this client would claim that the submitted
  57.  
  58.                 // host and the peer host are not equal.
  59.  
  60.                 connection.setHostnameVerifier( new HostnameVerifierImpl() );
  61.  
  62.                
  63.  
  64.                 // Make this URL connection available for input and output
  65.  
  66.                 connection.setDoOutput( true );
  67.  
  68.                
  69.  
  70.                 // Login
  71.  
  72.             s      = login + ":" + password;
  73.  
  74.             base64 = "Basic " + new BASE64Encoder().encode( s.getBytes() );                    
  75.  
  76.             connection.setRequestProperty( "Authorization", base64 );
  77.  
  78.             connection.connect();
  79.  
  80.  
  81.  
  82.             // vom Stream lesen und als String zurückgeben
  83.  
  84.         reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
  85.  
  86.         str    = new StringBuffer();
  87.  
  88.  
  89.  
  90.         while( (line = reader.readLine()) != null ) {
  91.  
  92.                 str.append( line + "\n" );
  93.  
  94.         }
  95.  
  96.        
  97.  
  98.         return( str.toString() );          
  99.  
  100.         }
  101.  
  102.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class X509TrustManagerImpl implements X509TrustManager {
  3.  
  4.  
  5.  
  6.         // Log4J
  7.  
  8.         private static Logger logger = Logger.getLogger( X509TrustManagerImpl.class );
  9.  
  10.  
  11.  
  12.        
  13.  
  14.         /**
  15.  
  16.          * Return an array of certificate authority certificates which are trusted
  17.  
  18.          * for authenticating peers.
  19.  
  20.          * @return <code>X509Certificate[]</code> - Return an array of certificate
  21.  
  22.          * authority certificates which are trusted for authenticating peers.
  23.  
  24.          */
  25.  
  26.         public X509Certificate[] getAcceptedIssuers() {
  27.  
  28.                 return( null );
  29.  
  30.         }
  31.  
  32.  
  33.  
  34.  
  35.  
  36.         /**
  37.  
  38.          * Given the partial or complete certificate chain provided by the peer,
  39.  
  40.          * build a certificate path to a trusted root and return if it can be
  41.  
  42.          * validated and is trusted for client SSL authentication based on the
  43.  
  44.          * authentication type. The authentication type is determined by the
  45.  
  46.          * actual certificate used. For instance, if RSAPublicKey is used, the
  47.  
  48.          * authType should be "RSA". Checking is case-sensitive.
  49.  
  50.          * @param chain <code>X509Certificate[]</code> the peer certificate chain
  51.  
  52.          * @param authType <code>String</code> the authentication type based on
  53.  
  54.          * the client certificate
  55.  
  56.          */
  57.  
  58.         public void checkClientTrusted( X509Certificate[] chain, String authType ) {           
  59.  
  60.         }
  61.  
  62.        
  63.  
  64.  
  65.  
  66.         /**
  67.  
  68.          * Given the partial or complete certificate chain provided by the peer,
  69.  
  70.          * build a certificate path to a trusted root and return if it can be
  71.  
  72.          * validated and is trusted for server SSL authentication based on the
  73.  
  74.          * authentication type. The authentication type is the key exchange
  75.  
  76.          * algorithm portion of the cipher suites represented as a String, such
  77.  
  78.          * as "RSA", "DHE_DSS". Note: for some exportable cipher suites, the key
  79.  
  80.          * exchange algorithm is determined at run time during the handshake. For
  81.  
  82.          * instance, for TLS_RSA_EXPORT_WITH_RC4_40_MD5, the authType should be
  83.  
  84.          * RSA_EXPORT when an ephemeral RSA key is used for the key exchange, and
  85.  
  86.          * RSA when the key from the server certificate is used. Checking is
  87.  
  88.          * case-sensitive.
  89.  
  90.          * @param chain <code>X509Certificate[]</code> the peer certificate chain
  91.  
  92.          * @param authType <code>String</code> the authentication type based on
  93.  
  94.          * the client certificate
  95.  
  96.          */
  97.  
  98.         public void checkServerTrusted( X509Certificate[] chain, String authType ) {           
  99.  
  100.         }
  101.  
  102. }
  103.  
  104.  
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class HostnameVerifierImpl implements HostnameVerifier {
  3.  
  4.  
  5.  
  6.         // Log4J
  7.  
  8.         private static Logger logger = Logger.getLogger( HostnameVerifierImpl.class );
  9.  
  10.  
  11.  
  12.         /**
  13.  
  14.          * Verify that the host name is an acceptable match with the server's authentication scheme.
  15.  
  16.          * @param hostname <code>String</code> the host name
  17.  
  18.          * @param session <code>SSLSession</code> SSLSession used on the connection to hos
  19.  
  20.          */
  21.  
  22.         public boolean verify( String hostname, SSLSession session ) {
  23.  
  24.                
  25.  
  26.                 if( ! hostname.equals( session.getPeerHost() ) ) {
  27.  
  28.                         logger.warn( "Das Zertifikat " + session.getPeerHost() + " passt nicht zum Host " + hostname );
  29.  
  30.                 }
  31.  
  32.                 return true;
  33.  
  34.         }      
  35.  
  36. }
  37.  
  38.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


the problem inside android is, that base64encoder isnt integrated.

i've found a working one inside the jar: http://www.winterwell.com/software/jtwitter.php

but its still not working. ssl seems not to be inside android :(

can you help me on this?

I can send the exception later...

greetings
darolla
User avatar
darolla
Master Developer
Master Developer
 
Posts: 273
Joined: Thu Sep 25, 2008 5:16 pm
Location: Dortmund, Germany

Top

Postby androidUser » Wed Apr 15, 2009 1:17 pm

Its very simple.

Try this,

String URL_UPDATE = "http://ipaddress:Port/axis2/services/StockQuoteService/update?symbol=demo&price="+inputPrice;

HttpUriRequest request = null;

DefaultHttpClient client = new DefaultHttpClient();

request = new HttpGet(URL_UPDATE);

try {

client.execute(request);

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
androidUser
Junior Developer
Junior Developer
 
Posts: 24
Joined: Sun Apr 05, 2009 1:08 pm

Postby darolla » Wed Apr 15, 2009 1:58 pm

well, thank you, but using the httpclient doesnt help me much. because I need input- and outputstreams to my servlet, and this only works with urlconnection. and beside this I need https over ssl.

greetings,
darolla
User avatar
darolla
Master Developer
Master Developer
 
Posts: 273
Joined: Thu Sep 25, 2008 5:16 pm
Location: Dortmund, Germany

Postby padde » Wed Apr 15, 2009 2:53 pm

First i have to say i have not tested this code.. its part of a huge app and i copy&pasted it from there..
i hope nothing is missing.. but i am quite sure that this will help.

First the connectionclient class
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.connection;
  3.  
  4.  
  5.  
  6. import java.security.KeyManagementException;
  7.  
  8. import java.security.KeyStoreException;
  9.  
  10. import java.security.NoSuchAlgorithmException;
  11.  
  12. import java.security.UnrecoverableKeyException;
  13.  
  14.  
  15.  
  16. import org.apache.http.auth.AuthScope;
  17.  
  18. import org.apache.http.auth.Credentials;
  19.  
  20. import org.apache.http.conn.scheme.Scheme;
  21.  
  22. import org.apache.http.impl.client.BasicCredentialsProvider;
  23.  
  24. import org.apache.http.impl.client.DefaultHttpClient;
  25.  
  26. import org.apache.http.params.HttpConnectionParams;
  27.  
  28.  
  29.  
  30.  
  31.  
  32. public class ConnectionClient extends DefaultHttpClient {
  33.  
  34.     public ConnectionClient(Credentials cred) {
  35.  
  36.         super();
  37.  
  38.         setCredentials(cred);
  39.  
  40.         HttpConnectionParams.setConnectionTimeout(this.getParams(), 15000);
  41.  
  42.     }
  43.  
  44.  
  45.  
  46.     public ConnectionClient(Credentials cred, int port) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
  47.  
  48.         super();
  49.  
  50.         registerTrustAllScheme(port);
  51.  
  52.         setCredentials(cred);
  53.  
  54.     }
  55.  
  56.  
  57.  
  58.     private void registerTrustAllScheme(int port) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
  59.  
  60.         TrustAllSSLSocketFactory tasslf = new TrustAllSSLSocketFactory();
  61.  
  62.         Scheme sch = new Scheme("https", tasslf, port);
  63.  
  64.         getConnectionManager().getSchemeRegistry().register(sch);      
  65.  
  66.     }
  67.  
  68.        
  69.  
  70.     private void setCredentials(Credentials cred) {
  71.  
  72.         BasicCredentialsProvider cP = new BasicCredentialsProvider();
  73.  
  74.         cP.setCredentials(AuthScope.ANY, cred);
  75.  
  76.         setCredentialsProvider(cP);
  77.  
  78.     }
  79.  
  80. }      
  81.  
  82.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


Trust all Manager
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.connection;
  3.  
  4.  
  5.  
  6. import java.security.cert.CertificateException;
  7.  
  8. import java.security.cert.X509Certificate;
  9.  
  10.  
  11.  
  12. import javax.net.ssl.X509TrustManager;
  13.  
  14.  
  15.  
  16. public class TrustAllManager implements X509TrustManager {
  17.  
  18.     public void checkClientTrusted(X509Certificate[] cert, String authType) throws CertificateException { }
  19.  
  20.     public void checkServerTrusted(X509Certificate[] cert, String authType) throws CertificateException { }
  21.  
  22.     public X509Certificate[] getAcceptedIssuers() { return null; }
  23.  
  24. }
  25.  
  26.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Trust All SSL Socket Factory
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.connection;
  3.  
  4.  
  5.  
  6. import java.io.IOException;
  7.  
  8. import java.net.InetAddress;
  9.  
  10. import java.net.Socket;
  11.  
  12. import java.security.KeyManagementException;
  13.  
  14. import java.security.KeyStoreException;
  15.  
  16. import java.security.NoSuchAlgorithmException;
  17.  
  18. import java.security.UnrecoverableKeyException;
  19.  
  20.  
  21.  
  22. import javax.net.ssl.SSLContext;
  23.  
  24. import javax.net.ssl.TrustManager;
  25.  
  26.  
  27.  
  28. import org.apache.http.conn.scheme.SocketFactory;
  29.  
  30. import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
  31.  
  32. import org.apache.http.conn.ssl.SSLSocketFactory;
  33.  
  34.  
  35.  
  36. public class TrustAllSSLSocketFactory extends SSLSocketFactory {
  37.  
  38.     private javax.net.ssl.SSLSocketFactory factory;
  39.  
  40.  
  41.  
  42.     public TrustAllSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
  43.  
  44.         super(null);
  45.  
  46.             try {
  47.  
  48.                 SSLContext sslcontext = SSLContext.getInstance("TLS");
  49.  
  50.                 sslcontext.init(null, new TrustManager[] { new TrustAllManager() }, null);
  51.  
  52.                 factory = sslcontext.getSocketFactory();
  53.  
  54.                 setHostnameVerifier(new AllowAllHostnameVerifier());                   
  55.  
  56.             } catch(Exception ex) { }
  57.  
  58.     }
  59.  
  60.    
  61.  
  62.     public static SocketFactory getDefault() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { return new TrustAllSSLSocketFactory(); }
  63.  
  64.     public Socket createSocket() throws IOException { return factory.createSocket(); }
  65.  
  66.     public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException { return factory.createSocket(socket, s, i, flag); }
  67.  
  68.     public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException { return factory.createSocket(inaddr, i, inaddr1, j); }
  69.  
  70.     public Socket createSocket(InetAddress inaddr, int i) throws IOException { return factory.createSocket(inaddr, i); }
  71.  
  72.     public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException { return factory.createSocket(s, i, inaddr, j); }
  73.  
  74.     public Socket createSocket(String s, int i) throws IOException { return factory.createSocket(s, i); }
  75.  
  76.     public String[] getDefaultCipherSuites() { return factory.getDefaultCipherSuites(); }
  77.  
  78.     public String[] getSupportedCipherSuites() { return factory.getSupportedCipherSuites(); }
  79.  
  80. }
  81.  
  82.  
Parsed in 0.046 seconds, using GeSHi 1.0.8.4


and here an example how to use this...
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.  
  3.  
  4. ConnectionClient con = returnConn("https://www.sercuresite.com:1234", "testuser", "secredpassword");
  5.  
  6.  
  7.  
  8. private ConnectionClient returnConn(URI uri, String user, String pass) {
  9.  
  10.     ConnectionClient conn = null;
  11.  
  12.     try {              
  13.  
  14.         UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
  15.  
  16.         if(uri.getScheme() == "https") {
  17.  
  18.             if(uri.getPort() == -1)
  19.  
  20.                 conn = new ConnectionClient(creds, 443);
  21.  
  22.             else
  23.  
  24.                 conn = new ConnectionClient(creds, uri.getPort());
  25.  
  26.         } else conn = new ConnectionClient(creds);
  27.  
  28.     } catch (KeyManagementException e) {
  29.  
  30.     } catch (NoSuchAlgorithmException e) {
  31.  
  32.     } catch (KeyStoreException e) {
  33.  
  34.     } catch (UnrecoverableKeyException e) {}
  35.  
  36.     return conn;
  37.  
  38. }
  39.  
  40.  
Parsed in 0.039 seconds, using GeSHi 1.0.8.4


Greets
Padde
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby The Spirit » Wed Apr 22, 2009 8:42 am

what app is this code part of?
do you have a link to the complete source code?
would be great
The Spirit
Developer
Developer
 
Posts: 48
Joined: Fri Jan 02, 2009 1:59 pm
Location: Germany

Postby padde » Wed Apr 22, 2009 10:51 am

That app is from me and i could give you parts of source
but not all because its part of my diploma and written for
a company that might want to sell the app in the future.

Greets
Padde
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Top

Postby The Spirit » Wed Apr 22, 2009 11:26 am

hi.
it´s ok. thanks for info
The Spirit
Developer
Developer
 
Posts: 48
Joined: Fri Jan 02, 2009 1:59 pm
Location: Germany

Postby darolla » Fri Sep 04, 2009 4:28 pm

padde wrote:That app is from me and i could give you parts of source
but not all because its part of my diploma and written for
a company that might want to sell the app in the future.

Greets
Padde


I am writing on my bachelor thesis. how far are you?

greetings,
darolla
User avatar
darolla
Master Developer
Master Developer
 
Posts: 273
Joined: Thu Sep 25, 2008 5:16 pm
Location: Dortmund, Germany

Postby padde » Fri Sep 04, 2009 4:52 pm

I have to start again because i had an car accident that took me about 2 months to fully recover.
Sadly i have to write about a different topic.. so actually i could open the code.. but its not realy finished
and not that nice to look at *g*

My new thesis is about webservices and connecting them with mobile devices.. sure as hell i take android
for the mobile part ;) Basically i describe the developmend of an app from the idea up to the implementation
and then some evaluation etc. .. u know the boring thesis stuff ;)
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby darolla » Fri Sep 04, 2009 5:14 pm

hell yeah. I hope you are feeling better now. I am so sorry.

just because I am wrinting my 2nd thesis, too.

but in my case it was justice that f*cked me up...

well, i've 2 weeks left.

and the stupid company i was working for put their servers behind https.

right now I am unable to connect android with the servers.

and i really get nuts on that ssl topic right now.

so for every help i would be so glad...
User avatar
darolla
Master Developer
Master Developer
 
Posts: 273
Joined: Thu Sep 25, 2008 5:16 pm
Location: Dortmund, Germany

Postby darolla » Fri Sep 04, 2009 7:15 pm

this topic is finally solved:

solution is here: http://www.anddev.org/viewtopic.php?p=26514

greetings,
darolla
User avatar
darolla
Master Developer
Master Developer
 
Posts: 273
Joined: Thu Sep 25, 2008 5:16 pm
Location: Dortmund, Germany

Top

Return to Networking & Database Problems

Who is online

Users browsing this forum: Yahoo [Bot] and 6 guests