gpt4 book ai didi

java - SSL套接字帮助-javax.net.ssl.SSLHandshakeException : Received fatal alert: certificate_unknown

转载 作者:太空宇宙 更新时间:2023-11-03 13:15:44 25 4
gpt4 key购买 nike

我在使用SSL套接字建立客户端服务器套接字连接时遇到问题。我仍在学习SSL加密以及处理证书和 keystore 的过程。我有一个客户端和服务器应用程序,它们应该按如下方式相互连接:

服务器-SSLReverseEchoer.java

import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class SSLReverseEchoer {
public static void main(String[] args) {
String ksName = "sslkeystore.jks";
String keystorePass = "sslkeystorepassword";
char ksPass[] = keystorePass.toCharArray();

int sslPort = 9099;

Security.addProvider(new BouncyCastleProvider());

File file = new File(ksName);
String absPath = file.getAbsolutePath();

System.setProperty("javax.net.ssl.keyStore", absPath);
System.setProperty("javax.net.ssl.keyStorePassword", "sslkeystorepassword");

try {

//Get keystore w/ password
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(ksName), ksPass);

//Trust Manager
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(ks);

KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, ksPass);

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(sslPort);
printServerSocketInfo(s);

//WAIT FOR CONNECTION TODO ADD THREAD for NIO
SSLSocket c = (SSLSocket) s.accept();
printSocketInfo(c);

BufferedWriter w = new BufferedWriter(new OutputStreamWriter(
c.getOutputStream()));
BufferedReader r = new BufferedReader(new InputStreamReader(
c.getInputStream()));

String m = "Welcome to SSL Reverse Echo Server."+
" Please type in some words.";
w.write(m,0,m.length());
w.newLine();
w.flush();
while ((m=r.readLine())!= null) {
if (m.equals(".")) break;
char[] a = m.toCharArray();
int n = a.length;
for (int i=0; i<n/2; i++) {
char t = a[i];
a[i] = a[n-1-i];
a[n-i-1] = t;
}
w.write(a,0,n);
w.newLine();
w.flush();
}
w.close();
r.close();
c.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printSocketInfo(SSLSocket s) {
System.out.println("Socket class: "+s.getClass());
System.out.println(" Remote address = "
+s.getInetAddress().toString());
System.out.println(" Remote port = "+s.getPort());
System.out.println(" Local socket address = "
+s.getLocalSocketAddress().toString());
System.out.println(" Local address = "
+s.getLocalAddress().toString());
System.out.println(" Local port = "+s.getLocalPort());
System.out.println(" Need client authentication = "
+s.getNeedClientAuth());
SSLSession ss = s.getSession();
System.out.println(" Cipher suite = "+ss.getCipherSuite());
System.out.println(" Protocol = "+ss.getProtocol());
}
private static void printServerSocketInfo(SSLServerSocket s) {
System.out.println("Server socket class: "+s.getClass());
System.out.println(" Socket address = "
+s.getInetAddress().toString());
System.out.println(" Socket port = "
+s.getLocalPort());
System.out.println(" Need client authentication = "
+s.getNeedClientAuth());
System.out.println(" Want client authentication = "
+s.getWantClientAuth());
System.out.println(" Use client mode = "
+s.getUseClientMode());
}
}

CLIENT -SSLSocketClient.java
import java.io.*;
import java.net.*;
import javax.net.ssl.*;

public class SSLSocketClient {

public static void main(String[] args) {

int sslPort = 9099;

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintStream out = System.out;

SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();

try {
SSLSocket c = (SSLSocket) f.createSocket("localhost", sslPort);
printSocketInfo(c);
c.startHandshake();

BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));

String m = null;
while ((m=r.readLine())!= null) {
out.println(m);
m = in.readLine();
w.write(m,0,m.length());
w.newLine();
w.flush();
}
w.close();
r.close();
c.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void printSocketInfo(SSLSocket s) {
System.out.println("Socket class: "+s.getClass());
System.out.println(" Remote address = "
+s.getInetAddress().toString());
System.out.println(" Remote port = "+s.getPort());
System.out.println(" Local socket address = "
+s.getLocalSocketAddress().toString());
System.out.println(" Local address = "
+s.getLocalAddress().toString());
System.out.println(" Local port = "+s.getLocalPort());
System.out.println(" Need client authentication = "
+s.getNeedClientAuth());
SSLSession ss = s.getSession();
System.out.println(" Cipher suite = "+ss.getCipherSuite());
System.out.println(" Protocol = "+ss.getProtocol());
}
}

