Java Socket使用加密协议进行传输对象的方法

时间:2022-09-23 08:56:08

本文实例讲述了Java Socket使用加密协议进行传输对象的方法。分享给大家供大家参考,具体如下:

前面的几篇文章介绍了Socket中一些常见的用法,但是对于一些有安全要求的应用就需要加密传输的数据,此时就需要用到SSLSocket了。

还是一样需要一个实现了Java.io.Serializable接口的简单Java对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.googlecode.garbagecan.test.socket.ssl;
public class User implements java.io.Serializable {
  private static final long serialVersionUID = 1L;
  private String name;
  private String password;
  public User() {
  }
  public User(String name, String password) {
    this.name = name;
    this.password = password;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
}

SSL Server类,这里需要用到ServerSocketFactory类来创建SSLServerSocket类实例,然后在通过SSLServerSocket来获取SSLSocket实例,这里考虑到面向对象中的面向接口编程的理念,所以代码中并没有出现SSLServerSocket和SSLSocket,而是用了他们的父类ServerSocket和Socket。在获取到ServerSocket和Socket实例以后,剩下的代码就和不使用加密方式一样了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.googlecode.garbagecan.test.socket.ssl;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class MyServer {
  private final static Logger logger = Logger.getLogger(MyServer.class.getName());
  public static void main(String[] args) {
    try {
      ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
      ServerSocket server = factory.createServerSocket(10000);
      while (true) {
        Socket socket = server.accept();
        invoke(socket);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  private static void invoke(final Socket socket) throws IOException {
    new Thread(new Runnable() {
      public void run() {
        ObjectInputStream is = null;
        ObjectOutputStream os = null;
        try {
          is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
          os = new ObjectOutputStream(socket.getOutputStream());
          Object obj = is.readObject();
          User user = (User)obj;
          System.out.println("user: " + user.getName() + "/" + user.getPassword());
          user.setName(user.getName() + "_new");
          user.setPassword(user.getPassword() + "_new");
          os.writeObject(user);
          os.flush();
        } catch (IOException ex) {
          logger.log(Level.SEVERE, null, ex);
        } catch(ClassNotFoundException ex) {
          logger.log(Level.SEVERE, null, ex);
        } finally {
          try {
            is.close();
          } catch(Exception ex) {}
          try {
            os.close();
          } catch(Exception ex) {}
          try {
            socket.close();
          } catch(Exception ex) {}
        }
      }
    }).start();
  }
}

SSL Client类和SSL Server类类似,只是将其中获取Socket的方式有所变化,其余的代码也和不使用加密方式一样。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.googlecode.garbagecan.test.socket.ssl;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
public class MyClient {
private final static Logger logger = Logger.getLogger(MyClient.class.getName());
  public static void main(String[] args) throws Exception {
    for (int i = 0; i < 100; i++) {
      Socket socket = null;
      ObjectOutputStream os = null;
      ObjectInputStream is = null;
      try {
        SocketFactory factory = SSLSocketFactory.getDefault();
        socket = factory.createSocket("localhost", 10000);
        os = new ObjectOutputStream(socket.getOutputStream());
        User user = new User("user_" + i, "password_" + i);
        os.writeObject(user);
        os.flush();
        is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
        Object obj = is.readObject();
        if (obj != null) {
          user = (User)obj;
          System.out.println("user: " + user.getName() + "/" + user.getPassword());
        }
      } catch(IOException ex) {
        logger.log(Level.SEVERE, null, ex);
      } finally {
        try {
          is.close();
        } catch(Exception ex) {}
        try {
          os.close();
        } catch(Exception ex) {}
        try {
          socket.close();
        } catch(Exception ex) {}
      }
    }
  }
}

代码写完了,下面就需要产生keystore文件了,运行下面的命令

复制代码 代码如下:
keytool -genkey -alias mysocket -keyalg RSA -keystore mysocket.jks

 

在提示输入项中,密码项自己给定,其它都不改直接回车,这里我使用的密码是“mysocket”。

运行Server

复制代码 代码如下:
java -Djavax.net.ssl.keyStore=mysocket.jks -Djavax.net.ssl.keyStorePassword=mysocket com.googlecode.garbagecan.test.socket.ssl.MyServer

 

运行Client

复制代码 代码如下:
java -Djavax.net.ssl.trustStore=mysocket.jks  -Djavax.net.ssl.trustStorePassword=mysocket com.googlecode.garbagecan.test.socket.ssl.MyClient

 

希望本文所述对大家java程序设计有所帮助。