I want help in getting the apt piece of code to get server certificates - valid and invalid , signed by CA and self signed. Any links and references will be highly appreciated.
I have a UNIX command which gives me what i want but I want the same output using Java. The command in UNIX is like this -
echo -n | openssl s_client -connect www.gmail.com:443 -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert
This returns the (dont know the encryption) chain of certificates on gmail. I want my java program to give the exact same information. Print the whole chain of certificates.
解决方案
This can be done using the following steps:
Initialise an SSLContext using a TrustManager that trusts anything (this use-case is one of the very few reasons to use such a trust manager). This is only if you suspect the remote cert won't be trusted.
Get an SSLSocketFactory from it.
Create an SSLSocket from this factory, using the host name you want to connect to. If you use the host name (and not an InetAddress), this will enable SNI on Java 7, so that would be the equivalent of using -servername as an additional option to your openssl command.
Start the handshake (e.g. with startHandhsake())
Get the SSLSession from this SSLSocket.
For each Certificate in getPeerCertificates():
Get its encoded value (as byte[]) using getEncoded()
Convert it into PEM, either:
Use BouncyCastle's PEMWriter.
Use a Base 64 encoder (e.g. Apache Commons), add the BEGIN/END delimiters and split the string with a new line every 64 characters.