1

我刚刚完成了为当地健身房开发的应用程序,并且由于我的测试几乎完成,并且版本 1 也即将完成,我开始考虑保护该应用程序免受任何 MITM 类型的攻击。虽然我知道有人甚至想要 MITM 这个应用程序(而不是银行应用程序)的机会几乎为零,但我仍然希望在安全方面有点主动。

虽然应用程序不发送/接收用户信息(来回发送的数据是体重、次数、时间、用户签到的班级名称等),但我正在传输所有活跃健身房成员的姓名(用于自动完成文本框)。我想加密名称,但我发现很难将我的代码从 HTTP 更改为 HTTPS。我的服务器上有 HTTPS 和自签名证书,但似乎无法让 android 端工作(在 eclipse 中保持没有对等证书错误)。作为一种解决方法,我考虑过使用 AES128 加密/散列每个名称,然后在手机上对其进行解密,然后在通过 PHP 将数据发送回数据库时同样执行相同的操作。

这是加密整个会话的充分替代方案吗?称之为“Lazy SSL”,好像有人拿到了密钥,他们就可以解密数据,但同样,我们只是传输名称,没有其他用户信息。

这是我正在使用的未加密代码(我省略了不必要的东西以使这个块更小):

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } 

这是一个用于解析 Json 的更大的类: 我的整个 JSONParser 类

我在需要将数据拉取或发送到服务器的地方调用这个类,例如:

final JSONParser jsonParser = new JSONParser();

    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", Globals.TAG_GETMEMBERS));
    params.add(new BasicNameValuePair("LastRow", lastRow));
    // getting JSON string from URL
    final JSONObject json = jsonParser.makeHttpRequest(
            Globals.WEBSERVICE_URL, "POST", params);

使用各种资源:

如何在 Android 上为 SSL 套接字启用自签名证书?

http://randomizedsort.blogspot.com/2010/09/step-to-step-guide-to-programming.html

我能够得到一些有用的东西,我最初尝试使用“信任所有证书”方法,但由于这很容易受到 MITM 的影响,我宁愿不使用它(而且它不起作用。使用我得到的第二个链接至于重新生成证书,我已经下载了充气城堡罐(

我还使用以下命令生成密钥库,并将其导入到我的项目中:

keytool -genkey -dname "cn = smashwebserver, ou=Development Team, o=Smash Gyms, L=Sunnyvale, s=California, c=US" -alias ssltest -keypass ssltest -keystore c:\dell\ssltest.keystore -storepass ssltest -validity 180

keytool -export -alias ssltest -keystore c:\dell\ssltest.keystore -file c:\dell\ssltest.cer -storepass ssltest -keypass ssltest

keytool -import -alias ssltestcert -file C:\dell\ssltest.cer -keypass ssltestcert -keystore "C:\Users\Evan Richardson\workspace\SmashGyms\res\raw\ssltestcert" -storetype BKS -storepass ssltestcert -providerClass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "C:\Users\Evan Richardson\workspace\SmashGyms\libs\bcprov-jdk15on-147.jar"

生成的 JSONParser 类块如下所示:

if (method == "POST") {

            // Load the self-signed server certificate
            char[] passphrase = "ssltest".toCharArray();
            KeyStore ksTrust = KeyStore.getInstance("BKS");
            ksTrust.load(context.getResources().openRawResource(
                    R.raw.ssltestcert), passphrase);
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            tmf.init(ksTrust);

            // Create a SSLContext with the certificate
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(),
                    new SecureRandom());

            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }

但是现在我收到以下错误:

10-29 11:55:28.470: W/System.err(9561): java.io.IOException: Wrong version of key store.

我查看了该错误,并在这里找到了可能的解决方案:Android bouncy castle: IOException

我已经下载了 145 版本的 bouncycastles Jar,并使用了它。这修复了 ioexception 错误,但现在我得到以下信息:

10-29 12:21:57.536: W/System.err(12506): Catch exception while startHandshake: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x10b9a10: Failure in SSL library, usually a protocol error
10-29 12:21:57.536: W/System.err(12506): error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:683 0x4026dced:0x00000000)
10-29 12:21:57.536: W/System.err(12506): return an invalid session with invalid cipher suite of SSL_NULL_WITH_NULL_NULL
10-29 12:21:57.586: W/System.err(12506): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

奇怪的是,如果我将我的网址更改为“ https://google.com ”,我没有收到任何错误,只是以下内容:

