Https Connection Android

时间:2009-06-15 11:02:20

标签: java android ssl

我正在做一个https帖子,我得到ssl异常的例外不可信服务器证书。如果我做正常的http它工作得很好。我必须以某种方式接受服务器证书吗?

15 个答案:

答案 0 :(得分:84)

这就是我在做的事情。它根本不再检查证书。

// always verify the host - dont check for certificate
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

/**
 * Trust every server - dont check for any certificate
 */
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain,
                String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain,
                String authType) throws CertificateException {
        }
    } };

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

    HttpURLConnection http = null;

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
        https.setHostnameVerifier(DO_NOT_VERIFY);
        http = https;
    } else {
        http = (HttpURLConnection) url.openConnection();
    }

答案 1 :(得分:45)

我正在猜测,但如果你想要进行实际的握手,你必须让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是一个实现javax.net.ssl.X509TrustManager的类,但没有一个方法实际执行任何工作,得到样本here

祝你好运!

答案 2 :(得分:33)

在尝试回答这个问题时,我发现了一个更好的教程。有了它,您不必妥协证书检查。

http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html

*我没有写这个,但感谢Bob Lee的工作

答案 3 :(得分:6)

您还可以查看我的博客文章,非常类似于crazybobs。

此解决方案也不会影响证书检查,并说明如何在您自己的密钥库中添加受信任的证书。

http://blog.antoine.li/index.php/2010/10/android-trusting-ssl-certificates/

答案 4 :(得分:4)

http://madurangasblogs.blogspot.in/2013/08/avoiding-javaxnetsslsslpeerunverifiedex.html

礼貌Maduranga

在开发使用https的应用程序时,您的测试服务器没有有效的SSL证书。或者有时网站使用自签名证书或网站使用免费的SSL证书。因此,如果您尝试使用Apache HttpClient连接到服务器,您将收到一个异常,告知" peer未经过身份验证"。虽然信任生产软件中的所有证书并不是一个好习惯,但您可能必须根据情况这样做。 此解决方案解决了由#34; peer未经过身份验证引起的异常"。

但在我们进入解决方案之前,我必须警告您,这对于生产应用程序来说不是一个好主意。这将违反使用安全证书的目的。因此,除非您有充分的理由,或者如果您确定这不会导致任何问题,请不要使用此解决方案。

通常你会像这样创建一个HttpClient

HttpClient httpclient = new DefaultHttpClient();

但是你必须改变你创建HttpClient的方式。

首先,您必须创建一个扩展org.apache.http.conn.ssl.SSLSocketFactory的类。

import org.apache.http.conn.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

public class MySSLSocketFactory extends SSLSocketFactory {
         SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

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

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

然后创建一个这样的方法。

public HttpClient getNewHttpClient() {
     try {
         KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
         trustStore.load(null, null);

         SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
         sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

         HttpParams params = new BasicHttpParams();
         HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
         HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

         SchemeRegistry registry = new SchemeRegistry();
         registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
         registry.register(new Scheme("https", sf, 443));

         ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

         return new DefaultHttpClient(ccm, params);
     } catch (Exception e) {
         return new DefaultHttpClient();
     }
}

然后您可以创建HttpClient

HttpClient httpclient = getNewHttpClient();

如果您尝试将帖子请求发送到登录页面,则其余代码将如下所示。

private URI url = new URI("url of the action of the form");
HttpPost httppost =  new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
nameValuePairs.add(new BasicNameValuePair("username", "user"));  
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

您将html页面输入到InputStream。然后你可以用返回的html页面做任何你想做的事。

但在这里你会遇到一个问题。如果要使用cookie管理会话,则无法使用此方法执行此操作。如果您想获取cookie,则必须通过浏览器进行操作。然后只有你会收到cookies。

答案 5 :(得分:3)

如果您使用的是StartSSL或Thawte证书,则对于Froyo和旧版本,它将失败。您可以使用newer version's CAcert repository而不是信任每个证书。

答案 6 :(得分:2)

这些都不适合我(Thawte bug也加剧了)。最后,我使用Self-signed SSL acceptance on AndroidCustom SSL handling stopped working on Android 2.2 FroYo

修复了此问题

答案 7 :(得分:2)

这些答案中的任何一个对我都不起作用,所以这里的代码信任任何证书。

import java.io.IOException;

