Android Open Source - android_asyncsocket S S L Client






From Project

Back to project page android_asyncsocket.

License

The source code is released under:

GNU Lesser General Public License

If you think the Android project android_asyncsocket listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.smorra.asyncsocket;
/*from ww w .  j ava  2  s. co  m*/
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import android.widget.Toast;

public class SSLClient implements TcpClientCallback
{
  TcpClient client;
  SSLClientCallback callback;
  SSLEngine engine;
  byte[] buffer = new byte[0];
  boolean connectSent = false;

  public SSLClient(String hostname, int port, SSLClientCallback callback) throws IOException, NoSuchAlgorithmException, KeyManagementException, CertificateException, KeyStoreException
  {
    this.callback = callback;
    client = new TcpClient(this, hostname, port);

    SSLContext sslCtx = SSLContext.getInstance("SSL");
    X509TrustManager tm = new X509TrustManager()
    {

      public X509Certificate[] getAcceptedIssuers()
      {
        return null;
      }

      @Override
      public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException
      {
        // TODO Auto-generated method stub

      }

      @Override
      public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException
      {
        // TODO Auto-generated method stub

      }
    };
    sslCtx.init(null, new TrustManager[] { tm }, null);
    engine = sslCtx.createSSLEngine(hostname, port);
  }

  @Override
  public void onConnectFailed(TcpClient tcpClient)
  {
    // TODO Auto-generated method stub

  }

