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

标签 android ssl https ssl-certificate

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

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

提前致谢。

最佳答案

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

在应用中:

  1. 将您的 keystore 文件加载到 java KeyStore
  2. 为您的 HttpClient 提供您的 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

关于android - 我们是否需要创建任何证书才能在 Android 中调用 https Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26202474/

相关文章:

c# - 上传捕获的图像进行解析(解析对象)

apache - 如何在本地轻松地通过 HTTPS 提供静态文件

ssl - IIS8 https 拒绝连接

c# - FTPS (SSL) 的证书验证/安装?

python - 是否可以在 Python 2.5 中使用 urllib2 通过身份验证代理获取 https 页面?

android - 任何适用于 Android 开发的 iOS Storyboard?

android - 警报管理器在特定时间设置每日警报?

android - bitmap.copy() 抛出内存不足错误

ssl - 如何在 Jetbrains Upsource 2.0 中启用 HTTPS

amazon-web-services - 如何在我的 AWS Elastic Beanstalk 环境中为解析服务器示例启用 HTTPS?