10-29 14:03:50.198: V/httpresponsetag:(17810): <!DOCTYPE html>
10-29 14:03:50.198: V/httpresponsetag:(17810): <html lang=en>
10-29 14:03:50.198: V/httpresponsetag:(17810):   <meta charset=utf-8>
10-29 14:03:50.198: V/httpresponsetag:(17810):   <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
10-29 14:03:50.198: V/httpresponsetag:(17810):   <title>Error 405 (Method Not Allowed)!!1</title>
10-29 14:03:50.198: V/httpresponsetag:(17810):   <style>
10-29 14:03:50.198: V/httpresponsetag:(17810):     *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}
10-29 14:03:50.198: V/httpresponsetag:(17810):   </style>
10-29 14:03:50.198: V/httpresponsetag:(17810):   <a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>
10-29 14:03:50.198: V/httpresponsetag:(17810):   <p><b>405.</b> <ins>That’s an error.</ins>
10-29 14:03:50.198: V/httpresponsetag:(17810):   <p>The request method <code>POST</code> is inappropriate for the URL <code>/</code>.  <ins>That’s all we know.</ins>

这可能表明它实际上是我的自签名证书,但如果我打开 https:servername,它可以工作(当然有默认警告)

编辑:

即使接受所有证书,我也遇到了同样的错误,所以我用我正在使用的主机名查看浏览器,同样的错误。然后我查看了路由器上的 NAT 设置……我转发到端口 80,而不是 443。失败。更改为 443,现在看起来它正在工作,至少接受所有证书和以下代码:

public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws NoSuchAlgorithmException,
        CertificateException, NotFoundException, KeyStoreException,
        KeyManagementException {

    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {

            // request method is POST
            // defaultHttpClient

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] certs,
                        String authType) {
                }

                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] certs,
                        String authType) {
                }
            } };

            // Install the all-trusting trust manager
            try {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts,
                        new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc
                        .getSocketFactory());
            } catch (Exception e) {
            }

            // Now you can access an https URL without having the certificate in the truststore

            HttpClient client = new DefaultHttpClient();
            client = this.sslClient(client);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            // Log.v(TAG, EntityUtils.toString(result.getEntity()));

            HttpResponse httpResponse = client.execute(httpPost);
            // Log.v("httpresponsetag:", EntityUtils.toString(httpResponse
            // .getEntity()));
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }
4

3 回答 3

4

忘记重新发明惰性 SSL 或其他任何东西。只需使用 SSL 并修复您的代码。并且不要关闭证书验证并信任所有证书。使用自签名证书并不是特别困难,发布您尝试过的内容,人们会为您指明正确的方向。一般来说,您需要:

  1. 拿到证书
  2. 把它放在你的应用程序的原始资源中
  3. KeyStore阅读它并用它初始化 a
  4. 将此传递给您的 SSL 套接字工厂
  5. 使用 4 中的套接字工厂初始化您的 HTTP 客户端。

如果您正在使用,这就是如何做到这HttpClient一点,重点是注册SSLSocketFactory

KeyStore ts = KeyStore.getInstance("BKS");
InputStream in = getResources().openRawResource(R.raw.mytruststore);
ts.load(in, TRUSTSTORE_PASSWORD.toCharArray());

SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(ts);
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
HttpParams params = new BasicHttpParams();
ClientConnectionManager cm = 
    new ThreadSafeClientConnManager(params, schemeRegistry);

HttpClient client = new DefaultHttpClient(cm, params);

查看更多示例、示例项目和一些背景信息: http: //nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html

于 2012-10-29T09:32:57.997 回答
1

我不明白您为什么要解决 SSL 并发明自己的加密方案。我感觉您的自签名证书正在引起您的问题,也许您需要关闭在 Eclipse 中验证自签名证书?

于 2012-10-29T05:10:18.437 回答
-2

我了解您正在使用 ssl,但如果您愿意,还有另一种选择。它正在使用编码和解码。

function encodeString($ss,$ntime){

    for($i=0;$i<$ntime;$i++){

        $ss=base64_encode($ss);

    }

    return $ss;

}



function decodeString($ss,$ntime){

    for($i=0;$i<$ntime;$i++){

        $ss=base64_decode($ss);

    }

    return $ss;

}

你可以像这样使用它,

 encodeString("$membername", 3); //3 will make the encryption more strong. Higher the value higher the encryption.

 decodeString("$membername", 3); //decodes the member name.
于 2012-10-29T05:22:16.623 回答