如何使用未知 CA 自签名的证书让 Android Volley 执行 HTTPS 请求?

2023-12-20

在提出问题之前,我找到了一些链接,我逐一检查了这些链接,但没有一个链接给我提供了解决方案:

  • 知名CA 使用 Volley 的 HTTPS 请求 https://stackoverflow.com/questions/21555404/https-request-using-volley
  • 接受所有 SSL 证书 无对等证书例外 - Volley 和具有自签名证书的 Android https://stackoverflow.com/questions/26412417/no-peer-certificate-exception-volley-and-android-with-self-signed-certificate
  • Node.js (Socket.io) Socket.io + SSL + 自签名 CA 证书连接时出错 https://stackoverflow.com/questions/15365772/socket-io-ssl-self-signed-ca-certificate-gives-error-when-connecting
  • “手动”导入的自签名证书: 使用自签名证书和 CA 的 Android SSL HTTP 请求 https://stackoverflow.com/questions/19433058/android-ssl-http-request-using-self-signed-cert-and-ca

到目前为止我找到的唯一链接是这个,它提供了两种方法:使用 Android Volley 发出 HTTPS 请求 https://stackoverflow.com/questions/17045795/making-a-https-request-using-android-volley

  • 1° 指示将一些类导入到您的应用程序中,而实际上,还必须导入其他类,并且这些类正在使用“apache.org”中已弃用的库
  • 2° NUKE 所有 SSL 证书的示例(非常糟糕的主意......)


我还找到了这个博客,其中有很多解释,但最后,我意识到这些示例使用的是“apache.org”中已弃用的库,而且该博客本身没有 Android Volley 的内容。https://nelenkov.blogspot.mx/2011/12/using-custom-certificate-trust-store-on.html https://nelenkov.blogspot.mx/2011/12/using-custom-certificate-trust-store-on.html


还有来自 Android 的链接和“未知证书颁发机构”部分的代码,它提供了有关解决方案的好主意,但代码本身的结构中缺少一些内容(Android Studio 抱怨......):https://developer.android.com/training/articles/security-ssl.html https://developer.android.com/training/articles/security-ssl.html

但链接中的这段引用似乎是解决问题的核心概念。

“TrustManager 是系统用来验证来自服务器的证书的工具,并且通过从具有一个或多个 CA 的 KeyStore 创建一个证书,这些将成为该 TrustManager 信任的唯一 CA。 给定新的 TrustManager,该示例初始化一个新的 SSLContext,它提供了一个 SSLSocketFactory,您可以使用它来覆盖 HttpsURLConnection 中的默认 SSLSocketFactory。这样,连接将使用您的 CA 进行证书验证。”



现在,这是我的问题:我有一个使用自签名证书的网络服务器,并且我根据其证书创建了一个“BKS 信任库”。我已将 de BKS 信任库导入到我的 Android 应用程序中,现在,我的应用程序上有以下代码(我只是在此处发布 MainActivity,我想这是迄今为止与此主题相关的唯一类):

package com.domain.myapp;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.InputStream;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;


public class LoginScreen extends AppCompatActivity {

Context ctx          = null;
InputStream inStream = null;
HurlStack hurlStack  = null;

EditText username    = null;
EditText password    = null;
String loginStatus   = null;

public LoginScreen() {

    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore ks = KeyStore.getInstance("BKS");
        inStream = ctx.getApplicationContext().getResources().openRawResource(R.raw.mytruststore);
        ks.load(inStream, null);
        inStream.close();
        tmf.init(ks);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        hurlStack = new HurlStack(null, sslSocketFactory);
    } catch (Exception e){
        Log.d("Exception:",e.toString());
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_screen);
    username = (EditText) findViewById(R.id.user);
    password = (EditText) findViewById(R.id.passwd);
}

