網頁

2017年9月5日 星期二

SSL, RaspberryPi Server, Android Client

請參考 Android 與 Raspberry 證書 和 SSL 網路程式設計 的 Server 端
在此提供 Android 的 Client

package com.example.mark.sslclient;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/** * Created by mark on 2017/9/1. */
public class SSLClient {
    static SSLContext ssl_ctx;

    public SSLClient(Context context) {
        try {
            Log.d("SSLClient", "SSLClient");

            //  Setup truststore            KeyStore trustStore = KeyStore.getInstance("BKS");
            InputStream trustStoreStream = context.getResources().openRawResource(R.raw.android);
            trustStore.load(trustStoreStream, "store1234".toCharArray());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            Log.d("SSLClient", "Trust " + trustStore.size());
            Log.d("SSLClient", "trustManagerFactory " + trustManagerFactory.getTrustManagers().length);

            //  Setup keystore            KeyStore keyStore = KeyStore.getInstance("BKS");
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            InputStream keyStoreStream = context.getResources().openRawResource(R.raw.android);
            keyStore.load(keyStoreStream, "store1234".toCharArray());
            keyManagerFactory.init(keyStore, "key1234".toCharArray());
            Log.d("SSLClient", "Key " + keyStore.size());
            Log.d("SSLClient", "keyManagerFactory " + keyManagerFactory.getKeyManagers().length);

            // Setup the SSL context to use the truststore and keystore            ssl_ctx = SSLContext.getInstance("TLS");
            if (true) {
                ssl_ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            } else {
                TrustManager tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authTyhpe) throws CertificateException {
                    }
                    public void checkServerTrusted(X509Certificate[] chain, String authTyhpe) throws CertificateException {
                    }
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                ssl_ctx.init(null, new TrustManager[] { tm }, null);
            }
        } catch (KeyStoreException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (CertificateException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (IOException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (KeyManagementException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (UnrecoverableKeyException e) {
            Log.d("SSLClient", e.getMessage());
        }
    }
}

package com.example.mark.sslclient;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

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

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private SSLClient sslClient;

    private Runnable threadMain = new Runnable() {
        @Override        public void run() {
            SSLSocketFactory socketFactory = (SSLSocketFactory)sslClient.ssl_ctx.getSocketFactory();
            try {
                Log.d(TAG, "threadMain createSocket a");
                SSLSocket socket = (SSLSocket)socketFactory.createSocket("192.168.1.61", 8080);
                Log.d(TAG, "threadMain createSocket b");
                PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                BufferedReader input = new BufferedReader((new InputStreamReader(socket.getInputStream())));
                output.println("\nthis is from client+++++++++++++++client send to server");
                output.flush();
                Log.d(TAG, "threadMain input.readLine() a");
                String line = input.readLine();
                while (line != null) {
                    Log.d(TAG, line);
                    line = input.readLine();
                }
                Log.d(TAG, "threadMain input.readLine() b");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate a");
        setContentView(R.layout.activity_main);

        sslClient = new SSLClient(this);
        Thread thread = new Thread(threadMain);
        thread.start();
        Log.d(TAG, "onCreate b");
    }
}

沒有留言:

張貼留言