使用已知证书的 SSL 服务器套接字和握手

SSL server socket and handshake with known certificate

我是 SSl 服务器套接字的新手。我要做的就是通过 SSL 读取数据。 我的应用程序在端口 8000 上侦听。请给我一些关于如何执行此操作的步骤。当我有证书(在我的光盘上)时,如何建立 SSL 服务器套接字并从客户端读取?

这是我的步骤

1) 从文件中读取 server.crt 并生成 X509Certificate(具有 public 证书和私钥) 2) 获取 JKS 密钥库实例

3) 获取上下文实例

4) 通过端口 (8000) 创建服务器套接字

InputStream in = new DataInputStream(new FileInputStream(new File("server.crt")));
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);

CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
in.close();

ks.setCertificateEntry("dts", cert);

char[] newpass = "password".toCharArray();
String name = "mykeystore.ks";
FileOutputStream output = new FileOutputStream(name);
ks.store(output, newpass);

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "password".toCharArray());




try{

    System.setProperty("javax.net.ssl.keyStore","mykeystore.ks");
    System.setProperty("javax.net.ssl.keyStorePassword","password");
    System.setProperty("javax.net.debug","all");



    SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(kmf.getKeyManagers(), null, null);
    SSLServerSocketFactory sslServerSocketfactory = context.getServerSocketFactory();
    SSLServerSocket sslServerSocket = (SSLServerSocket)sslServerSocketfactory.createServerSocket(8000);
    SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept();  


    InputStream dataIN = sslSocket.getInputStream();

    byte[] hello = new byte[20];

    dataIN.read(hello);
    System.out.println(new String(hello));

    dataIN.close();

} catch (IOException e){
    e.printStackTrace();
}

我得到了我的问题的答案,我研究了如何使用自签名证书设置我自己的密钥库。这种方式对我有帮助。

请联系我以获得详细的解决方案。