Maciej Radzikowski
Maciej Radzikowski

Reputation: 2477

Extract certificate from SSLContext

I'm creating SSLContext in standard way:

The question is - how can I extract KeyStore and certificate data back from SSLContext? The task is to obtain fingerprint hash from certficate.

Is it even possible or I have to get it separately, reading certificate from file?

Upvotes: 4

Views: 4476

Answers (1)

always_a_rookie
always_a_rookie

Reputation: 4840

It can be done if you have a custom TrustManager. You can refer to this link for that custom class. Look for the private SavingTrustManager static class.

And the place where you are using the java's default TrustManager, use this class so that you can retrieve the certificate that the server sent.

SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(dummyTrustStore);

X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];

SavingTrustManager savingTrustManager = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { savingTrustManager }, null);
SSLSocketFactory factory = context.getSocketFactory();

And after you have started the handshake, you can get the certificates from the SavingTrustManager from the static member variable chain, like:

savingTrustManager.chain

Upvotes: 1

Related Questions