    import java.net.Socket;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;

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

    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.conn.ssl.X509HostnameVerifier;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
    import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

    public class HttpsClientBuilder {
        public static DefaultHttpClient getBelieverHttpsClient() {

            DefaultHttpClient client = null;

            SchemeRegistry Current_Scheme = new SchemeRegistry();
            Current_Scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            try {
                Current_Scheme.register(new Scheme("https", new Naive_SSLSocketFactory(), 8443));
            } catch (KeyManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnrecoverableKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            HttpParams Current_Params = new BasicHttpParams();
            int timeoutConnection = 8000;
            HttpConnectionParams.setConnectionTimeout(Current_Params, timeoutConnection);
            int timeoutSocket = 10000;
            HttpConnectionParams.setSoTimeout(Current_Params, timeoutSocket);
            ThreadSafeClientConnManager Current_Manager = new ThreadSafeClientConnManager(Current_Params, Current_Scheme);
            client = new DefaultHttpClient(Current_Manager, Current_Params);
            //HttpPost httpPost = new HttpPost(url);
            //client.execute(httpPost);

         return client;
         }

    public static class Naive_SSLSocketFactory extends SSLSocketFactory
    {
        protected SSLContext Cur_SSL_Context = SSLContext.getInstance("TLS");

        public Naive_SSLSocketFactory ()
                throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException
        {
            super(null, null, null, null, null, (X509HostnameVerifier)null);
            Cur_SSL_Context.init(null, new TrustManager[] { new X509_Trust_Manager() }, null);
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port,
                boolean autoClose) throws IOException
        {
            return Cur_SSL_Context.getSocketFactory().createSocket(socket, host, port, autoClose);
        }

        @Override
        public Socket createSocket() throws IOException
        {
            return Cur_SSL_Context.getSocketFactory().createSocket();
        }
    }

    private static class X509_Trust_Manager implements X509TrustManager
    {

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

    };
}

答案 8 :(得分:1)

我不知道ssl证书的Android细节,但有意义的是Android不会接受自签名的ssl证书。我从android论坛发现了这篇帖子,似乎解决了同样的问题: http://androidforums.com/android-applications/950-imap-self-signed-ssl-certificates.html

答案 9 :(得分:1)

这是Android 2.x的一个已知问题。我一直在努力解决这个问题,直到我遇到以下问题,这不仅提供了问题的良好背景,而且提供了一个没有任何安全漏洞的有效解决方案。

'No peer certificate' error in Android 2.3 but NOT in 4

答案 10 :(得分:0)

出于某种原因,上面针对httpClient提到的解决方案对我没有用。最后,我能够通过在实现自定义SSLSocketFactory类时正确覆盖该方法来使其工作。

@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) 
                              throws IOException, UnknownHostException 
    {
    return sslFactory.createSocket(socket, host, port, autoClose);
}

@Override
public Socket createSocket() throws IOException {
    return sslFactory.createSocket();
}

这对我来说是完美的。您可以在以下线程中看到完整的自定义类并实现: http://blog.syedgakbar.com/2012/07/21/android-https-and-not-trusted-server-certificate-error/

答案 11 :(得分:0)

我创建了这个课程并找到了

package com.example.fakessl;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import android.util.Log;

public class CertificadoAceptar {
    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements
            javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public boolean isClientTrusted(X509Certificate[] chain) {
            return (true);
        }

        public boolean isServerTrusted(X509Certificate[] chain) {
            return (true);
        }

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

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection
                .setDefaultHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[] { new _FakeX509TrustManager() };
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            Log.e("allowAllSSL", e.toString());
        } catch (KeyManagementException e) {
            Log.e("allowAllSSL", e.toString());
        }
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());
    }
}

在你的代码白色

CertificadoAceptar ca = new CertificadoAceptar();
ca.allowAllSSL();
HttpsTransportSE Transport = new HttpsTransportSE("iphost or host name", 8080, "/WS/wsexample.asmx?WSDL", 30000);

