Java Keytool 创建可信的自签名证书

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2200176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:40:08  来源:igfitidea点击:

Keytool create a trusted self signed certificate

javaweb-servicescertificatessl-certificatekeytool

提问by sixtyfootersdude

I am trying to use the (java) keytool to create a self signed certificate but when I attempt to use it I get the following exception (see bottom for entire exception).

我正在尝试使用 (java) keytool 创建一个自签名证书,但是当我尝试使用它时,我得到以下异常(整个异常请参见底部)。

...<5 more exceptions above this>
Caused by: sun.security.validator.ValidatorException: No trusted certificate found
        at sun.security.validator.SimpleValidator.buildTrustedChain(SimpleValidator.java:304)
        at sun.security.validator.SimpleValidator.engineValidate(SimpleValidator.java:107)
        at sun.security.validator.Validator.validate(Validator.java:203)
        at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
        at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:841)
        ... 22 more

I know that I can by-pass this with this code:

我知道我可以使用以下代码绕过它:

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

HostnameVerifier hv = new HostnameVerifier() {
    public boolean verify(String urlHostName, SSLSession session) {
        System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
        return true;
    }
};

HttpsURLConnection.setDefaultHostnameVerifier(hv);

(source)

(来源)

But I am not interested in this solutions because I think that it creates a security hole. (please correct me if I am wrong).

但我对这个解决方案不感兴趣,因为我认为它会造成一个安全漏洞。(如果我错了,请纠正我)。

Can anyone point me in the right direction? I am testing locally at the moment right now so it is pretty easy to change things. I have access to the server code, client code and to the .keystore file.

任何人都可以指出我正确的方向吗?我现在正在本地测试,所以很容易改变。我可以访问服务器代码、客户端代码和 .keystore 文件。

Update

更新

I was attempting to use one .keystore file for both the client and server but in hopes of simplifying my issues I have created server.keystore (see below) and client.truststore (see below). I am reasonably confident that the certicates are correct but if someone could verify I would be grateful.

我试图为客户端和服务器使用一个 .keystore 文件,但为了简化我的问题,我创建了 server.keystore(见下文)和 client.truststore(见下文)。我有理由相信证书是正确的,但如果有人可以验证,我将不胜感激。

server.keystore

服务器.keystore

hostname[username:/this/is/a/path][711]% keytool -list -keystore server.keystore -v
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: hostname
Creation date: Feb 4, 2010
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname
Issuer: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname
Serial number: 4b6b0ea7
Valid from: Thu Feb 04 13:15:03 EST 2010 until: Wed May 05 14:15:03 EDT 2010
Certificate fingerprints:
         MD5:  81:C0:3F:EC:AD:5B:7B:C4:DA:08:CC:D7:11:1F:1D:38
         SHA1: F1:78:AD:C8:D0:3A:4C:0C:9A:4F:89:C0:2A:2F:E2:E6:D5:13:96:40
         Signature algorithm name: SHA1withDSA
         Version: 3


*******************************************
*******************************************

client.truststore

客户端信任库

hostname[username:/this/is/a/path][713]% keytool -list -keystore client.truststore -v
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: mykey
Creation date: Feb 4, 2010
Entry type: trustedCertEntry

Owner: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname
Issuer: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname
Serial number: 4b6b0ea7
Valid from: Thu Feb 04 13:15:03 EST 2010 until: Wed May 05 14:15:03 EDT 2010
Certificate fingerprints:
         MD5:  81:C0:3F:EC:AD:5B:7B:C4:DA:08:CC:D7:11:1F:1D:38
         SHA1: F1:78:AD:C8:D0:3A:4C:0C:9A:4F:89:C0:2A:2F:E2:E6:D5:13:96:40
         Signature algorithm name: SHA1withDSA
         Version: 3


*******************************************
*******************************************

Update

更新

I thought it could be useful to include the entire exception:

我认为包含整个异常可能很有用:

