团队冲刺DAY6
今天的内容是无图形界面的客户端和服务器的加密解密系统。
通信时用的socket方法,内置的密钥,端口,ip地址.
客户端:
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.util.*;
public class Client {
private static final String SKEY = "abcdefgh";
private static final Charset CHARSET = Charset.forName("gb2312");
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Socket mysocket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread readData ;
Read read=null;
try{ mysocket=new Socket();
read = new Read();
readData = new Thread(read);
String IP = "127.0.0.1";
int port = 2010;
if(mysocket.isConnected()){}
else{
InetAddress address=InetAddress.getByName(IP);
InetSocketAddress socketAddress=new InetSocketAddress(address,port);
mysocket.connect(socketAddress);
in =new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
read.setDataInputStream(in);
readData.start();
}
}
catch(Exception e) {
System.out.println("服务器已断开"+e);
}
System.out.println("已经成功连接服务器,开始通讯!");
System.out.print("输入:");
while(scanner.hasNext()) {
Macq S = new Macq();
String s = "";
String st = "";
try {
s = scanner.nextLine();
}
catch(InputMismatchException exp){
System.exit(0);
}
if(s.equals("end!")){
System.exit(0);
}
s = DesUtil.encrypt(s, CHARSET, SKEY);
st = S.mac(s);
try {
out.writeUTF(s);
out.writeUTF(st);
}
catch(Exception e) {}
}
}
}
服务器:
import java.io.*;
import java.nio.charset.Charset;
public class Read implements Runnable {
private static final String SKEY = "abcdefgh";
private static final Charset CHARSET = Charset.forName("gb2312");
DataInputStream in;
public void setDataInputStream(DataInputStream in) {
this.in = in;
}
@Override
public void run() {
Macq S = new Macq();
String s = "";
String mactext = "";
String mactest = "";
while(true) {
try{
s = in.readUTF();
mactext = in.readUTF();
System.out.println("服务器回复:"+s);
System.out.println("接收到的mac:"+mactext);
try{
mactest =S.mac(s);
System.out.println("本地检验的mac:"+mactext);
if(mactest.equals(mactext)==true){
throw new java.io.IOException("没有通过mac检验");
}
}catch (Exception e2){
e2.printStackTrace();
}
try {
s = DesUtil.decrypt(s, CHARSET, SKEY);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("解密为:"+s);
System.out.print("输入:");
}
catch(IOException e) {
System.out.println("与服务器已断开!"+e);
break;
}
}
}
}
因为不是最终稿,所以并没有用更难组合的用两个线程的客户端和服务器的DAY1代码,而是用的书上的例子,来增加部分代码的方法先练练手。