当前位置: 首页 > 面试题库 >

Android通过SSL与Bouncy Castle进行服务器之间的通信

羊舌航
2023-03-14
问题内容

我知道这并不是一件容易的事,但是很遗憾,自昨天以来我一直被困在这里并与之抗争。我遵循了Android互助身份验证教程,将密钥库放置在资源中并尝试通过SSL连接到我的服务器,但是得到以下异常

java.lang.RuntimeException:org.spongycastle.jcajce.provider.asymmetric.x509.CertificateFactory
$ ExCertificateException

我将sslapptruststore.pfx文件放在下面res/raw/sslapptruststore.pfx 并使用了这段代码

try {

                           KeyStore clientCert = KeyStore.getInstance("PKCS12");
                                   clientCert.load(getResources().openRawResource(R.raw.sslapptruststore), "123456".toCharArray());// this line causes exception

                            HttpClient httpClient = null;
                            HttpParams httpParams = new BasicHttpParams();
                            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(clientCert, null, null);
                            SchemeRegistry registry = new SchemeRegistry();
                            registry.register(new Scheme("https", sslSocketFactory, 8443));
                            httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams);


                            HttpPost httpPost = new HttpPost(
                                    "https://192.168.1.113:8443/CertProvider");
                            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
                            nameValuePair.add(new BasicNameValuePair("csr", csr.toString()));

                            // Url Encoding the POST parameters
                                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

                            // Making HTTP Request
                            // HttpResponse response = null;
                            ResponseHandler<String> responseHandler = new BasicResponseHandler();
                            String response = "";
                            response = httpClient.execute(httpPost, responseHandler);
                                } catch (Exception e) {
                                    Log.e("", e.getMessage());
                                }

我也搜索过,但其他人正在使用.bks

任何帮助表示赞赏。


问题答案:

我添加了以下课程来解决该问题

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
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 java.util.ArrayList;
import java.util.Arrays;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * Allows you to trust certificates from additional KeyStores in addition to
 * the default KeyStore
 */
public class AdditionalKeyStoresSSLSocketFactory extends SSLSocketFactory{
    protected SSLContext sslContext = SSLContext.getInstance("TLSv1");

    public AdditionalKeyStoresSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(null, null, null, null, null, null);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());;
        keyManagerFactory.init(keyStore, "123456".toCharArray());
        sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[]{new AdditionalKeyStoresTrustManager(keyStore)}, null);
    }

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

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



    /**
     * Based on http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#X509TrustManager
     */
    public static class AdditionalKeyStoresTrustManager implements X509TrustManager {

        protected ArrayList<X509TrustManager> x509TrustManagers = new ArrayList<X509TrustManager>();


        protected AdditionalKeyStoresTrustManager(KeyStore... additionalkeyStores) {
            final ArrayList<TrustManagerFactory> factories = new ArrayList<TrustManagerFactory>();

            try {
                // The default Trustmanager with default keystore
                final TrustManagerFactory original = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                original.init((KeyStore) null);
                factories.add(original);

                for( KeyStore keyStore : additionalkeyStores ) {
                    final TrustManagerFactory additionalCerts = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    additionalCerts.init(keyStore);
                    factories.add(additionalCerts);
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }



            /*
             * Iterate over the returned trustmanagers, and hold on
             * to any that are X509TrustManagers
             */
            for (TrustManagerFactory tmf : factories)
                for( TrustManager tm : tmf.getTrustManagers() )
                    if (tm instanceof X509TrustManager)
                        x509TrustManagers.add( (X509TrustManager)tm );


            if( x509TrustManagers.size()==0 )
                throw new RuntimeException("Couldn't find any X509TrustManagers");

        }

        /*
         * Delegate to the default trust manager.
         */
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            final X509TrustManager defaultX509TrustManager = x509TrustManagers.get(0);
            defaultX509TrustManager.checkClientTrusted(chain, authType);
        }

        /*
         * Loop over the trustmanagers until we find one that accepts our server
         */
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for( X509TrustManager tm : x509TrustManagers ) {
                try {
                    tm.checkServerTrusted(chain,authType);
                    return;
                } catch( CertificateException e ) {
                    // ignore
                }
            }
            throw new CertificateException();
        }

        public X509Certificate[] getAcceptedIssuers() {
            final ArrayList<X509Certificate> list = new ArrayList<X509Certificate>();
            for( X509TrustManager tm : x509TrustManagers )
                list.addAll(Arrays.asList(tm.getAcceptedIssuers()));
            return list.toArray(new X509Certificate[list.size()]);
        }
    }

}


 类似资料:
  • 本文向大家介绍Android通过Socket与服务器之间进行通信的示例,包括了Android通过Socket与服务器之间进行通信的示例的使用技巧和注意事项,需要的朋友参考一下 一、首先进行Server的编写: 二、对客户端的编写,主要用用AIDL进行Server和Client AIDL 的编写主要为以下三部分: 1、创建 AIDL 1)、创建要操作的实体类,实现 Parcelable 接口,以便序

  • 我正在开发一个应用程序,需要在Windows/Linux/Mac计算机上建立一个服务器,该服务器需要通过现有的WiFi网络与Android/iOS设备通信。 我现在只是在研究阶段,虽然我可以找到在PC-Android、PC-iOS、iOS等之间交流的答案,但我找不到一个可以做到这一切的答案。 当然,这两个平台的移动应用程序是不同的,但是服务器应用程序最好是相同的,并且应该是跨平台的。我还应该提到服

  • 问题内容: 我的项目结构如下 我试图像这样从模块(即默认模块)导入, 但事实证明。但是我可以在内部实现相同的功能。请注意,我正在同时运行和文件。 问题答案: 部署后,GAE服务/模块不会在其模块目录(文件所在的目录)之外共享 任何内容。 因此,在dir(存在的地方)上方看不到任何东西,因此看不到。但是可以,因为模型位于其目录(存在)中。 如果需要,可以在内部进行符号链接,请参阅在App Engin

  • 我有一个关于SSLConnection的问题,在java中,我为客户端编写了下面的代码(这个应用程序必须连接到服务器,我有支持ssl的服务器),但我得到了这样的错误“javax.net.ssl.sslException:Connection Hays Shutdown:javax.net.ssl.sslhandShakeException:sun.security.validator.valida

  • 我的Vertx后端服务器无法通过WSL向同一台机器上运行的节点服务器(typescript)发送HTTP (GET)请求。然而,通过Postman,我能够向节点服务器发送HTTP (GET)请求。 我将提供一个最小的、可行的示例: 首先,localhost托管节点服务器,配置如下: index.ts: 后端服务器是一个Vertx服务器(Vertx 4.0.2),它使用Vertx Web客户端向“l

  • 我已经用自签名证书配置了Tomcat服务器(apache-Tomcat-9.0.1)。在此服务器上添加了所需的配置。xml,然后复制。jks文件在conf文件夹中。 使用SSL Stuff创建自签名证书配置Tomcat HTTPS按预期在浏览器上工作。 在进行HttpsURLConnection调用以获取REST API时禁用SSL验证 证书异常禁用证书异常 它起作用了- 在服务器上。xml-=仅