我执行 服务器,它开始监听指定的端口,但是当执行 CLIENT 时,我得到以下堆栈跟踪。

服务器输出
Server socket class: class sun.security.ssl.SSLServerSocketImpl
Socket address = 0.0.0.0/0.0.0.0
Socket port = 9099
Need client authentication = false
Want client authentication = false
Use client mode = false
Socket class: class sun.security.ssl.SSLSocketImpl
Remote address = /127.0.0.1
Remote port = 62145
Local socket address = /127.0.0.1:9099
Local address = /127.0.0.1
Local port = 9099
Need client authentication = false
Cipher suite = SSL_NULL_WITH_NULL_NULL
Protocol = NONE
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at sun.security.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1541)
at sun.security.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1553)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:71)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
at java.io.BufferedWriter.flush(BufferedWriter.java:254)
at com.example.SSLReverseEchoer.main(SSLReverseEchoer.java:60)
Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2023)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1125)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.getSession(SSLSocketImpl.java:2267)
at com.example.SSLReverseEchoer.printSocketInfo(SSLReverseEchoer.java:94)
at com.example.SSLReverseEchoer.main(SSLReverseEchoer.java:49)

客户输出
Socket class: class sun.security.ssl.SSLSocketImpl
Remote address = localhost/127.0.0.1
Remote port = 9099
Local socket address = /127.0.0.1:62145
Local address = /127.0.0.1
Local port = 62145
Need client authentication = false
Cipher suite = SSL_NULL_WITH_NULL_NULL
Protocol = NONE
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1541)
at sun.security.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1553)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1399)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at com.example.SSLSocketClient.main(SSLSocketClient.java:23)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.getSession(SSLSocketImpl.java:2267)
at com.example.SSLSocketClient.printSocketInfo(SSLSocketClient.java:55)
at com.example.SSLSocketClient.main(SSLSocketClient.java:22)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
... 9 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 15 more

我使用 keystore 生成具有以下参数的 sslkeystore.jks X509_certificate.cer :

生成sslkeystore.jks
keytool -genkey -keyalg RSA -alias sslsocket -keystore sslkeystore.jks -storepass sslkeystorepassword -validity 365 -keysize 2048
What is your first and last name?
[Unknown]: Gandalf
What is the name of your organizational unit?
[Unknown]: Wizardry
What is the name of your organization?
[Unknown]: Arnock
What is the name of your City or Locality?
[Unknown]: Minas Tirith
What is the name of your State or Province?
[Unknown]: Gondor
What is the two-letter country code for this unit?
[Unknown]: GD
Is CN=Gandalf, OU=Wizardry, O=Arnock, L=Minas Tirith, ST=Gondor, C=GD correct?
[no]: yes

Enter key password for <sslsocket>
(RETURN if same as keystore password):

导出证书。cer
keytool -export -alias sslsocket -keystore sslkeystore.jks -rfc -file X509_certificate.cer
Enter keystore password:
Certificate stored in file <X509_certificate.cer>

对这里出什么问题有什么建议吗?

我要在这里实现的是使用公钥和私钥对套接字进行非对称加密。 * .jks是否持有公钥,*。cer是否持有私钥?如果是这种情况,我是否需要在客户端中添加一些其他东西来使用私钥,还是在握手期间将其提供给客户端?

任何帮助,将不胜感激。

最佳答案

您已经倒退了。 As the Wikipedia article begins:

Public-key cryptography, or asymmetric cryptography, is any cryptographic system that uses pairs of keys: public keys that may be disseminated widely [which are mathematically] paired with private keys which are known only to the owner.



SSL/TLS服务器 保留其私钥为私有(private);它是向他人(特别是客户)发出的公钥。但是正如wp所说

The binding between a public key and its "owner" must be correct, or else the algorithm may function perfectly and yet be entirely insecure in practice. [...] Associating a public key with its owner is typically done by protocols implementing a public key infrastructure – these allow the validity of the association to be formally verified by reference to a trusted third party in the form of either a hierarchical certificate authority (e.g., X.509) [...]



