如何在Java密钥库中导入现有的x509证书和私钥以在SSL中使用?
我有这个在activemq配置
<sslContext> <sslContext keyStore="file:/home/alex/work/amq/broker.ks" keyStorePassword="password" trustStore="file:${activemq.base}/conf/broker.ts" trustStorePassword="password"/> </sslContext>
我有一对x509证书和一个密钥文件
如何导入这两个用于ssl和ssl + stomp连接器? 所有的例子,我可以谷歌总是自己生成密钥,但我已经有一个关键。
我努力了
keytool -import -keystore ./broker.ks -file mycert.crt
但是这只导入证书而不是密钥文件和结果
2009-05-25 13:16:24,270 [localhost:61612] ERROR TransportConnector - Could not accept connection : No available certificate or key corresponds to the SSL cipher suites which are enabled.
我已经尝试连接证书和密钥,但得到了相同的结果
我如何导入密钥?
不管你是否信任,keytool都不会提供像将私钥导入密钥库的基本功能。 您可以尝试将PKSC12文件与私钥合并到密钥库的解决方法 。
或者,只需使用IBM的更人性化的KeyMan进行密钥库处理,而不是使用keytool.exe。
我使用了以下两个步骤,在其他答案中链接的评论/帖子中找到:
第一步:将x509 Cert和Key转换为pkcs12文件
openssl pkcs12 -export -in server.crt -inkey server.key \ -out server.p12 -name [some-alias] \ -CAfile ca.crt -caname root
注意:确保你在p12文件上输入了一个密码 – 否则当你试图导入它的时候你会得到一个空引用异常。 (如果其他人有这个头痛)。 ( 谢谢jocull! )
注2:您可能需要添加-chain
选项以保留完整的证书链。 ( 谢谢Mafuba )
第二步:将pkcs12文件转换为java密钥库
keytool -importkeystore \ -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \ -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \ -alias [some-alias]
成品
可选步骤零,创建自签名证书
openssl genrsa -out server.key 2048 openssl req -new -out server.csr -key server.key openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
干杯!
Java 6中的Keytool确实具有以下功能: 使用keytool将私钥导入Java密钥库
以下是该帖子的基本细节。
-
使用OpenSSL将现有的证书转换为PKCS12。 询问时需要输入密码,否则第二步就会投诉。
openssl pkcs12 -export -in [my_certificate.crt] -inkey [my_key.key] -out [keystore.p12] -name [new_alias] -CAfile [my_ca_bundle.crt] – 扫描根目录
-
将PKCS12转换为Java密钥库文件。
keytool -importkeystore -deststorepass [new_keystore_pass] -destkeypass [new_key_pass] -destkeystore [keystore.jks] -srckeystore [keystore.p12] -srcstoretype PKCS12 -srcstorepass [pass_used_in_p12_keystore] -alias [alias_used_in_p12_keystore]
还有一个:
#!/bin/bash # We have: # # 1) $KEY : Secret key in PEM format ("-----BEGIN RSA PRIVATE KEY-----") # 2) $LEAFCERT : Certificate for secret key obtained from some # certification outfit, also in PEM format ("-----BEGIN CERTIFICATE-----") # 3) $CHAINCERT : Intermediate certificate linking $LEAFCERT to a trusted # Self-Signed Root CA Certificate # # We want to create a fresh Java "keystore" $TARGET_KEYSTORE with the # password $TARGET_STOREPW, to be used by Tomcat for HTTPS Connector. # # The keystore must contain: $KEY, $LEAFCERT, $CHAINCERT # The Self-Signed Root CA Certificate is obtained by Tomcat from the # JDK's truststore in /etc/pki/java/cacerts # The non-APR HTTPS connector (APR uses OpenSSL-like configuration, much # easier than this) in server.xml looks like this # (See: https://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html): # # <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" # SSLEnabled="true" # maxThreads="150" scheme="https" secure="true" # clientAuth="false" sslProtocol="TLS" # keystoreFile="/etc/tomcat6/etl-web.keystore.jks" # keystorePass="changeit" /> # # Let's roll: TARGET_KEYSTORE=/etc/tomcat6/foo-server.keystore.jks TARGET_STOREPW=changeit TLS=/etc/pki/tls KEY=$TLS/private/httpd/foo-server.example.com.key LEAFCERT=$TLS/certs/httpd/foo-server.example.com.pem CHAINCERT=$TLS/certs/httpd/chain.cert.pem # ---- # Create PKCS#12 file to import using keytool later # ---- # From https://www.sslshopper.com/ssl-converter.html: # The PKCS#12 or PFX format is a binary format for storing the server certificate, # any intermediate certificates, and the private key in one encryptable file. PFX # files usually have extensions such as .pfx and .p12. PFX files are typically used # on Windows machines to import and export certificates and private keys. TMPPW=$$ # Some random password PKCS12FILE=`mktemp` if [[ $? != 0 ]]; then echo "Creation of temporary PKCS12 file failed -- exiting" >&2; exit 1 fi TRANSITFILE=`mktemp` if [[ $? != 0 ]]; then echo "Creation of temporary transit file failed -- exiting" >&2; exit 1 fi cat "$KEY" "$LEAFCERT" > "$TRANSITFILE" openssl pkcs12 -export -passout "pass:$TMPPW" -in "$TRANSITFILE" -name etl-web > "$PKCS12FILE" /bin/rm "$TRANSITFILE" # Print out result for fun! Bug in doc (I think): "-pass " arg does not work, need "-passin" openssl pkcs12 -passin "pass:$TMPPW" -passout "pass:$TMPPW" -in "$PKCS12FILE" -info # ---- # Import contents of PKCS12FILE into a Java keystore. WTF, Sun, what were you thinking? # ---- if [[ -f "$TARGET_KEYSTORE" ]]; then /bin/rm "$TARGET_KEYSTORE" fi keytool -importkeystore \ -deststorepass "$TARGET_STOREPW" \ -destkeypass "$TARGET_STOREPW" \ -destkeystore "$TARGET_KEYSTORE" \ -srckeystore "$PKCS12FILE" \ -srcstoretype PKCS12 \ -srcstorepass "$TMPPW" \ -alias foo-the-server /bin/rm "$PKCS12FILE" # ---- # Import the chain certificate. This works empirically, it is not at all clear from the doc whether this is correct # ---- echo "Importing chain" TT=-trustcacerts keytool -import $TT -storepass "$TARGET_STOREPW" -file "$CHAINCERT" -keystore "$TARGET_KEYSTORE" -alias chain # ---- # Print contents # ---- echo "Listing result" keytool -list -storepass "$TARGET_STOREPW" -keystore "$TARGET_KEYSTORE"
是的,keytool没有导入私钥的功能的确是一个令人遗憾的事实。
为了记录,最后我去了这里描述的解决方案
在我的情况下,我有一个pem文件,其中包含两个证书和一个加密的私钥用于相互SSL认证。 所以我的文件看起来像这样:
-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9 ... -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----
这是我做的:
将文件分成三个单独的文件,每个文件只包含一个条目,从“— BEGIN ..”开始,以“— END ..”结尾。 让我们假设我们现在有三个文件:cert1.pem cert2.pem和pkey.pem
使用openssl和以下语法将pkey.pem转换为DER格式:
openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER
注意,如果私钥是加密的,你需要提供一个密码(从原pem文件的供应商处获得)以转换为DER格式,openssl会询问你这样的密码:“为pkey输入密码.pem:“如果转换成功,您将得到一个名为”pkey.der“的新文件
创建一个新的Java密钥库并导入私钥和证书:
String keypass = "password"; // this is a new password, you need to come up with to protect your java key store file String defaultalias = "importkey"; KeyStore ks = KeyStore.getInstance("JKS", "SUN"); // this section does not make much sense to me, // but I will leave it intact as this is how it was in the original example I found on internet: ks.load( null, keypass.toCharArray()); ks.store( new FileOutputStream ( "mykeystore" ), keypass.toCharArray()); ks.load( new FileInputStream ( "mykeystore" ), keypass.toCharArray()); // end of section.. // read the key file from disk and create a PrivateKey FileInputStream fis = new FileInputStream("pkey.der"); DataInputStream dis = new DataInputStream(fis); byte[] bytes = new byte[dis.available()]; dis.readFully(bytes); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); byte[] key = new byte[bais.available()]; KeyFactory kf = KeyFactory.getInstance("RSA"); bais.read(key, 0, bais.available()); bais.close(); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key ); PrivateKey ff = kf.generatePrivate (keysp); // read the certificates from the files and load them into the key store: Collection col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem")); Collection col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem")); Certificate crt1 = (Certificate) col_crt1.iterator().next(); Certificate crt2 = (Certificate) col_crt2.iterator().next(); Certificate[] chain = new Certificate[] { crt1, crt2 }; String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName(); String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName(); ks.setCertificateEntry(alias1, crt1); ks.setCertificateEntry(alias2, crt2); // store the private key ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain ); // save the key store to a file ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());
(可选)验证新密钥库的内容:
keytool -list -keystore mykeystore -storepass password
密钥库类型:JKS密钥库提供者:SUN
您的密钥库包含3个条目
cn = …,ou = …,o = ..,2014年9月2日,trustedCertEntry,证书指纹(SHA1):2C:B8:…
importkey,2014年9月2日,PrivateKeyEntry,证书指纹(SHA1):9C:B0:…
cn = …,o = ….,2014年9月2日,trustedCertEntry,证书指纹(SHA1):83:63:…
(可选)根据您的SSL服务器从您的新密钥库中测试您的证书和私钥:(您可能希望启用调试作为VM选项:-Djavax.net.debug = all)
char[] passw = "password".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(new FileInputStream ( "mykeystore" ), passw ); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passw); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); TrustManager[] tm = tmf.getTrustManagers(); SSLContext sclx = SSLContext.getInstance("TLS"); sclx.init( kmf.getKeyManagers(), tm, null); SSLSocketFactory factory = sclx.getSocketFactory(); SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 ); socket.startHandshake(); //if no exceptions are thrown in the startHandshake method, then everything is fine..
最后,如果打算使用它,请使用HttpsURLConnection注册您的证书:
char[] passw = "password".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(new FileInputStream ( "mykeystore" ), passw ); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passw); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); TrustManager[] tm = tmf.getTrustManagers(); SSLContext sclx = SSLContext.getInstance("TLS"); sclx.init( kmf.getKeyManagers(), tm, null); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) { System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'."); } return true; } }; HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() ); HttpsURLConnection.setDefaultHostnameVerifier(hv);
以前的答案正确地指出,只有通过将JKS文件转换为PKCS#12格式,才能使用标准的JDK工具执行此操作。 如果您有兴趣,我可以将一个紧凑的实用程序导入到JKS格式的密钥库中,而不必先将密钥库转换为PKCS#12: http : //commandlinefanatic.com/cgi-bin/showarticle。 CGI?文章= art049
你可以像这样使用链接的工具:
$ openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/CN=localhost"
(签署CSR,取回localhost.cer)
$ openssl rsa -in localhost.key -out localhost.rsa Enter pass phrase for localhost.key: writing RSA key $ java -classpath . KeyImport -keyFile localhost.rsa -alias localhost -certificateFile localhost.cer -keystore localhost.jks -keystorePassword changeit -keystoreType JKS -keyPassword changeit
基于上面的答案,这里是如何创建一个全新的密钥库为您的基于Java的Web服务器,从独立创建的Comodo证书和私钥使用keytool(需要JDK 1.6 +)
-
发出此命令并在密码提示符处输入somepass – 'server.crt'是您的服务器证书,'server.key'是您用于颁发CSR的私钥: openssl pkcs12 -export -in server.crt -inkey服务器。 key -out server.p12 -name http://www.yourdomain.com -CAfile AddTrustExternalCARoot.crt -caname“AddTrust External CA Root”
-
然后使用keytool将p12密钥库转换为jks密钥库: keytool -importkeystore -deststorepass somepass -destkeypass somepass -destkeystore keystore.jks -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass somepass
然后导入从Comodo收到的另外两个根/中级证书:
-
keytool -import -trustcacerts -alias cert1 -file COMODORSAAddTrustCA.crt -keystore keystore.jks
-
keytool -import -trustcacerts -alias cert2 -file COMODORSADomainValidationSecureServerCA.crt -keystore keystore.jks
首先转换为p12:
openssl pkcs12 -export -in [filename-certificate] -inkey [filename-key] -name [host] -out [filename-new-PKCS-12.p12]
从p12创建新的JKS:
keytool -importkeystore -deststorepass [password] -destkeystore [filename-new-keystore.jks] -srckeystore [filename-new-PKCS-12.p12] -srcstoretype PKCS12
以下是我将密钥导入到现有密钥库的步骤 – 从这里和其他地方的答案中得到的组合指令,以获得适用于我的Java密钥库的这些步骤:
- 跑
openssl pkcs12 -export -in yourserver.crt -inkey yourkey.key -out server.p12 -name somename -certfile yourca.crt -caname root
(如果需要的话,把-chain选项,把这个失败了)。 这将要求密码 – 你必须给出正确的密码,否则你会得到一个错误(标题错误或填充错误等)。
- 它会要求你输入一个新的密码 – 你必须在这里输入密码 – 输入任何东西,但记住它。 (让我们假设你进入阿拉贡)。
- 这将以pkcs格式创建server.p12文件。
- 现在将其导入
*.jks
文件运行:
keytool -importkeystore -srckeystore server.p12 -srcstoretype PKCS12 -destkeystore yourexistingjavakeystore.jks -deststoretype JKS -deststorepass existingjavastorepassword -destkeypass existingjavastorepassword
(非常重要 – 不要忽略deststorepass和destkeypass参数。)
5.它会询问您的src密码存储密码。 进入阿拉贡并打回车。 证书和密钥现在导入到您现有的Java密钥库中。