且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CertPathValidatorException:信任锚证书路径未找到 - 改造Android的

更新时间:2021-09-07 21:48:42

好了,我懂了工作使用的 Android开发者指南

Okay, I got it working using Android Developers guide.

正如OP,我试图使用改造 OkHttp 连接到一个自签名的SSL功能的服务器。

Just as OP, I'm trying to use Retrofit and OkHttp to connect to a self-signed SSL-enabled server.

下面是该得到的东西的工作(我已经删除了try / catch块)的code:

Here's the code that got things working (I've removed the try/catch blocks):

public static RestAdapter createAdapter(Context context) {
  OkHttpClient okHttpClient = new OkHttpClient();

  // loading CAs from an InputStream
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  InputStream cert = context.getResources().openRawResource(R.raw.my_cert);
  Certificate ca;
  try {
    ca = cf.generateCertificate(cert);
  } finally { cert.close(); }

  // creating a KeyStore containing our trusted CAs
  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  // creating a TrustManager that trusts the CAs in our KeyStore
  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  tmf.init(keyStore);

  // creating an SSLSocketFactory that uses our TrustManager
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, tmf.getTrustManagers(), null);
  okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

  // creating a RestAdapter using the custom client
  return new RestAdapter.Builder()
              .setEndpoint(UrlRepository.API_BASE)
              .setClient(new OkClient(okHttpClient))
              .build();
}

要帮助调试,我还添加了 .setLogLevel(RestAdapter.LogLevel.FULL)来我RestAdapter创建命令,我可以看到它的连接,并获得从响应服务器。

To help in debugging, I also added .setLogLevel(RestAdapter.LogLevel.FULL) to my RestAdapter creation commands and I could see it connecting and getting the response from the server.

时采取了我原来的 .CRT 保存在文件主/ RES /生。 在 .CRT 文件,又名证书,是创建的两个文件之一,当您创建使用证书的OpenSSL 。通常,它是一个.CRT或.cert文件,而另一个是一个.key文件。

All it took was my original .crt file saved in main/res/raw. The .crt file, aka the certificate, is one of the two files created when you create a certificate using openssl. Generally, it is a .crt or .cert file, while the other is a .key file.

AFAIK,.CRT文件是以您的公钥和.key文件是你的私钥。

Afaik, the .crt file is your public key and the .key file is your private key.

正如我所看到的,您已经有了一个 .cert 文件,尝试使用它。

As I can see, you already have a .cert file, try to use it.

对于那些读它的未来,只有有一个.pem文件,根据这个答案,你只需要这个转换一个到另一个:

For those that read it in the future and only have a .pem file, according to this answer, you only need this to convert one to the other:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

请接受这个答案,如果你的作品。 :)

Please accept this answer if it works for you. :)