Java Mutual authentication-客户端服务器

时间:2014-05-02 13:48:48

标签: java ssl client-server mutual-authentication

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

在上面的场景中,我正在寻找基于SSL的相互身份验证。 我需要在java中实现它。

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

2 个答案:

答案 0 :(得分:-1)

当您说"客户端/服务器"时,是否意味着使用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"));

答案 1 :(得分:-1)

服务器代码:

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);
 } 
}
相关问题