问题
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