2014年6月4日 星期三

TLS Socket Sample

Uses Permission:
android.permission.INTERNET


MainActivity.java:
package com.example.sample_sslsocket;

import java.io.IOException;
import java.net.UnknownHostException;
import java.security.cert.Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;



public class MainActivity extends Activity {
 private TextView textView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  //get UI view
  textView = (TextView) this.findViewById(R.id.textView1);
  textView.setText("");
  //start SSL test sample.
  new Thread(new Runnable(){
   @Override
   public void run() {
    mainTest();
   }}).start();
  
 }
 private void TRACE(final String log){
  this.runOnUiThread(new Runnable(){
   @Override
   public void run() {
    Log.w("MainActivity", log);
    textView.append(log+"\r\n");   
   }}
  );
 }
 private void mainTest(){
  /**
  * 443 is the network port number used by the SSL https: URi scheme.
  */
  int port = 443;
  String hostname = "www.google.com";
  SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();

TRACE("Creating a SSL Socket For "+hostname+" on port "+port);
  
  SSLSocket socket = null;
  try {
   socket = (SSLSocket) factory.createSocket(hostname, port);
  } catch (UnknownHostException e) {
TRACE("factory.createSocket >> UnknownHostException");
  } catch (IOException e) {
TRACE("factory.createSocket >> IOException");
  }
TRACE("factory.createSocket >> successful");
  /**
  * Starts an SSL handshake on this connection. Common reasons include a
  * need to use new encryption keys, to change cipher suites, or to
  * initiate a new session. To force complete reauthentication, the
  * current session could be invalidated before starting this handshake.
  * If data has already been sent on the connection, it continues to flow
  * during this handshake. When the handshake completes, this will be
  * signaled with an event. This method is synchronous for the initial
  * handshake on a connection and returns when the negotiated handshake
  * is complete. Some protocols may not support multiple handshakes on an
  * existing socket and may throw an IOException.
  */
  try {
   socket.startHandshake();
  } catch (IOException e) {
TRACE("socket.startHandshake >> IOException");
  }
TRACE("Handshaking Complete");
  
  /**
  * Retrieve the server's certificate chain
  *
  * Returns the identity of the peer which was established as part of
  * defining the session. Note: This method can be used only when using
  * certificate-based cipher suites; using it with non-certificate-based
  * cipher suites, such as Kerberos, will throw an
  * SSLPeerUnverifiedException.
  *
  *
  * Returns: an ordered array of peer certificates, with the peer's own
  * certificate first followed by any certificate authorities.
  */
  Certificate[] serverCerts = null;
  try {
   serverCerts = socket.getSession().getPeerCertificates();
  } catch (SSLPeerUnverifiedException e) {
TRACE(" socket.getSession().getPeerCertificates >> SSLPeerUnverifiedException");
  }
TRACE("Retreived Server's Certificate Chain");
TRACE(serverCerts.length + "Certifcates Found\n\n\n");
  for (int i = 0; i < serverCerts.length; i++) {
   Certificate myCert = serverCerts[i];
TRACE("====Certificate:" + (i+1) + "====");
TRACE("-Public Key-\n" + myCert.getPublicKey());
TRACE("-Certificate Type-\n " + myCert.getType());
TRACE("");
  }
  
  
  String packet = "GET / HTTP/1.1\r\n\r\n";
TRACE("sending packet = "+packet);
  try {
   socket.getOutputStream().write(packet.getBytes());
TRACE("sending packet succeeded");
  } catch (IOException e1) {
TRACE("socket.getOutputStream().write >> IOException");
  }
TRACE("recving packet");
  byte[] recv = new byte[10000];
  try {
   int recvLen = socket.getInputStream().read(recv, 0, recv.length);
   String str = new String(recv, 0, recvLen);
TRACE("recv packet = "+str);
  } catch (IOException e1) {
TRACE("socket.getInputStream().read >> IOException");
  }
  
  
  try {
TRACE("closing socket");
   socket.close();
TRACE("socket closed");
  } catch (IOException e) {
TRACE("socket.close >> IOException");
  }
 }
}


activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sample_sslsocket.MainActivity"
    tools:ignore="MergeRootFrame" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <ScrollView
            android:id="@+id/scrollView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:text="TextView" />

            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</FrameLayout>

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sample_sslsocket"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sample_sslsocket.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


沒有留言 :

張貼留言