3

我正在编写一个简单的 java 客户端/服务器程序,其中只需与服务器建立连接,向它发送一个句子,然后服务器为此发送响应。这实际上是一个直截了当的例子。

在上述情况下,我正在寻找基于 SSL 的相互身份验证。我需要在java中实现它。

如果您有任何示例或如何在 Java 中实现相同的示例,请建议我。

4

2 回答 2

-2

当您说“客户端/服务器”时,是否意味着使用 Socket ?但 SSL 通常用于 HTTP 连接。我还没有看到它用于套接字连接。这是 HTTP 的示例:您必须将 PKCS12 证书加载到密钥库中,并将该存储区提供给 SSLContext。

private SSLSocketFactory getFactory( File pKeyFile, String pKeyPassword ) throws ... {
      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509);
      KeyStore keyStore = KeyStore.getInstance("PKCS12");

      InputStream keyInput = new FileInputStream(pKeyFile);
      keyStore.load(keyInput, pKeyPassword.toCharArray());
      keyInput.close();

      keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

      SSLContext context = SSLContext.getInstance("TLS");
      context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

      return context.getSocketFactory();
    }

    URL url = new URL("someurl");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(getFactory(new File("file.p12"), "secret"));
于 2014-05-02T14:17:02.830 回答
-2

服务器代码:

import java.io.*;
import java.net.*;
import java.util.*;
public class OTPServer {
 public static void main(String []args) throws IOException {
  ServerSocket ServerSocket= new ServerSocket(7777);
  System.out.println("Sever running and waiting for client");
  Socket ClientSocket=ServerSocket.accept();
  PrintWriter out=new PrintWriter(ClientSocket.getOutputStream(),true);
  Scanner sc=new Scanner(ClientSocket.getInputStream());
  String id=sc.nextLine();
  Random r=new Random();
  String otp=new String();
  for(int i=0;i<5;i++){
   otp+=r.nextInt(10);
  }
  System.out.print(otp);
  String newId=sc.nextLine();
  String newOtp=sc.nextLine();
  if(newId.equals(id)){
   if(!newOtp.equals(otp)){
    out.println("Incoreeect OTP!");    
   }
   else{
    out.println("Logged In!");
   }
  }
  System.exit(0);
 } 
}

客户端代码:

import java.io.*;
import java.net.*;
import java.util.*;
public class OTPServer {
 public static void main(String []args) throws IOException {
  ServerSocket ServerSocket= new ServerSocket(7777);
  System.out.println("Sever running and waiting for client");
  Socket ClientSocket=ServerSocket.accept();
  PrintWriter out=new PrintWriter(ClientSocket.getOutputStream(),true);
  Scanner sc=new Scanner(ClientSocket.getInputStream());
  String id=sc.nextLine();
  Random r=new Random();
  String otp=new String();
  for(int i=0;i<5;i++){
   otp+=r.nextInt(10);
  }
  System.out.print(otp);
  String newId=sc.nextLine();
  String newOtp=sc.nextLine();
  if(newId.equals(id)){
   if(!newOtp.equals(otp)){
    out.println("Incoreeect OTP!");    
   }
   else{
    out.println("Logged In!");
   }
  }
  System.exit(0);
 } 
}
于 2015-04-22T11:24:55.937 回答