HTTPS connection with client certificate in an android app

后端 未结 5 1282
無奈伤痛
無奈伤痛 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条回答
  •  悲&欢浪女
    2020-12-13 10:00

    There's a simpler way to implement @jglouie 's solution. Basically, if you use a SSLContext and initialize it with null for the trust manager parameter, you should get a SSL context using the default trust manager. Note that this is not documented in the Android documentation, but the Java documentation for SSLContext.init says

    Either of the first two parameters may be null in which case the installed security providers will be searched for the highest priority implementation of the appropriate factory.

    Here's what the code would look like:

    // This can be any protocol supported by your target devices.
    // For example "TLSv1.2" is supported by the latest versions of Android
    final String SSL_PROTOCOL = "TLS";
    
    try {               
       sslContext = SSLContext.getInstance(SSL_PROTOCOL);
    
       // Initialize the context with your key manager and the default trust manager 
       // and randomness source
       sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
    } catch (NoSuchAlgorithmException e) {
       Log.e(TAG, "Specified SSL protocol not supported! Protocol=" + SSL_PROTOCOL);
       e.printStackTrace();
    } catch (KeyManagementException e) {
       Log.e(TAG, "Error setting up the SSL context!");
       e.printStackTrace();
    }
    
    // Get the socket factory
    socketFactory = sslContext.getSocketFactory();
    

提交回复
热议问题