javax.xml.soap.SOAPException: java.io.IOException: Could not transmit message
        at org.jboss.ws.core.soap.SOAPConnectionImpl.callInternal(SOAPConnectionImpl.java:115)
        at org.jboss.ws.core.soap.SOAPConnectionImpl.call(SOAPConnectionImpl.java:66)
        at com.alcatel.tpapps.common.utils.SOAPClient.execute(SOAPClient.java:193)
        at com.alcatel.tpapps.common.utils.SOAPClient.main(SOAPClient.java:280)
Caused by: java.io.IOException: Could not transmit message
        at org.jboss.ws.core.client.RemotingConnectionImpl.invoke(RemotingConnectionImpl.java:192)
        at org.jboss.ws.core.client.SOAPRemotingConnection.invoke(SOAPRemotingConnection.java:77)
        at org.jboss.ws.core.soap.SOAPConnectionImpl.callInternal(SOAPConnectionImpl.java:106)
        ... 3 more
Caused by: org.jboss.remoting.CannotConnectException: Can not connect http client invoker. sun.security.validator.ValidatorException: No trusted certificate found.
        at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:368)
        at org.jboss.remoting.transport.http.HTTPClientInvoker.transport(HTTPClientInvoker.java:148)
        at org.jboss.remoting.MicroRemoteClientInvoker.invoke(MicroRemoteClientInvoker.java:141)
        at org.jboss.remoting.Client.invoke(Client.java:1858)
        at org.jboss.remoting.Client.invoke(Client.java:718)
        at org.jboss.ws.core.client.RemotingConnectionImpl.invoke(RemotingConnectionImpl.java:171)
        ... 5 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found
        at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1584)
        at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
        at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:848)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
        at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
        at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:877)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1089)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1116)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1100)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:857)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
        at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:288)
        ... 10 more
Caused by: sun.security.validator.ValidatorException: No trusted certificate found
        at sun.security.validator.SimpleValidator.buildTrustedChain(SimpleValidator.java:304)
        at sun.security.validator.SimpleValidator.engineValidate(SimpleValidator.java:107)
        at sun.security.validator.Validator.validate(Validator.java:203)
        at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
        at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:841)
        ... 22 more

采纳答案by Armadillo

