Andrei Manolache
Andrei Manolache

Reputation: 933

Add cert file in retrofit request

I'm trying to integrate a banking API in my mobile app (Android) and, being in sandbox mode, I have a public key (the certificate) and private key that should be on each request. In doc, this is how the request looks like:

curl -i -k --cert public.cert --cert-type PEM --key private.key --key-type PEM "endpoint.com" -H "Correlation-ID: OK1200" -H "WEB-API-Key: MY_API_KEY" -H "Authorization: Bearer MY_TOKEN"

So, being in sandbox mode, how should I add both private key and public key to my retrofit requests?

Upvotes: 1

Views: 1473

Answers (1)

Pavlo Ostasha
Pavlo Ostasha

Reputation: 16729

What you want to do is TLS(transport layer security) implementation. It is a usual procedure in terms of secure apps. If you are using OkHttp as your network client for Retrofit you will be able to do it relatively easily since OkHttp supports it out of the box. There are several options, one of which to do everything manually, but I would not recommend that. Instead, I would recommend okhttp-tls library which was done exactly for that. There may be some specifics, but generally, your code should look something like this:

// keyPair is a KeyPair(PublicKey, PrivateKey) where PublicKey and PrivateKey may be implemented via AndroidKeyStore
//certificate is X509Certificate which can bo obtained (X509Certificate)CertificateFactory.getInstance("X509").generateCertificate(assets.open("pathToCertificate.pem"))
HeldCertificate rootCertificate = HeldCertificate(keyPair, certificate);
HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()
    .addTrustedCertificate(rootCertificate.certificate())
    .build();
OkHttpClient client = new OkHttpClient.Builder()
    .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager())
    .build();

Upvotes: 1

Related Questions