草庐IT

java - Android 客户端上的 SSL 相互身份验证失败客户端接受服务器证书但服务器未获得客户端证书

coder 2023-12-04 原文

我正在尝试在 Linux 服务器和 Android APP 之间设置相互验证的 SSL。 到目前为止,我已经能够让应用程序与通过 SSL 通信的服务器证书一起工作,但是一旦我将服务器设置为仅接受客户端证书,它就会停止工作。服务器配置似乎没问题,但我有点卡住了。我最好的猜测是客户端证书没有正确地呈现给服务器,但不知道接下来如何测试它。我尝试在我的 OS X 钥匙串(keychain)中为客户端使用 .pem,但浏览器似乎无法使用该证书。然后服务器证书再次完美运行,因为我可以实现 https 连接并且 APP 接受我未签名的服务器证书。

我一直在使用的代码是各种教程的组合,答案这是我 Collection 的主要内容:

这是我用于连接的两个主要类: 1) 此类处理 JSON 解析并执行请求

package edu.hci.additional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import android.content.Context;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params, Context context) {

        // Making HTTP request
        try {

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

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

            }else if(method == "GET"){
                // request method is GET
                SecureHttpClient httpClient = new SecureHttpClient(context);
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

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


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

第二个类处理 SSL 身份验证:

package edu.hci.additional;

import android.content.Context;
import android.util.Log;
import edu.hci.R;
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.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

import java.io.IOException;
import java.io.InputStream;
import java.security.*;


public class SecureHttpClient extends DefaultHttpClient {

    private static Context appContext = null;
    private static HttpParams params = null;
    private static SchemeRegistry schmReg = null;
    private static Scheme httpsScheme = null;
    private static Scheme httpScheme = null;
    private static String TAG = "MyHttpClient";

    public SecureHttpClient(Context myContext) {

        appContext = myContext;

        if (httpScheme == null || httpsScheme == null) {
            httpScheme = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
            httpsScheme = new Scheme("https", mySSLSocketFactory(), 443);
        }

        getConnectionManager().getSchemeRegistry().register(httpScheme);
        getConnectionManager().getSchemeRegistry().register(httpsScheme);

    }

    private SSLSocketFactory mySSLSocketFactory() {
        SSLSocketFactory ret = null;
        try {

            final KeyStore clientCert = KeyStore.getInstance("BKS");
            final KeyStore serverCert = KeyStore.getInstance("BKS");

            final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.authclientcerts);
            final InputStream server_inputStream = appContext.getResources().openRawResource(R.raw.certs);

            clientCert.load(client_inputStream, appContext.getString(R.string.client_store_pass).toCharArray());
            serverCert.load(server_inputStream, appContext.getString(R.string.server_store_pass).toCharArray());

            String client_password = appContext.getString(R.string.client_store_pass);

            server_inputStream.close();
            client_inputStream.close();

            ret = new SSLSocketFactory(clientCert,client_password,serverCert);
        } catch (UnrecoverableKeyException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (KeyStoreException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (KeyManagementException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (NoSuchAlgorithmException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (IOException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (Exception ex) {
            Log.d(TAG, ex.getMessage());
        } finally {
            return ret;
        }
    }

}

要创建 key ,我将 openssl 与此命令结合使用:

openssl req -nodes -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 500

为了获取 Android 版 BKS 的 key ,我使用了位于以下位置的充气城堡 bcprov-jdk15on-150.jar:http://www.bouncycastle.org/latest_releases.html

并使用命令:

keytool -import -v -trustcacerts -alias 0 -file ~/cert.pem -keystore ~/Downloads/authclientcerts.bks -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath ~/Downloads/bcprov-jdk15on-150.jar -storepass passWORD

最后,我在 Fedora 19 中添加到/etc/httpd/conf.d/ssl.conf 以要求客户端证书并检查证书有效性(与我创建的客户端证书匹配)的行是:

...
SSLVerifyClient require
SSLVerifyDepth  5
...
<Location />
SSLRequire (    %{SSL_CLIENT_S_DN_O} eq "Develop" \
            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "Operations", "Dev"} )
</Location>
...
SSLOptions +FakeBasicAuth +StrictRequire

我在这个配置文件上尝试了很多组合,但都以相同的结果结束,给我一个“SSLPeerUnverifiedException:没有对等证书”异常。我在服务器的 SSL 配置文件上评论了这一行,一切正常,但服务器接受所有客户端,这不是我需要的。

提前致谢:)

更新

@EJP 的回答成功了

首先,我必须将证书添加到正确的 (/etc/pki/tls/certs/) 路径并使用以下方法加载它: 重命名证书:mv ca-andr.pem ca-andr.crt 现在加载证书:

 ln -s ca-andr.crt $( openssl x509 -hash -noout -in ca-andr.crt )".0"

这将创建一个名称类似于“f3f24175.0”的 openSSL 可读符号链接(symbolic link)

然后我在/etc/httpd/conf.d/ssl.conf 配置文件中设置新的证书文件。

…
SSLCACertificateFile /etc/pki/tls/certs/f2f62175.0
…

现在重启http服务 测试证书是否加载:

openssl verify -CApath /etc/pki/tls/certs/ f2f62175.0

如果一切正常你应该看到:

f3f24175.0:好的

你可以结束测试:

openssl s_client -connect example.com:443 -CApath /etc/pki/tls/certs

这应该返回受信任的客户端证书列表(如果您看到您添加的证书正在运行)

现在问题的第二部分是我的 authclientcerts.BKS 不包含私钥,所以我提供的密码从未使用过,服务器不会验证证书。所以我将我的 key 和证书导出到 pkcs12 并相应地更新了 JAVA 代码。

导出命令:

openssl pkcs12 -export -in ~/cert.pem -inkey ~/key.pem > android_client_p12.p12

然后我更改了 SecureHttpClient.java 类的部分以使用 PKCS12 而不是 BKS 制作客户端证书。

将 key 存储类型从 BKS 更改为 PKCS12 我替换了:

final KeyStore clientCert = KeyStore.getInstance("BKS”);

为此:

final KeyStore clientCert = KeyStore.getInstance("PKCS12");

然后我更新了对位于 res/raw/上的实际 key 存储文件的引用 通过替换:

final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.authclientcerts);

为此:

final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.android_client_p12);

这就成功了:D

最佳答案

当服务器请求客户端证书时,它会提供一个 CA 列表,它将接受由其签名的证书。如果客户端没有其中之一签名的证书,则不会发送证书作为回复。如果服务器配置为需要客户端证书,而不是只需要一个,它将关闭连接。

因此,请确保客户端拥有服务器信任库可接受的证书。

关于java - Android 客户端上的 SSL 相互身份验证失败客户端接受服务器证书但服务器未获得客户端证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23114049/

有关java - Android 客户端上的 SSL 相互身份验证失败客户端接受服务器证书但服务器未获得客户端证书的更多相关文章

  1. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  5. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  6. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

  7. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  8. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  9. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  10. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

随机推荐