  @Override
  public void onConnect(TcpClient tcpClient)
  {

    try
    {
      engine.setUseClientMode(true);
      engine.beginHandshake();
      System.out.println(engine.getHandshakeStatus());
      while (true)
      {
        if (engine.getHandshakeStatus() == HandshakeStatus.NEED_WRAP)
        {
          int bufSize = engine.getSession().getPacketBufferSize();
          while (engine.getHandshakeStatus() == HandshakeStatus.NEED_WRAP)
          {
            System.out.println("IN OOOOOOP");
            ByteBuffer src = ByteBuffer.allocate(0);
            ByteBuffer dst = ByteBuffer.allocate(bufSize);

            SSLEngineResult res = null;
            try
            {
              res = engine.wrap(src, dst);
            }
            catch (SSLException e)
            {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            // process produced bytes
            byte[] produced = new byte[res.bytesProduced()];
            System.arraycopy(dst.array(), 0, produced, 0, produced.length);
            try
            {
              client.write(produced);
            }
            catch (IOException e)
            {
              e.printStackTrace();
            }
            System.out.println("RESULT IS " + res.getStatus());
            if (res.getStatus() == Status.BUFFER_OVERFLOW)
            {
              bufSize += 1024;
            }
            else if (res.getStatus() == Status.OK)
            {
              bufSize = engine.getSession().getApplicationBufferSize();
            }
            else if (res.getStatus() == Status.CLOSED)
            {
              System.out.println("WHAT TO DO?");
            }
            else if (res.getStatus() == Status.BUFFER_UNDERFLOW)
            {
              System.out.println("BUFFER_UNDERFLOW while wrapping?");
            }

          }

        }
        else if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK)
        {
          Runnable runnable = engine.getDelegatedTask();
          runnable.run();
        }
        else
        {
          break;
        }

      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  @Override
  public void onDisconnected(TcpClient tcpClient)
  {
    callback.onDisconnected(this);
  }

  @Override
  public void onRead(TcpClient tcpClient, byte[] readBytes)
  {
    byte[] new_bytes = new byte[readBytes.length + buffer.length];
    System.arraycopy(buffer, 0, new_bytes, 0, buffer.length);
    System.arraycopy(readBytes, 0, new_bytes, buffer.length, readBytes.length);
    buffer = new_bytes;
    try
    {
      boolean enoughBytesForUnwrap = true;
      while (true)
      {
        if (engine.getHandshakeStatus() == HandshakeStatus.NEED_WRAP)
        {
          int bufSize = engine.getSession().getPacketBufferSize();
          while (engine.getHandshakeStatus() == HandshakeStatus.NEED_WRAP)
          {
            System.out.println("IN OOOOOOP");
            ByteBuffer src = ByteBuffer.allocate(0);
            ByteBuffer dst = ByteBuffer.allocate(bufSize);

            SSLEngineResult res = null;
            try
            {
              res = engine.wrap(src, dst);
            }
            catch (SSLException e)
            {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            // process produced bytes
            byte[] produced = new byte[res.bytesProduced()];
            System.arraycopy(dst.array(), 0, produced, 0, produced.length);
            try
            {
              client.write(produced);
            }
            catch (IOException e)
            {
              e.printStackTrace();
            }
            System.out.println("RESULT IS " + res.getStatus());
            if (res.getStatus() == Status.BUFFER_OVERFLOW)
            {
              bufSize += 1024;
            }
            else if (res.getStatus() == Status.OK)
            {
              bufSize = engine.getSession().getApplicationBufferSize();
            }
            else if (res.getStatus() == Status.CLOSED)
            {
              System.out.println("WHAT TO DO?");
            }
            else if (res.getStatus() == Status.BUFFER_UNDERFLOW)
            {
              System.out.println("BUFFER_UNDERFLOW while wrapping?");
            }

          }

        }
        else if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK)
        {
          Runnable runnable = engine.getDelegatedTask();
          runnable.run();
        }
        else if (engine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP)
        {
          if (!enoughBytesForUnwrap)
            break;

          int bufSize = engine.getSession().getApplicationBufferSize();
          System.out.println("ENTER LOOP");
          while (true)
          {
            ByteBuffer dst = ByteBuffer.allocate(bufSize);
            ByteBuffer src = ByteBuffer.wrap(buffer);
            SSLEngineResult res = null;
            try
            {
              res = engine.unwrap(src, dst);
            }
            catch (Exception e)
            {
              e.printStackTrace();
            }

            // process produced bytes
            byte[] decoded = new byte[res.bytesProduced()];
            System.arraycopy(dst.array(), 0, decoded, 0, decoded.length);
            try
            {
              System.out.println("CALLIGN FROM LINE XYZ2");
              callback.onRead(this, decoded);
            }
            catch (Exception e)
            {
              e.printStackTrace();
            }

            byte[] new_buffer = new byte[src.capacity() - src.position()];
            System.arraycopy(buffer, src.position(), new_buffer, 0, new_buffer.length);
            buffer = new_buffer;

            if (res.getStatus() == Status.BUFFER_OVERFLOW)
            {
              System.out.println("BUFFER OVERFLOW");
              bufSize += 1024;
            }
            else if (res.getStatus() == Status.BUFFER_UNDERFLOW || res.getStatus() == Status.CLOSED)
            {
              System.out.println("BUFFER UNDERFLOW or CLOSED");
              enoughBytesForUnwrap = false;
              break;
            }
            else if (res.getStatus() == Status.OK)
            { // do it again
              if (res.bytesConsumed() == 0)
              {
                enoughBytesForUnwrap = false;
                break;
              }
              bufSize = engine.getSession().getApplicationBufferSize();
            }
          }

        }
        else
        {
          if (!connectSent)
          {
            callback.onConnect(this);
            connectSent = true;
          }
          break;
        }

      }
      int bufSize = engine.getSession().getApplicationBufferSize();

      while (true)
      {
        System.out.println("IN LOOP AFTER");
        ByteBuffer dst = ByteBuffer.allocate(bufSize);
        ByteBuffer src = ByteBuffer.wrap(buffer);

        SSLEngineResult res = null;
        try
        {
          res = engine.unwrap(src, dst);
        }
        catch (SSLException e1)
        {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }

        // process produced bytes
        byte[] decoded = new byte[res.bytesProduced()];
        System.arraycopy(dst.array(), 0, decoded, 0, decoded.length);
        try
        {
          System.out.println("CALLIGN FROM LINE XY");
          callback.onRead(this, decoded);
        }
        catch (Exception e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        // refresh buffer
        byte[] new_buffer = new byte[buffer.length - res.bytesConsumed()];
        System.arraycopy(buffer, res.bytesConsumed(), new_buffer, 0, new_buffer.length);
        buffer = new_buffer;

        if (res.getStatus() == Status.BUFFER_OVERFLOW)
        {
          bufSize += 1024;
        }
        else if (res.getStatus() == Status.BUFFER_UNDERFLOW || res.getStatus() == Status.CLOSED)
        {
          break;
        }
        else if (res.getStatus() == Status.OK)
        {
          if (res.bytesConsumed() == 0)
            break;
          // do it again
          bufSize = engine.getSession().getApplicationBufferSize();
        }

      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public void write(byte[] bytes) throws IOException, InterruptedException
  {

    int bufSize = engine.getSession().getApplicationBufferSize();
    while (bytes.length != 0)
    {
      ByteBuffer src = ByteBuffer.wrap(bytes);
      ByteBuffer dst = ByteBuffer.allocate(bufSize);
      SSLEngineResult res = engine.wrap(src, dst);

      byte[] produced = new byte[res.bytesProduced()];
      System.arraycopy(dst.array(), 0, produced, 0, res.bytesProduced());
      client.write(produced);

      byte[] new_bytes = new byte[bytes.length - res.bytesConsumed()];
      System.arraycopy(bytes, res.bytesConsumed(), new_bytes, 0, new_bytes.length);
      bytes = new_bytes;

      if (res.getStatus() == Status.BUFFER_OVERFLOW)
        bufSize += 1024;

    }

  }

  @Override
  public void onWritten(TcpClient tcpClient)
  {
    // TODO Auto-generated method stub

  }
}




Java Source Code List

com.smorra.asyncsocket.DnsResolverCallback.java
com.smorra.asyncsocket.DnsResolver.java
com.smorra.asyncsocket.SSLClientCallback.java
com.smorra.asyncsocket.SSLClient.java
com.smorra.asyncsocket.TcpClientCallback.java
com.smorra.asyncsocket.TcpClient.java
com.smorra.asyncsocket.TcpServerCallback.java
com.smorra.asyncsocket.TcpServerClientCallback.java
com.smorra.asyncsocket.TcpServerClient.java
com.smorra.asyncsocket.TcpServer.java