尽管PKC通常具有其他选项,但SSL/TLS通常(并且始终在Java中)使用X.509证书。一方的 证书证书,此处的服务器 包含该方的公钥,该方的身份(对于SSL/TLS服务器,通常是DNS名称或服务器的多个名称),以及其他一些信息您可以忽略,通常由 Certificate Authority 签名的

通常,管理者(客户端)已经安装了知名CA(例如Verisign,GoDaddy等)以及可能是更多本地CA(例如您的雇主或州政府)的“根”证书副本,并且服务器仅发送自己的证书,再加上SSL/TLS握手中CA提供的任何所需的“链”或中间证书;客户端可以使用其预安装的根副本来验证证书。 (对于Java客户端,请参见下文。)

但是,如果您不花心或没有资格从真实的CA获得证书,则SSL/TLS协议(protocol)可以代替使用服务器自身签名的证书,称为自签名证书。在这种情况下,由于客户端没有先验的方式来知道特定证书是服务器的正确证书,而不是冒名顶替者创建的伪证书,因此您需要将服务器的自签名证书放入客户端的信任库中。通常,您需要将证书从服务器安全地复制到客户端,但是由于您显然是在单个主机上进行测试,因此大大简化了该问题。

具体来说,在Java中:
  • keytool -genkeypair或过时的同义词-genkey在文件(默认为JKS文件)中创建带有自签名(默认)证书
  • 的 key 对
  • keytool -exportcert(或-export)将证书(包含公钥和名称)复制到文件中,在此处将其命名为X509_certficate.cer。由于您没有获得真正的CA证书,因此这是自签名证书,您需要将其放入每个客户端的信任库中。

  • 有三种方法可以将证书放入Java客户端的信任库中:
  • 显式1:使用keytool -importcert将证书放入 keystore 文件(通常为JKS)中,将该 keystore 读取到内存中,并使用它来初始化TrustManager,然后是SSLContext,然后是SSLSocketFactory。除了没有KeyManager部分,这与服务器代码相似,并且您使用SSLSocket类而不是SSLServerSocket类。
  • 显式2:使用CertificateFactory类型的X.509从文件中读取(仅)证书,在内存中创建 keystore (无 keystore 文件)并将证书放入其中,然后按照显式1进行。
    如果您需要多个受信任的证书,则可以读取每个证书并将其全部保存在内存中,但是,与读取包含所有证书的单个 keystore 文件相比,这很快就变得更加繁琐。
  • middle:在首次创建SSL套接字之前,将证书放入 keystore 文件中,并设置系统属性javax.net.ssl.trustStore...trustStorePassword(如果不是默认的JKS,则设置为...trustStoreType,如果不是默认的JKS,或者在Java8中也为PKCS12)以指向它。您可以通过调用System.setProperty或在启动-Dname=value时在命令行上使用标志java来设置系统属性。
  • 隐式:将证书添加到默认使用的文件中,该文件为JREHOME/lib/security/cacerts(或jssecacerts(如果存在),但默认情况下不存在),并且安装为包含约一百个知名CA。这会影响使用该JRE的所有程序,除非它们使用上述选项设置了自己的信任库,这可能会或可能不会成为问题,这取决于您或其他人(在Java中)在此系统上运行的是什么。

  • 最后,SSL/TLS服务器证书中的 CommonName ,这是keytool提示输入first and last name时实际设置的字段(回读中注意CN=Gandalf,CN表示CommonName),应该是服务器的主机名,或更确切地说是服务器的主机名
    客户端使用的名称 连接到服务器(在您的示例中显然是localhost)。另外,特别是对于Real-CA证书,可以使用名为SubjectAlternativeName(缩写为SAN)的扩展名,但是使用keytool进行SAN相当笨拙。

    基本的SSLSocket逻辑不会(当前)验证主机名,但是大多数其他客户端(例如Web浏览器)(甚至Java中的HttpsURLConnection)都可以验证主机名,并且除非您的服务器可以作为Gandalf连接(没有任何域限定),否则这些客户端将拒绝即使证书本身是“有效的”,也可以使用证书连接到服务器。

    关于java - SSL套接字帮助-javax.net.ssl.SSLHandshakeException : Received fatal alert: certificate_unknown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028065/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com