SMACK 4.2.4通过TLS与ejabberd连接

时间:2018-06-16 21:43:13

标签: android ejabberd smack

我一直在和ejabberd一起工作并且打了4.2.4。直到我从LetsEncrypt实施TLS证书才行。现在它给出了SSL握手错误。

如果我在连接配置中启用TLS,则相同的安全连接适用于iOS和其他客户端。

我搜索了但是可以找到任何想法如何解决这个问题。请帮助Android连接。

谢谢,

1 个答案:

答案 0 :(得分:0)

我花了时间,终于为我解决了这个问题。

configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
SSLContext sslContext = getSSLContext(context);
configBuilder.setCustomSSLContext(sslContext);


public SSLContext getSSLContext(Context context ) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        CertificateFactory cf = null;

        try {
            cf = CertificateFactory.getInstance("X.509");
        } catch (CertificateException e) {
            Log.e(TAG, e.getMessage());
        }

        InputStream in = context.getResources().openRawResource(R.raw.chain); // R.raw.chain is CA Root Certificate added in RAW resources folder

        InputStream caInput = new BufferedInputStream(in);
        Certificate ca = null;
        try {
            ca = cf.generateCertificate(caInput);
            Log.d(TAG, "ca=" + ((X509Certificate) ca).getSubjectDN());
        }
        catch (Exception e){
            Log.e(TAG, e.getMessage());
        }
        finally {
            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 = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        return sslContext;

    }