自签名证书 - 未找到信任锚

时间:2015-08-31 04:27:20

标签: android ssl https self-signed

修改:评论中的BNK已链接到找到的解决方案here

我通过REST向后端服务器(通过LAN)发送POST请求,所有这些都是通过HTTPS完成的。这个服务器有一个自签名证书作为.pem文件,一切正常。

我现在正在尝试连接到不同的Web服务器(通过WAN,通过DNS),自签名证书,但作为.crt文件(标准,BER / DER格式)。但是现在,虽然代码是相同的,但我收到以下异常:

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

我不确定为什么一台服务器可以连接但另一台服务器没有。我不想信任所有证书,因为这将通过公共互联网。

我的网络代码:

public HttpsURLConnection setUpHttpsConnection(String urlString)
{
    try
    {
        // Load CAs from an InputStream
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        InputStream caInput = new BufferedInputStream(context.getAssets().open("server.crt"));
        Certificate ca = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((java.security.cert.X509Certificate) ca).getSubjectDN());

        // 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 = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        // Create all-trusting host name verifier
        //  to avoid the following :
        //   java.security.cert.CertificateException: No name matching
        // This is because Java by default verifies that the certificate CN (Common Name) is
        // the same as host name in the URL. If they are not, the web service client fails.
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        // Install it
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        // Tell the URLConnection to use a SocketFactory from our SSLContext
        URL url = new URL(urlString);
        HttpsURLConnection urlConnection = null;
        urlConnection = (HttpsURLConnection)url.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

        return urlConnection;
    }
    catch (Exception ex)
    {
        Log.e("NetworkManager", "Failed to establish SSL connection to server: " + ex.toString());
        return null;
    }
}

/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class POSTTask extends AsyncTask<POSTRequest, Void, StringBuilder>
{
    POSTTask()
    {
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected StringBuilder doInBackground(POSTRequest... params)
    {
        OutputStream os = null;

        try {
            HttpsURLConnection urlConnection = setUpHttpsConnection(params[0].url);
            //Sets the maximum time to wait for an input stream read to complete before giving up.
            urlConnection.setReadTimeout(30000);
            //Sets the maximum time in milliseconds to wait while connecting.
            urlConnection.setConnectTimeout(20000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params[0].nameValuePairs);
            os = urlConnection.getOutputStream();
            formEntity.writeTo(os);

            InputStream in = urlConnection.getInputStream();
            StringBuilder ret = inputStreamToString(in);

            return ret;

        } catch (IOException e) {
            Log.i("NetworkError", e.toString());
        } catch (Exception e) {

        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                }
            }
        }             
        return null;
    }

    @Override
    protected void onPostExecute(StringBuilder result) {
    }

    @Override
    protected void onCancelled() {
    }
}

1 个答案:

答案 0 :(得分:3)

如果我正确理解您对“所有信任”的想法,即代码中的主机名验证程序,您可以参考以下内容:

假设您的服务器应用程序在IIS中托管,其中包含"Issued to""localhost"的服务器证书。然后,在验证方法内,您可以验证"localhost"

HostnameVerifier hostnameVerifier = new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        HostnameVerifier hv =
            HttpsURLConnection.getDefaultHostnameVerifier();
        return hv.verify("localhost", session);
    }
};