Following up on my earlier post about using keytool to import and export certificates into a keystore. Here is some more information on using openssl to download the certificate from a remote server and then using keytool to import it into the keystore.
keytool needs the certificate to be in X509 format, so we will use sed to format the certificate.
echo -n | openssl s_client -connect HOST:PORTNUMBER | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert
breaking down the command
send an end of line signal to openssl. This allows openssl (or rather the server it is trying to connect to) to disconnect the session
openssl s_client -connect HOST:PORTNUMBER
asks openssl to act as a client and connect to the HOST on the specificed PORTNUMBER
sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
asks sed to take the input from openssl and only output the content between BEGIN CERTIFICATE and END CERTIFICATE.
NOTE: If you get an error like “SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert unexpected message”, it means the server doesn’t support SSL negotation. Using the command option -no_tls1 helps work around this error. This option will tell openssl to disable TLS1 negotiation.