Wael

How to connect to a server with a self signed certificate from android using 5222 port

Discussion created by Wael on Apr 14, 2015
Latest reply on Apr 17, 2015 by Wael

Put your certificate into the asset folder (***.crt). Just download it using Firefox when you enter your domain via https

then use the following code

.

.

.

XMPPTCPConnectionConfiguration   config  = XMPPTCPConnectionConfiguration.builder()

        .setHost(HOST)

        .setPort(PORT) // default 5222

        .setServiceName(SERVECE_NAME) // usually the same as your server name

        .setCustomSSLContext(getSSLContext())

        .setResource(RESOURCE)

        .setUsernameAndPassword(USERNAME, PASSWORD)

        .setCompressionEnabled(true)

        .setSecurityMode(ConnectionConfiguration.SecurityMode.required)

        .setDebuggerEnabled(true)

        .setSendPresence(false).build();

.

.

.

 

public  SSLContext getSSLContext (){

   CertificateFactory cf = null;

   SSLContext context= null;

   try {

            cf = CertificateFactory.getInstance("X.509");

 

            InputStream caInput = new BufferedInputStream((application or activity Context).getAssets().open("***.crt"));

            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();

            KeyStore keyStore = KeyStore.getInstance(keyStoreType);

            keyStore.load(null, null);

            keyStore.setCertificateEntry("ca", ca);

 

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);

            tmf.init(keyStore);

 

             // Create an SSLContext that uses our TrustManager
            context = SSLContext.getInstance("TLS");

            context.init(null, tmf.getTrustManagers(), null);

 

  } catch (CertificateException e) {

            e.printStackTrace();

  } catch (KeyManagementException e) {

            e.printStackTrace();

  } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

  } catch (KeyStoreException e) {

            e.printStackTrace();

  } catch (IOException e) {

            e.printStackTrace();

  }

   return context;

}

 

Resources: CertificateFactory (Java Platform SE 7 )

Outcomes