HTTPS 连接安卓
Posted
技术标签:
【中文标题】HTTPS 连接安卓【英文标题】:Https Connection Android 【发布时间】:2010-11-02 23:45:29 【问题描述】:我正在做一个 https 帖子,但我收到了 ssl 异常不受信任的服务器证书的异常。如果我做正常的http,它工作得很好。我必须以某种方式接受服务器证书吗?
【问题讨论】:
我可以得到一些相同的示例实现 这个线程可能会有所帮助,但我不知道它是否适用于最新的 API:groups.google.com/group/android-developers/browse_thread/thread/… 【参考方案1】:这就是我正在做的。它根本不再检查证书。
// 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();
【讨论】:
这看起来不错!但是,我使用的是 WebView,并且只需要连接到 https 服务器即可进行测试。 (客户端不能提供一个匹配的 FQDN,也不能在 http 上进行测试。)在使用 WebView 时有没有办法解决这个问题?我是否只是将此代码放在 WebView 所在的 Activity 中并且“它可以正常工作”? (怀疑不是……??) 我正在尝试逐步使用该解决方案,但我遇到了这样的异常:07-25 12:35:25.941: WARN/System.err(24383): java.lang.ClassCastException : org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl 在我试图打开连接的地方......知道为什么吗?? 嘿,我按照你的建议做了,但我得到了javax.net.ssl.SSLException: Received fatal alert: bad_record_mac
的异常。我也尝试用SSL
替换TLS
,但它没有帮助。请帮帮我,谢谢
虽然这在开发阶段很好,但您应该知道这样一个事实,即任何人都可以通过伪造随机 SSL 证书来 MITM 您的安全连接,这会使您的连接不再安全。看看this question 看看它是否正确,here 看看如何接收证书,最后看看this 了解如何将它添加到密钥库中。
您不应使用推荐或发布此代码。这是根本不安全的。你应该解决实际问题。【参考方案2】:
我在猜测,但如果您希望发生真正的握手,您必须让 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。
祝你好运!
【讨论】:
为什么会有FACTORY变量?? 返回 FACTORY.createSocket();有问题。创建的套接字在执行()上给出了空指针异常。另外,我注意到,有 2 个 SocketFactory 类。 1. org.apache.http.conn.ssl.SSLSocketFactory 和 2. javax.net.ssl.SSLSocketFactory 嗨内特,这看起来对我的情况有帮助。但是,我在制作 CustomSSLSocketFactory 时遇到了一些问题。它应该扩展什么类?或者它应该实现什么接口?我一直在尝试:javax.net.SocketFactory、javax.net.ssl.SSLSocketFactory、org.apache.http.conn.scheme.SocketFactory,所有这些都强制执行其他方法......所以,一般来说,什么您的代码中使用的类的命名空间是什么?谢谢你。 :) 对我不起作用,给我同样的不受信任的服务器证书错误。 我怎样才能得到这个课程FullX509TrustManager
【参考方案3】:
在尝试回答这个问题时,我发现了一个更好的教程。有了它,您不必破坏证书检查。
http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html
*这不是我写的,但感谢 Bob Lee 的工作
【讨论】:
这是完美的答案。我发布了一个更新帖子,显示了当我收到 PeerCertificate 错误时如何处理未列出的 CA。在这里看到它:blog.donnfelker.com/2011/06/13/…【参考方案4】:你也可以看看我的博客文章,很像crazybobs。
此解决方案也不会影响证书检查,并说明如何在您自己的密钥库中添加受信任的证书。
http://blog.antoine.li/index.php/2010/10/android-trusting-ssl-certificates/
【讨论】:
【参考方案5】:http://madurangasblogs.blogspot.in/2013/08/avoiding-javaxnetsslsslpeerunverifiedex.html
礼貌马杜兰加
在开发使用 https 的应用程序时,您的测试服务器没有有效的 SSL 证书。或者有时网站使用自签名证书或网站使用免费 SSL 证书。因此,如果您尝试使用 Apache HttpClient
连接到服务器,您将收到一个异常,告诉您“对等方未通过身份验证”。尽管信任生产软件中的所有证书并不是一个好习惯,但您可能必须根据情况这样做。
此方案解决了“peer not authenticated”导致的异常。
但是在我们讨论解决方案之前,我必须警告您,这对于生产应用程序来说不是一个好主意。这将违反使用安全证书的目的。因此,除非您有充分的理由或者您确信这不会造成任何问题,否则不要使用此解决方案。
通常你会像这样创建一个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,则必须通过浏览器进行。那么只有你会收到 cookie。
【讨论】:
【参考方案6】:如果您使用的是 StartSSL 或 Thawte 证书,则对于 Froyo 和旧版本将失败。您可以使用newer version's CAcert repository 而不是信任每个证书。
【讨论】:
【参考方案7】:这些都不适合我(Thawte bug 也会加剧)。最终我用Self-signed SSL acceptance on Android 和Custom SSL handling stopped working on Android 2.2 FroYo 修复了它
【讨论】:
【参考方案8】:这些答案中的任何一个都不适合我,所以这里是信任任何证书的代码。
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;
;
【讨论】:
此代码适用于 URL 模式 - localhost:8443/webProject/YourService 构造函数 SSLSocketFactory(null, null, null, null, null, X509HostnameVerifier) 未定义【参考方案9】:我不了解 ssl 证书的 Android 细节,但 Android 不会立即接受自签名 ssl 证书是有道理的。我从 android 论坛上找到了这篇文章,似乎解决了同样的问题: http://androidforums.com/android-applications/950-imap-self-signed-ssl-certificates.html
【讨论】:
就像我说的那样,我不知道 Android 的细节,但你必须告诉平台你要连接的服务器的 ssl 证书是什么。也就是说,如果您使用的是平台无法识别的自签名证书。 SslCertificate 类可能会有所帮助:developer.android.com/reference/android/net/http/… 今天晚些时候,当我有更多时间时,我会深入研究。【参考方案10】:这是 Android 2.x 的一个已知问题。我在这个问题上苦苦挣扎了一个星期,直到遇到以下问题,它不仅提供了问题的良好背景,而且提供了一个没有任何安全漏洞的有效解决方案。
'No peer certificate' error in Android 2.3 but NOT in 4
【讨论】:
【参考方案11】:由于某种原因,上面提到的 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/
【讨论】:
【参考方案12】:我做了这门课,发现
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);
【讨论】:
【参考方案13】:帮助我在我的 AWS Apache 服务器上使用我的自签名证书并从 android 设备连接到 HttpsURLConnection 的来源:SSL on aws instance - 关于 ssl 的亚马逊教程Android Security with HTTPS and SSL - 创建您自己的客户端信任管理器,用于接受您的证书Creating self signed certificate - 用于创建证书的简单脚本
然后我做了以下事情:
-
确保服务器支持 https (sudo yum install -y mod24_ssl)
将此脚本放入文件
create_my_certs.sh
:
#!/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/
-
运行
bash create_my_certs.sh yourdomain.com
将证书放在服务器上适当的位置(您可以在 /etc/httpd/conf.d/ssl.conf 中找到配置)。所有这些都应该设置: SSL证书文件 SSLCertificateKeyFile SSL证书链文件 SSLCACertificateFile
使用 sudo service httpd restart
重新启动 httpd 并确保 httpd 已启动:
停止 httpd:[确定]
启动 httpd:[确定]
复制my-private-root-ca.cert
到你的android项目资产文件夹
创建您的信任经理:
SSLContext SSLContext;
CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = context.getAssets().open("my-private-root-ca.cert.pem"); 证书ca; 尝试 ca = cf.generateCertificate(caInput); 最后 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);
并使用 HttpsURLConnection 建立连接:
HttpsURLConnection 连接 = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(SSLContext.getSocketFactory());
就是这样,试试你的 https 连接。
【讨论】:
【参考方案14】:也许你可以尝试这样的事情。这对我有帮助
SslContextFactory sec = new SslContextFactory();
sec.setValidateCerts(false);
sec.setTrustAll(true);
org.eclipse.jetty.websocket.client.WebSocketClient client = new WebSocketClient(sec);
【讨论】:
【参考方案15】:只需将此方法用作您的 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();
【讨论】:
以上是关于HTTPS 连接安卓的主要内容,如果未能解决你的问题,请参考以下文章