You would need to "establish trust" between your server and client (I'm assuming you only need to do server-side authentication). This is because you use self-signed certs. That involves importing your server's cert into the client trust store:

您需要在服务器和客户端之间“建立信任”(我假设您只需要进行服务器端身份验证)。这是因为您使用自签名证书。这涉及将服务器的证书导入客户端信任库:

On the server side:

在服务器端:

keytool -keystore <keystore file> -alias <alias> -export -file <certfilename>.cert

Copy the .cert file over to the client side and then:

将 .cert 文件复制到客户端,然后:

keytool -keystore <truststore file> -alias <alias> -import -file <certfilename>.cert

回答by Pascal Thivent

I don't get it. Are you using the server key store with the client? What is your use case exactly? Are you trying to setup mutual authentication?

我不明白。您是否在客户端使用服务器密钥库?你的用例到底是什么?您是否正在尝试设置相互身份验证?

If yes, you're on the wrong path here. You'll need a client key store (for the client's self-signed certificate and private key) and a client trust store (for the server's "stand-alone" self-signed certificate i.e. without its private key). Both are different from the server key store.

如果是,那么您在这里走错了路。您需要一个客户端密钥库(用于客户端的自签名证书和私钥)和一个客户端信任库(用于服务器的“独立”自签名证书,即没有其私钥)。两者都不同于服务器密钥库。

回答by user207421

You mustn't do that. A keystore is strictly private. If you leak it to anybody you have fatally compromised security. There is no point in doing this kind of thing just to get it working, because it isn'tworking - it is just a security breach. You have to do it right: export from the server's keystore into the client's truststore, and from the client's keystore if any to the server's keystore.

你不应该那样做。密钥库是严格私有的。如果你把它泄露给任何人,你就会严重损害安全性。有一个在做这种只是为了得到它的工作的事情没有意义的,因为它工作-它只是一个安全漏洞。您必须正确执行:从服务器的密钥库导出到客户端的信任库,并从客户端的密钥库(如果有)导出到服务器的密钥库。

回答by Laurent Caillette

You can't share the keystore between client and server, because the keystore contains the private key. When authenticating, the client skips the certificates with private keys. As said above you need to deploy a truststore on client side.

您不能在客户端和服务器之间共享密钥库,因为密钥库包含私钥。进行身份验证时,客户端会跳过带有私钥的证书。如上所述,您需要在客户端部署信任库。

The certificates in a keystore don't behave the same way, depending on how you generated or imported them.

密钥库中的证书的行为方式不同,具体取决于您生成或导入它们的方式。

An imported certificate's entry type (seen when verbosely listing the whole keystore with -list -v) is "trustedCertEntry". A generated certificate's entry type is "PrivateKeyEntry". When you export a certificate, you only export its public key, and an optional reference to its issuer.

导入证书的条目类型(在使用 详细列出整个密钥库时可见-list -v)是“trustedCertEntry”。生成的证书的条目类型是“PrivateKeyEntry”。导出证书时,您只导出其公钥,以及对其颁发者的可选引用。

Seems like you need to export the self-signed certificate in your keystore as a trusted certificate in your truststore (names make sense here).

似乎您需要将密钥库中的自签名证书导出为信任库中的受信任证书(名称在这里有意义)。

I wouldn't do that, because SSL/TLS implementations probably don't support it. From a real world perspective it's like deploying the ultimately secret private key from Verisign on some obscure Web server to sign casual pages, while the only purpose of this private key is to remain in a safe and sign other certificates. SSL/TLS implementors probably won't pollute their code with such a use case, and anyways, the "KeyUsage" certificate extension may restrict a certificate usage to signing, preventing encipherment.

我不会这样做,因为 SSL/TLS 实现可能不支持它。从现实世界的角度来看,这就像在某个不起眼的 Web 服务器上部署来自 Verisign 的最终秘密私钥来签署临时页面,而此私钥的唯一目的是留在保险箱中并签署其他证书。SSL/TLS 实现者可能不会用这样的用例污染他们的代码,无论如何,“KeyUsage”证书扩展可能会将证书使用限制为签名,从而防止加密。

That's why I suggest to rebuild a chain of certificates for your test.

这就是为什么我建议为您的测试重建一系列证书。

The keytool documentation contains an interesting part about creating a chain (-gencertcommand) but it's a very skeletal example which doesn't cover the keystore-truststore relationship. I've enhanced it to simulate a third-party certification authority.

keytool 文档包含一个关于创建链(-gencert命令)的有趣部分,但它是一个非常简单的示例,不包括密钥库-信任库关系。我已经对其进行了增强以模拟第三方证书颁发机构。

A temporary store their-keystore.jksrepresents a certificate-emitting authority. I feed it with a certificate chain of ca2 -> ca1 -> cawith cabeing considered as a root certificate. The chain appears with each non-root certificate (namely ca1and ca2) referencing their issuer as Certificate[2]. Please note that every certificate is "PrivateKeyEntry".

临时存储their-keystore.jks代表证书颁发机构。我用的证书链给它ca2 -> ca1 -> caca被视为根证书。该链与每个非根证书(即ca1ca2)一起出现,将其颁发者称为Certificate[2]。请注意,每个证书都是“PrivateKeyEntry”。

Then I feed the my-keystore.jkswith those certificates in order: ca, ca1, ca2. I import cawith the -trustcacertsoption which means it becomes a root certificate. In my-keystore.jkseach imported certificate now is "trustedCertEntry" which means there is only the public key. The issuing relationship only appears in the "Issuer" field but it's OK because the trust relationship mattered most at the time of the import.

然后我my-keystore.jks按顺序提供这些证书:ca, ca1, ca2。我ca使用-trustcacerts选项导入,这意味着它成为根证书。my-keystore.jks现在在每个导入的证书中都是“trustedCertEntry”,这意味着只有公钥。发行关系仅出现在“发行人”字段中,但没关系,因为信任关系在导入时最为重要。

At this point my-keystore.jkssimulates an environment containing some trusted certificates, like a fresh JRE. The their-keystore.jkssimulates the owners of those certificates, who have the power to sign certificate requests.

此时my-keystore.jks模拟包含一些受信任证书的环境,如新的 JRE。该their-keystore.jks模拟这些证书,谁必须签署证书请求动力的车主。

So do I : I create a self-signed certificate e1in my-keystore.jks, get it signed by ca2(through their-keystore.jks) and import the signed result back into my-keystore.jks. e1is still a "PrivateKeyEntry" (because its private key remains in my-keystore.jks) but now I've built the following chain : e1 -> ca2 -> ca1. It seems that ca1 -> cais implicit with cabeing a certification authority.

所以,做我:我创建了一个自签名的证书e1my-keystore.jks,得到它签署了ca2(通过their-keystore.jks),并导入签名结果回my-keystore.jkse1仍然是“PrivateKeyEntry”(因为它的私钥保留在 中my-keystore.jks)但现在我已经构建了以下链:e1 -> ca2 -> ca1。作为认证机构,这似乎ca1 -> ca是隐含的ca

To build the truststore I just import certificates ca, ca1and ca2the same way I did for my-keystore.jks. Please note I don't import e1, as I expect the SSL/TLS client to validate it against ca2.

为了建立信任我刚刚导入证书caca1ca2以同样的方式我做了my-keystore.jks。请注意,我不导入e1,因为我希望 SSL/TLS 客户端根据ca2.

I think this gets rather close of how things work in real world. What's nice here is you have full control on the certificates, and no dependency on JRE's cacerts.

我认为这与现实世界中的工作方式非常接近。这里的好处是您可以完全控制证书,并且不依赖于 JRE 的 cacerts。

Here is the code putting what I say in practice. Seems to work with Jetty (client and server) as long as you disable certificate revocation list (a topic left for another day).

这是将我所说的付诸实践的代码。只要您禁用证书吊销列表(该主题留待改天),似乎就可以与 Jetty(客户端和服务器)一起使用。

#!/bin/bash

rm  their-keystore.jks 2> /dev/null
rm  my-keystore.jks    2> /dev/null
rm  my-truststore.jks  2> /dev/null

echo "===================================================="
echo "Creating fake third-party chain ca2 -> ca1 -> ca ..."
echo "===================================================="

keytool -genkeypair -alias ca  -dname cn=ca                           \
  -validity 10000 -keyalg RSA -keysize 2048                           \
  -ext BasicConstraints:critical=ca:true,pathlen:10000                \
  -keystore their-keystore.jks -keypass Keypass -storepass Storepass

keytool -genkeypair -alias ca1 -dname cn=ca1                          \
  -validity 10000 -keyalg RSA -keysize 2048                           \
  -keystore their-keystore.jks -keypass Keypass -storepass Storepass

keytool -genkeypair -alias ca2 -dname cn=ca2                          \
  -validity 10000 -keyalg RSA -keysize 2048                           \
  -keystore their-keystore.jks -keypass Keypass -storepass Storepass


  keytool -certreq -alias ca1                                            \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass   \
| keytool -gencert -alias ca                                             \
    -ext KeyUsage:critical=keyCertSign                                   \
    -ext SubjectAlternativeName=dns:ca1                                  \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass   \
| keytool -importcert -alias ca1                                         \
    -keystore   their-keystore.jks -keypass Keypass -storepass Storepass

#echo "Debug exit" ; exit 0

  keytool -certreq -alias ca2                                           \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass  \
| keytool -gencert -alias ca1                                           \
    -ext KeyUsage:critical=keyCertSign                                  \
    -ext SubjectAlternativeName=dns:ca2                                 \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass  \
| keytool -importcert -alias ca2                                        \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass

keytool -list -v -storepass Storepass -keystore their-keystore.jks


echo  "===================================================================="
echo  "Fake third-party chain generated. Now generating my-keystore.jks ..."
echo  "===================================================================="
read -p "Press a key to continue."

# Import authority's certificate chain

  keytool -exportcert -alias ca                                         \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass  \
| keytool -importcert -trustcacerts -noprompt -alias ca                 \
    -keystore  my-keystore.jks -keypass Keypass -storepass Storepass

  keytool -exportcert -alias ca1                                        \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass  \
| keytool -importcert -noprompt -alias ca1                              \
    -keystore  my-keystore.jks -keypass Keypass -storepass Storepass

  keytool -exportcert -alias ca2                                        \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass  \
| keytool -importcert -noprompt -alias ca2                              \
    -keystore  my-keystore.jks -keypass Keypass -storepass Storepass

# Create our own certificate, the authority signs it.

keytool -genkeypair -alias e1  -dname cn=e1                        \
  -validity 10000 -keyalg RSA -keysize 2048                        \
  -keystore my-keystore.jks -keypass Keypass -storepass Storepass

  keytool -certreq -alias e1                                            \
    -keystore my-keystore.jks -keypass Keypass -storepass Storepass     \
| keytool -gencert -alias ca2                                           \
    -ext SubjectAlternativeName=dns:localhost                           \
    -ext KeyUsage:critical=keyEncipherment,digitalSignature             \
    -ext ExtendedKeyUsage=serverAuth,clientAuth                         \
    -keystore their-keystore.jks -keypass Keypass -storepass Storepass  \
| keytool -importcert -alias e1                                         \
    -keystore my-keystore.jks -keypass Keypass -storepass Storepass

keytool -list -v  -storepass Storepass -keystore  my-keystore.jks

echo "================================================="
echo "Keystore generated. Now generating truststore ..."
echo "================================================="
read -p "Press a key to continue."

  keytool -exportcert -alias ca                                        \
    -keystore my-keystore.jks -keypass Keypass -storepass Storepass    \
| keytool -importcert -trustcacerts -noprompt -alias ca                \
    -keystore my-truststore.jks -keypass Keypass -storepass Storepass

  keytool -exportcert -alias ca1                                       \
    -keystore my-keystore.jks -keypass Keypass -storepass Storepass    \
| keytool -importcert -noprompt -alias ca1                             \
    -keystore my-truststore.jks -keypass Keypass -storepass Storepass

  keytool -exportcert -alias ca2                                       \
    -keystore my-keystore.jks -keypass Keypass -storepass Storepass    \
| keytool -importcert -noprompt -alias ca2                             \
    -keystore my-truststore.jks -keypass Keypass -storepass Storepass

keytool -list -v  -storepass Storepass -keystore  my-truststore.jks

rm  their-keystore.jks 2> /dev/null

回答by Lokesh Babu

Springboot 2.1.5 , java 1.8, keytool(it is part of JDK 8) 

these are the steps to follow to generate the self signed ssl certifcate in spring boot


1. Generate self signed ssl certificate

keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

ex: D:\example> <here run the above command>

if it is not working then make sure that your java bin path is set at environment variables to the PATH variable as

C:\Program Files\Java\jdk1.8.0_191\bin

2. after key generation has done then copy that file in to the src/main/resources folder in your project

3. add key store properties in applicaiton.properties 

server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123     # change the pwd
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

3. change your postman ssl verification settings to turn OFF
    go to settings and select the  ssl verification  to turn off

now verify the url ( your applicaiton url)
https://localhost:8443/test/hello