public static SSLSocketFactory getPinnedCertSslSocketFactory(Context context,
                                                               int keyStoreRawResId,
                                                               String keyStorePassword) {
    InputStream in = null;
    try {
      // Get an instance of the Bouncy Castle KeyStore format
      KeyStore trusted = KeyStore.getInstance("BKS");

      // Get the keystore from raw resource
      in = context.getResources().openRawResource(keyStoreRawResId);
      // Initialize the keystore with the provided trusted certificates
      // Also provide the password of the keystore
      trusted.load(in, keyStorePassword.toCharArray());

      // Create a TrustManager that trusts the CAs in our KeyStore
      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
      tmf.init(trusted);

      // Create an SSLContext that uses our TrustManager
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, tmf.getTrustManagers(), null);

      return sslContext.getSocketFactory();
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (IOException e) {
        Logger.e(e.getMessage());
      }
    }
  }
public static SSLSocketFactory getPinnedCertSslSocketFactory ( Context context , int keyStoreRawResId , String keyStorePassword ) { InputStream in = null ; try { KeyStore trusted = KeyStore . getInstance ( "BKS" ) ; in = context . getResources ( ) . openRawResource ( keyStoreRawResId ) ; trusted . load ( in , keyStorePassword . toCharArray ( ) ) ; String tmfAlgorithm = TrustManagerFactory . getDefaultAlgorithm ( ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( tmfAlgorithm ) ; tmf . init ( trusted ) ; SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( null , tmf . getTrustManagers ( ) , null ) ; return sslContext . getSocketFactory ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { try { if ( in != null ) { in . close ( ) ; } } catch ( IOException e ) { Logger . e ( e . getMessage ( ) ) ; } } }
Helper method to create an {@link SSLSocketFactory} which trusts only given certificate

@return created specific factory