HTTPS connection with client certificate in an android app

后端 未结 5 1283
無奈伤痛
無奈伤痛 2020-12-13 09:28

I am trying to replace the currently working HTTP connection with a HTTPS connection in a Android app that I am writing. The additional security of a HTTPS connection is nec

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 10:04

    I think this is indeed the issue.

    The first possibility, as far as I can tell, is that I need to configure this SSLSocketFactory with the devices' truststore that includes all of the standard Intermediate and endpoint Certificate Authorities

    If this is true, how would I best go about loading this data?

    Try something like this (you'll need to get your socket factory to use this default trust manager):

    X509TrustManager manager = null;
    FileInputStream fs = null;
    
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    
    try
    {
        fs = new FileInputStream(System.getProperty("javax.net.ssl.trustStore")); 
        keyStore.load(fs, null);
    }
    finally
    {
        if (fs != null) { fs.close(); }
    }
    
    trustManagerFactory.init(keyStore);
    TrustManager[] managers = trustManagerFactory.getTrustManagers();
    
    for (TrustManager tm : managers)
    {
        if (tm instanceof X509TrustManager) 
        {
            manager = (X509TrustManager) tm;
            break;
        }
    }
    

    EDIT: Please look at Pooks' answer before using the code here. It sounds like there's a better way to do this now.

提交回复
热议问题