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.
[code]echo -n | openssl s_client -connect HOST:PORTNUMBER | sed -ne ‘/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p’ > /tmp/$SERVERNAME.cert [/code]
breaking down the command
[code]echo -n[/code]
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
[code]openssl s_client -connect HOST:PORTNUMBER[/code]
asks openssl to act as a client and connect to the HOST on the specificed PORTNUMBER
[code]sed -ne ‘/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p’ [/code]
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.