2017-04-06 177 views
0

我試圖從我的android應用程序訪問HTTPS url。 我有我的服務器端的自簽名證書(server_certificate.cer)。Android Volley自簽名證書

我想知道如何將自簽名證書添加到抽籤網絡請求以信任我的自簽名證書。 與http://blog.applegrew.com/2015/04/using-pinned-self-signed-ssl-certificate-with-android-volley/

嘗試並獲取javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:未找到證書路徑的信任錨點。

回答

0

我成功地遵循了該教程。

您需要創建一個密鑰庫文件(例如「cert_keystore.pkcs12」)來包含您的服務器證書並將其添加到您的應用程序中。

我發現它最容易使用密鑰庫文件的PKCS12格式。 (在使用keytool轉換密鑰庫時添加-deststoretype PKCS12參數)

我的測試服務器在IP地址上,我必須禁用主機名驗證才能使用我的自簽名證書。這other tutorial是有用的。

我不得不將HttpsURLConnection.setDefaultHostnameVerifier()添加到newSslSocketFactory()的自定義HostnameVerifier和HttpsURLConnection.setDefaultSSLSocketFactory()

(newSslSocketFactory()中Volley.newRequestQueue(mCtx.getApplicationContext(), new HurlStack(null, newSslSocketFactory())使用)

新newSslSocketFactory()現在函數爲:

private SSLSocketFactory newSslSocketFactory() 
{ 
    try 
    { 
     KeyStore trusted = KeyStore.getInstance ("PKCS12"); 

     // Get the raw resource, which contains the keystore with 
     // your trusted certificates (root and any intermediate certs) 
     InputStream in = mCtx.getApplicationContext().getAssets().open ("cert_keystore.pkcs12"); 
     try { 
      // Initialize the keystore with the provided trusted certificates 
      // Provide the password of the keystore 
      trusted.load (in, "password".toCharArray()); 
     } finally { 
      in.close(); 
     } 

     String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); 
     TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); 
     tmf.init(trusted); 


     HostnameVerifier hostnameVerifier = new HostnameVerifier() { 
      @Override 
      public boolean verify (String hostname, SSLSession session) { 

       return hostname.equals ("192.168.1.10"); //The Hostname of your server 

      } 
     }; 


     HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); 


     SSLContext context = SSLContext.getInstance("TLS"); 
     context.init(null, tmf.getTrustManagers(), null); 

     SSLSocketFactory sf = context.getSocketFactory(); 
     HttpsURLConnection.setDefaultSSLSocketFactory (sf); 

     return sf; 
    } 
    catch (Exception e) 
    { 
     throw new AssertionError(e); 
    } 
}