【问题标题】:Do we need to create any certificate to call https web service in Android我们是否需要创建任何证书才能在 Android 中调用 https 网络服务
【发布时间】:2014-10-05 12:10:40
【问题描述】:

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

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

提前致谢。

【问题讨论】:

  • 你说的是访问令牌吗?
  • 没有。我说的是 ssl 证书 *.cert 文件

标签: android ssl https ssl-certificate


【解决方案1】:
  1. 创建 BouncyCastle KeyStore,将证书放入其中(可以使用 openssl),稍后将创建的 KeyStore 放入 res/raw 文件夹。

应用内:

  1. 将您的密钥库文件加载到 java KeyStore
  2. 用你的KeyStore 喂你的HttpClient

例子:

// 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

【讨论】:

  • 我是否也必须使用相同生成的 KeyStore 证书到服务器?
  • 我不知道你在问什么
  • 我要求这个过程我们必须将证书文件保存在 android 项目的 rawassests 中,以便与服务器建立 https 连接,我们还必须将相同的证书文件保存到服务器我们在android中有哪些?
  • 看这里:stackoverflow.com/questions/188266/…,唯一的区别是您(应用程序,在该链接中充当网络浏览器)不下载证书 - 您将证书与您的应用程序一起提供。
  • 所以根据那个答案,这意味着你不必创建任何证书,也不需要添加android客户端,但你告诉了这个Create BouncyCastle KeyStore, put your certificate in it (you can use openssl), later put created KeyStore into res/raw folder.。现在我很困惑:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 2016-08-20
  • 2019-08-07
  • 2014-08-28
相关资源
最近更新 更多