How to make https request with ssl certificate in "Retrofit"

I have a .p12 certificate file and I use SSL Converter to convert it to a .pem certificate file. Then I use this pem certificate file in my Android code like this:

OkHttpClient okHttpClient = new OkHttpClient(); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream instream = context.getResources().openRawResource(R.raw.pem_certificate); Certificate ca; ca = cf.generateCertificate(instream); KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType()); kStore.load(null, null); kStore.setCertificateEntry("ca", ca); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(kStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); okHttpClient.setSslSocketFactory(sslContext.getSocketFactory()); } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException | KeyManagementException e) { e.printStackTrace(); } baseURL = endpoint; RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(baseURL) .setClient(new OkClient(okHttpClient)) .build(); service = restAdapter.create(DishService.class); 

But this code does not work. It failed on the line "ca = cf.generateCertificate (instream)"; with the message CertificateException.

+6
source share
2 answers

Perhaps you have a problem in R.raw.pem_certificate ...

1) Try to get a raw open certificate from the server using openssl : openssl s_client -connect {HOSTNAME}: {PORT} -showcerts

(for more details see here https://superuser.com/questions/97201/how-to-save-a-remote-server-ssl-certificate-locally-as-a-file )

2) How to configure Retrofit2 using a special SSL certificate https://adiyatmubarak.wordpress.com/tag/add-ssl-certificate-in-retrofit-2/

or Retrofit1: https://number1.co.za/use-retrofit-self-signed-unknown-ssl-certificate-android/

PS: it works for me, please do not convert the PEM file to BKS.

+3
source

Try to answer in the link below that worked for me

Upgrade 2.3.0

Verify Self Signed SSL Certificate

0
source

Source: https://habr.com/ru/post/988916/


All Articles