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

时间:2015-05-21 19:15:53

标签: java security ssl x509certificate serversocket

我是SSl服务器套接字的新手。我所要做的就是通过SSL读取数据。 我的应用程序侦听端口8000.请给我几个步骤,我可以如何做到这一点。当我有证书(在我的光盘上)时,如何建立SSL服务器套接字并从客户端读取?

以下是我的步骤

1)从文件读取server.crt并制作X509Certificate(具有公共证书和私钥) 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();
}

1 个答案:

答案 0 :(得分:1)

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

请给我一个详细的解决方案。