答案 12 :(得分:0)

帮助我在AWS Apache服务器上使用自签名证书并从Android设备连接HttpsURLConnection的来源:

SSL on aws instance - 关于ssl的亚马逊教程 Android Security with HTTPS and SSL - 在客户端创建自己的信任经理,以接受您的证书 Creating self signed certificate - 用于创建证书的简单脚本

然后我做了以下事情:

  1. 确保服务器支持https(sudo yum install -y mod24_ssl)
  2. 将此脚本放入文件create_my_certs.sh
  3. #!/bin/bash
    FQDN=$1
    
    # make directories to work from
    mkdir -p server/ client/ all/
    
    # Create your very own Root Certificate Authority
    openssl genrsa \
      -out all/my-private-root-ca.privkey.pem \
      2048
    
    # Self-sign your Root Certificate Authority
    # Since this is private, the details can be as bogus as you like
    openssl req \
      -x509 \
      -new \
      -nodes \
      -key all/my-private-root-ca.privkey.pem \
      -days 1024 \
      -out all/my-private-root-ca.cert.pem \
      -subj "/C=US/ST=Utah/L=Provo/O=ACME Signing Authority Inc/CN=example.com"
    
    # Create a Device Certificate for each domain,
    # such as example.com, *.example.com, awesome.example.com
    # NOTE: You MUST match CN to the domain name or ip address you want to use
    openssl genrsa \
      -out all/privkey.pem \
      2048
    
    # Create a request from your Device, which your Root CA will sign
    openssl req -new \
      -key all/privkey.pem \
      -out all/csr.pem \
      -subj "/C=US/ST=Utah/L=Provo/O=ACME Tech Inc/CN=${FQDN}"
    
    # Sign the request from Device with your Root CA
    openssl x509 \
      -req -in all/csr.pem \
      -CA all/my-private-root-ca.cert.pem \
      -CAkey all/my-private-root-ca.privkey.pem \
      -CAcreateserial \
      -out all/cert.pem \
      -days 500
    
    # Put things in their proper place
    rsync -a all/{privkey,cert}.pem server/
    cat all/cert.pem > server/fullchain.pem         # we have no intermediates in this case
    rsync -a all/my-private-root-ca.cert.pem server/
    rsync -a all/my-private-root-ca.cert.pem client/
    
    1. 运行bash create_my_certs.sh yourdomain.com
    2. 将证书放在服务器上的适当位置(您可以在/etc/httpd/conf.d/ssl.conf中找到配置)。所有这些都应该设置:
      了SSLCertificateFile
      了SSLCertificateKeyFile
      SSLCertificateChainFile
      SSLCACertificateFile

    3. 使用sudo service httpd restart重启httpd并确保启动httpd:
      停止httpd:[确定]
      启动httpd:[确定]

    4. my-private-root-ca.cert复制到您的android项目资产文件夹

    5. 创建您的信任经理:

      SSLContext SSLContext;

      CertificateFactory cf = CertificateFactory.getInstance(“X.509”);           InputStream caInput = context.getAssets()。open(“my-private-root-ca.cert.pem”);           证书ca;           尝试{             ca = cf.generateCertificate(caInput);           } finally {             caInput.close();           }

        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
      
        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);
      
        // Create an SSLContext that uses our TrustManager
        SSLContext = SSLContext.getInstance("TLS");
        SSSLContext.init(null, tmf.getTrustManagers(), null);
      
    6. 使用HttpsURLConnection建立连接:

      HttpsURLConnection connection =(HttpsURLConnection)url.openConnection(); connection.setSSLSocketFactory(SSLContext.getSocketFactory());

    7. 多数,尝试你的https连接。

答案 13 :(得分:0)

可能您可以尝试这样的事情。这对我有帮助

    SslContextFactory sec = new SslContextFactory();
    sec.setValidateCerts(false);
    sec.setTrustAll(true);

    org.eclipse.jetty.websocket.client.WebSocketClient client = new WebSocketClient(sec);

答案 14 :(得分:-1)

只需将此方法用作HTTPClient:

public static  HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}