Java keytool从url/port添加服务器证书的简便方法

wun*_*tee 41 java keytool ssl-certificate

我有一个带有自签名证书的服务器,但也需要客户端证书身份验证.我正在尝试获取原始CA服务器证书,因此我可以将其导入密钥库.任何人都有一些关于如何轻松做到这一点的建议?谢谢.

dno*_*zay 79

在查看如何在使用jenkins cli时信任证书,并找到 https://issues.jenkins-ci.org/browse/JENKINS-12629,其中有一些配方.

这将为您提供证书:

openssl s_client -connect ${HOST}:${PORT} </dev/null
Run Code Online (Sandbox Code Playgroud)

如果您只对证书部分感兴趣,可以通过管道将其剪切为:

| sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
Run Code Online (Sandbox Code Playgroud)

并重定向到文件:

> ${HOST}.cert
Run Code Online (Sandbox Code Playgroud)

然后使用keytool导入它:

keytool -import -noprompt -trustcacerts -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}
Run Code Online (Sandbox Code Playgroud)

一气呵成:

HOST=myhost.example.com
PORT=443
KEYSTOREFILE=dest_keystore
KEYSTOREPASS=changeme

# get the SSL certificate
openssl s_client -connect ${HOST}:${PORT} </dev/null \
    | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert

# create a keystore and import certificate
keytool -import -noprompt -trustcacerts \
    -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

# verify we've got it.
keytool -list -v -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS} -alias ${HOST}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,KEYSTOREPASS =改变不是'changeme' (3认同)
  • 从 2012 年的 j7 开始,keytool(通常和 CertificateFactory)忽略证书的 PEM 文件中的无关文本,因此您不需要 sed。同样使用`-noprompt` _and_ `-storepass` 你可以在没有临时文件的情况下进行管道传输:`openssl s_client -connect host:port | keytool -import -noprompt -alias nm -keystore 文件 -storepass pw` (3认同)

wun*_*tee 22

我发现有几种方法可以做到这一点:

    java InstallCert [host]:[port] 
    keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert
    keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert


dav*_*085 6

我使用openssl,但是如果您不喜欢使用opensl,或者使用的是opensl,那么该系统(尤其是Windows)没有,因为2011年的java 7 keytool可以完成全部工作

 keytool -printcert -sslserver host[:port] -rfc >tempfile
 keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile 
 # or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
 keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]
Run Code Online (Sandbox Code Playgroud)

相反,对于Java 9 up up,以及在许多情况下,对于早期版本,Java可以将PKCS12文件用作密钥库而不是传统的JKS文件,并且OpenSSL可以在没有keytool的任何帮助的情况下创建PKCS12

openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options 
# including actual value, envvar, or file; see the openssl(1ssl) man page 
Run Code Online (Sandbox Code Playgroud)


Jon*_*man 4

您可以使用 Firefox 导出证书,该网站有说明。然后使用keytool添加证书。