简体   繁体   中英

Extract certificate from SSLContext

I'm creating SSLContext in standard way:

  • take .p12 certificate file,
  • create KeyStore and load certificate into it,
  • create KeyManagerFactory, init it with KeyStore, and get KeyManagers,
  • create TrustManagerFactory, init it with null, and get TrustManagers.
  • create SSLContext and init it with KeyManagers and TrustManagers.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM