我们是否需要创建任何证书才能在Android中调用https Web服务

时间:2014-10-05 12:10:40

标签: android ssl https ssl-certificate

您好我正在使用Android应用程序,我在所有Web服务中使用https协议。所以要从Android应用程序与https启用的服务器进行通信,我们是否需要在我的raw android文件夹中添加任何证书?

如果是,那么它的过程是什么。我检查了很多答案,但人们只是忽略了https procotol只接受所有证书或通过。

提前致谢。

1 个答案:

答案 0 :(得分:1)

  1. 创建BouncyCastle KeyStore,将证书放入其中(您可以使用openssl),稍后将创建的KeyStore放入res / raw文件夹。
  2. 在app中:

    1. 将您的密钥库文件加载到java KeyStore
    2. 使用HttpClient
    3. 提供KeyStore

      示例:

      // Load CAs from an InputStream
      // (could be from a resource or ByteArrayInputStream or ...)
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      // From https://www.washington.edu/itconnect/security/ca/load-der.crt
      InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
      Certificate ca;
      try {
          ca = cf.generateCertificate(caInput);
          System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
      } finally {
          caInput.close();
      }
      
      // Create a KeyStore containing our trusted CAs
      String keyStoreType = KeyStore.getDefaultType();
      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(null, null);
      keyStore.setCertificateEntry("ca", ca);
      
      // Create a TrustManager that trusts the CAs in our KeyStore
      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
      tmf.init(keyStore);
      
      // Create an SSLContext that uses our TrustManager
      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);
      
      // Tell the URLConnection to use a SocketFactory from our SSLContext
      URL url = new URL("https://certs.cac.washington.edu/CAtest/");
      HttpsURLConnection urlConnection =
          (HttpsURLConnection)url.openConnection();
      urlConnection.setSSLSocketFactory(context.getSocketFactory());
      InputStream in = urlConnection.getInputStream();
      copyInputStreamToOutputStream(in, System.out);
      

      源: https://developer.android.com/training/articles/security-ssl.html