public void login(View view) {

    RequestQueue queue = Volley.newRequestQueue(this, hurlStack);
    final String url = "https://myserver.domain.com/app/login";

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    Log.d("Response", response);
                    loginStatus = "OK";
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("Error.Response", String.valueOf(error));
                    loginStatus = "NOK";
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("username", String.valueOf(user));
            params.put("domain", String.valueOf(passwd));

            return params;
        }
    };
    queue.add(postRequest);

    if (loginStatus == "OK") {
        Intent intent = new Intent(LoginScreen.this, OptionScreen.class);
        startActivity(intent);
    } else {
        Toast.makeText(getApplicationContext(), "Login failed",Toast.LENGTH_SHORT).show();
    }
}

}

关于构造函数类,我冒昧地复制了代码,并添加了一些注释,说明我对其中每个部分的理解:

try {
// I have a TrustManagerFactory object
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// I have a KeyStore considering BKS (BOUNCY CASTLE) KeyStore object
KeyStore ks = KeyStore.getInstance("BKS");
// I have configured a inputStream using my TrustStore file as a Raw Resource
inStream = ctx.getApplicationContext().getResources().openRawResource(R.raw.mytruststore);
// I have loaded my Raw Resource into the KeyStore object
ks.load(inStream, null);
inStream.close();
// I have initialiazed my Trust Manager Factory, using my Key Store Object
tmf.init(ks);
// I have created a new SSL Context object
SSLContext sslContext = SSLContext.getInstance("TLS");
// I have initialized my new SSL Context, with the configured Trust Managers found on my Trust Store
sslContext.init(null, tmf.getTrustManagers(), null);
// I have configured a HttpClientStack, using my brand new Socket Context
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
hurlStack = new HurlStack(null, sslSocketFactory);
} catch (Exception e){
Log.d("Exception:",e.toString());
}

之后,在另一个类方法中,我有 RequestQueue,使用我在类构造函数上配置的 HttpClientStack:

RequestQueue queue = Volley.newRequestQueue(this, hurlStack);
final String url = "https://myserver.domain.com/app/login";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,new Response.Listener<String>()
    {
    ...
    ...
    }

当我运行我的应用程序并提供 Web 服务器所需的用户名和密码时,我可以在 Android Studio 的 Android 监视器中看到以下消息:

09-17 21:57:13.842 20617-20617/com.domain.myapp D/Error.Response: com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException:找不到证书路径的信任锚。

经过所有这些解释,我有以下问题:

  • 为了使 Android 接受来自我在类的构造函数中配置的自定义 TrustManager 的 CA 的 SSL 证书,还必须配置什么?

请原谅我,但我是 Android 编程和 Java 编程的初学者,所以也许,我犯了一个可怕的错误......

任何帮助将非常感激。

UPDATE

我改进了类的构造函数,对语句进行了更好的分组,并且还使用了密钥管理工厂,这似乎在这个过程中非常重要。开始:

public class LoginScreen extends AppCompatActivity {

...
...

  public LoginScreen() {

    try {
        inStream = this.getApplicationContext().getResources().openRawResource(R.raw.mytruststore);

        KeyStore ks = KeyStore.getInstance("BKS");
        ks.load(inStream, "bks*password".toCharArray());
        inStream.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(ks, "bks*password".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ks);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(),tmf.getTrustManagers(), null);
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        hurlStack = new HurlStack(null, sslSocketFactory);
    } catch (Exception e){
        Log.d("Exception:",e.toString());
    }

  }

...
...

}

无论如何,我还是有问题。。

响应:com.android.volley.NoConnectionError:javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚。


我通过以下代码在我的 volley 类中创建新的 requestQueue 来实现 https

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, newSslSocketFactory()));

    }

    return mRequestQueue;
}

private SSLSocketFactory newSslSocketFactory() {
    try {
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream in = getApplicationContext().getResources().openRawResource(R.raw.keystore);
        try {
            // Initialize the keystore with the provided trusted certificates
            // Provide the password of the keystore
            trusted.load(in, KEYSTORE_PASSWORD);
        } finally {
            in.close();
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trusted);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        SSLSocketFactory sf = context.getSocketFactory();
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用未知 CA 自签名的证书让 Android Volley 执行 HTTPS 请求? 的相关文章

随机推荐