DjangoDev1
DjangoDev1

Reputation: 252

How to send certificate and private key separately in HttpUrlConnection and do I even need to send them?

I need to send the certificate along with a private key to an API endpoint. I can't do it using PKCS12 as they only accept PEM and DER format. Is there a way to send them using HttpsUrlConnection? For example, in curl this would be curl -k -X POST --key private.key --cert certificate.pem --url.

I am kinda new to all of this, so I am wondering if I should really send them in every request or should these be installed on the server and they'll be automatically sent when the API requests them.

For now, I have this snippet:

   URL url = new URL("endpoint");
   HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
   connection.setRequestMethod("POST");
   connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   connection.setDoOutput(true);

EDIT: This question shouldn't be closed because Innovationchef provided a really good explanation of mutual TLS that is not explained in the other similar question.

Upvotes: 0

Views: 1663

Answers (1)

Innovationchef
Innovationchef

Reputation: 388

Private keys are never sent. Since you are owning a private key, I will assume we are talking about mutual TLS here.

In this case, both parties have there private keys with them and it is called private because you neve share it with anyone.

Public keys are exchanged between you and your api server.

  1. Now, all you need to do is setup a SSLContext object by passing your private key and the server's public key.
  2. Provide this object while creating the connection object.
  3. Then Java will create a secured socket object for you and the TLS handshake will happen. Everything is taken care by the libraries and java ecosystem and you don't have to worry about how the certificates are exchanged.

Once the handshake is done, a connection is established and the payloads that you are sending will be encrypted.

I would suggest you add a -v switch to your curl and see the whole process happening on the bash command line. Java does the same things but with the SSLContext object.

Look at the first diagram on this link - https://docs.oracle.com/cd/E19226-01/820-7627/bncbs/index.html

When you run your curl in verbose mode, you will see all these steps being printed in the exact same order. SSLContext is a way of expressing --key private.key --cert certificate.pem in java.

Upvotes: 3

Related Questions