简体   繁体   English

如何在Android上为SSL套接字启用自签名证书?

[英]How to enable a self-signed certificate for SSL sockets on Android?

I have a self signed server certificate (cert.pem) and need to enable it for SSL sockets in an Android application. 我有自签名服务器证书(cert.pem),需要在Android应用程序中为SSL套接字启用它。 Ideally I'd like to package the code as .jar file and not need an external certificate file (ie include it into the code). 理想情况下,我想将代码打包为.jar文件,而不需要外部证书文件(即将其包含在代码中)。

With this code I can accept all certificates, which is not what I want: 使用此代码,我可以接受所有证书,这不是我想要的:

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager [] { new MyTrustManager() }, new SecureRandom());

Do I need to add the certificate to a custom KeyManager or the custom TrustManager? 我是否需要将证书添加到自定义KeyManager或自定义TrustManager?

One problem I've encountered is that Android does not accept JKS keystores (KeyStore.getDefaultType() returns "BKS"): " java.security.KeyStoreException: KeyStore JKS implementation not found " 我遇到的一个问题是Android不接受JKS密钥库(KeyStore.getDefaultType()返回“BKS”):“ java.security.KeyStoreException:找不到KeyStore JKS实现

Any ideas how to proceed would be highly appreciated! 任何想法如何进行将非常感谢!

Yes, you need to add the certificate to a custom KeyStore. 是的,您需要将证书添加到自定义KeyStore。 It is basically a 4-step process: 它基本上是一个分为四步的过程:

  1. Obtain your server certificate. 获取服务器证书。
  2. Import the server certificate to a keystore as a raw resource in your application. 将服务器证书作为应用程序中的原始资源导入密钥库。 The KeyStore type must be BKS. KeyStore类型必须是BKS。
  3. Create your own TrustManager in your Java/Android program to load the certificate into a SSLContext. 在Java / Android程序中创建自己的TrustManager,将证书加载到SSLContext中。
  4. Use that SSLContext for your SSL connections. 将SSLContext用于SSL连接。

See this link for detailed instructions and sample code: 有关详细说明和示例代码,请参阅此链接:
http://randomizedsort.blogspot.com/2010/09/step-to-step-guide-to-programming.html http://randomizedsort.blogspot.com/2010/09/step-to-step-guide-to-programming.html

Good luck. 祝好运。
Nehc Nehc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM