使用Trustkit与Google Cloud Endpoints实施SSL固定

时间:2018-02-21 10:40:39

标签: android google-app-engine google-cloud-endpoints pinning public-key-pinning

我正在使用Google Cloud Endpoints与我的Android应用的应用引擎后端进行互动。我想实现公钥/ SSL固定。对于Android N及更高版本,这很容易做到这一点,但我想为早期版本的Android实现固定。这似乎是一种常见的方法,使用Trustkit

Trustkit链接上的入门说明,通过设置SSLSocketFactory来描述如何设置它,例如

  // HttpsUrlConnection
  HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
  connection.setSSLSocketFactory(TrustKit.getInstance().getSSLSocketFactory(serverHostname));

  // OkHttp 2.x
  OkHttpClient client =
    new OkHttpClient()
        .setSSLSocketFactory(TrustKit.getInstance().getSSLSocketFactory(serverHostname));

但由于设置连接的方式,我不确定如何将其应用于Google Cloud Endpoints,例如,在我的代码中为Google Cloud Endpoints设置的方式

        import com.xxxx.backend.myApi.MyApi;

    //I believe the MyApi class is generated automatically as part of the Google Cloud Endpoints integration in Android Studio.

        class EndpointsAsyncTask  extends AsyncTask<HashMap, Void, String> {

        @Override
        protected String doInBackground(HashMap... params) {

        HashMap<String, String> dict = params[0];
        String data = dict.get("dataString");


         MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                                .setRootUrl("https://xxxxx").setApplicationName("xxxx");

        myApiService = builder.build();

        //This calls the API method
        return myApiService.customApiMethodName(data).execute().getDict().toString();
        }
        }

我想知道的是我如何在早期版本的Android中实现SSL固定,例如API16-API23仍在连接到Google Cloud Endpoints,就像我的应用程序一样,如上所示?

如果可能的话我想使用Trustkit,也许有不同的方法我可以设置如何连接我的Api方法,以便我可以使用它?如果这是不可能的,我可以使用Trustkit的替代方案吗?或者只是以一种完全不同的方式实现SSL固定,同时仍以这种方式使用Google Cloud Endpoints?

1 个答案:

答案 0 :(得分:2)

您必须停止使用AndroidHttp helper并根据它自行编写。

您必须使用其构建器,而不是仅调用new NetHttpTransport()new ApacheHttpTransport(),例如:

public static HttpTransport newCompatibleTransport(String hostname) {
  SSLSocketFactory factory = TrustKit.getInstance().getSSLSocketFactory(serverHostname);
  if (AndroidUtils.isMinimumSdkLevel(9)) {
    return new NetHttpTransport.Builder()
        .setSslSocketFactory(factory)
        .build();
  }
  return new ApacheHttpTransport.Builder()
      .setSslSocketFactory(factory)
      .build();
}