使用openssl / java的双向SSL

时间:2016-05-31 07:52:52

标签: java ssl openssl jks

我有一个java的客户端应用程序,希望以双向SSL连接到服务器。 我创建了一对公钥/私钥。公钥名称为 key.cert ,私钥名称为 key.pem 。 然后服务器端给我一个带有 server.cert 名称的公钥。 我的问题是:

  1. 将我(客户端)的三个密钥( key.cert \ key.pem \ server.cert )转换为java 密钥库(JKS)的内容是什么?
  2. 在连接服务器的代码中创建 Socket 是什么?

1 个答案:

答案 0 :(得分:0)

        System.out.println("Connecting to " +IP + "port "
                + Port);

        // load client private key
            KeyStore clientKeys = KeyStore.getInstance("JKS");
            clientKeys.load(
                    new FileInputStream(ProjectConfig
                            .getProperty("KeyStoreAndTrustStore")),
                    ProjectConfig.getProperty(
                            "KeyStoreAndTrustStorePassword")
                            .toCharArray());
            KeyManagerFactory clientKeyManager = KeyManagerFactory
                    .getInstance("SunX509");
            clientKeyManager.init(
                    clientKeys,
                    ProjectConfig.getProperty(
                            "KeyStoreAndTrustStorePassword")
                            .toCharArray());
            // load server public key
            KeyStore serverPub = KeyStore.getInstance("JKS");
            serverPub.load(
                    new FileInputStream(ProjectConfig
                            .getProperty("KeyStoreAndTrustStore")),
                    ProjectConfig.getProperty(
                            "KeyStoreAndTrustStorePassword")
                            .toCharArray());
            TrustManagerFactory trustManager = TrustManagerFactory
                    .getInstance("SunX509");
            trustManager.init(serverPub);

            // use keys to create SSLSoket
            SSLContext ssl = SSLContext.getInstance("TLS");
            ssl.init(clientKeyManager.getKeyManagers(),
                    trustManager.getTrustManagers(),
                    SecureRandom.getInstance("SHA1PRNG"));

            sslClient = (SSLSocket) ssl.getSocketFactory().createSocket(
                    IP, Port);

            sslClient.setSoTimeout(TimeOut);
            System.out.println("connected to "
                    + sslClient.getRemoteSocketAddress());
            OutputStream outToServer = sslClient.getOutputStream();

            out = new DataOutputStream(outToServer);
            String contentToSend = ((String)Paylod);

            out.writeUTF(contentToSend);
            System.out.println(" sending data.... " + contentToSend);
            InputStream inFromServer = sslClient.getInputStream();
            in = new DataInputStream(inFromServer);
            response = in.readUTF();
            System.out.println("Server says.... " + response);
            sslClient.close();