2017-04-06 8 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 paramを追加してください)

私のテストサーバーはIPアドレスを使用していたため、自己署名証明書で動作するようにホスト名検証を無効にしなければなりませんでした。このother tutorialは役に立ちました。

カスタムHostnameVerifierでHttpsURLConnection.setDefaultHostnameVerifier()を追加し、newSslSocketFactory()に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); 
    } 
} 
関連する問題