Extract certificate from SSLContext

别等时光非礼了梦想. 提交于 2020-04-11 04:44:07

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/40530117/extract-certificate-from-sslcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!