如何在Android中使用SSL加密数据?

时间:2013-09-04 11:19:55

标签: android ssl

在我的应用程序中,我需要创建一个包含用户名和密码组合的注册表单。但它需要加密到服务器。如果我可以使用SSL,请告诉我,如果是,请使用它?

谢谢。

1 个答案:

答案 0 :(得分:1)

我正在猜测,但如果你想要进行实际的握手,你必须让android知道你的证书。如果你想接受无论什么,那么使用这个伪代码来获得你需要的Apache HTTP客户端:

        SchemeRegistry schemeRegistry = new SchemeRegistry ();

        schemeRegistry.register (new Scheme ("http",
        PlainSocketFactory.getSocketFactory (), 80));
        schemeRegistry.register (new Scheme ("https",
        new CustomSSLSocketFactory (), 443));

        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager (
           params, schemeRegistry);


         return new DefaultHttpClient (cm, params);
    }

    // CustomSSLSocketFactory:

       public class CustomSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory
         {
           private SSLSocketFactory FACTORY =  HttpsURLConnection.getDefaultSSLSocketFactory ();

        public CustomSSLSocketFactory ()
          {
            super(null);  
        try
           {
            SSLContext context = SSLContext.getInstance ("TLS");
            TrustManager[] tm = new TrustManager[] { new FullX509TrustManager () };
             context.init (null, tm, new SecureRandom ());

             FACTORY = context.getSocketFactory ();
          }
         catch (Exception e)
         {
              e.printStackTrace();
         }
    }

   public Socket createSocket() throws IOException
     {
        return FACTORY.createSocket();
      }

     // TODO: add other methods like createSocket() and getDefaultCipherSuites().
   // Hint: they all just make a call to member FACTORY 
}


   //FullX509TrustManager is a class that implements javax.net.ssl.X509TrustManager,    yet   none of the methods actually perform any work, get a sample here.
相关问题