Java第五次实验
Java第五次实验--网络编程与安全
任务一:
一、实验要求:
两人一组结对编程:
0. 参考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA
- 结对实现中缀表达式转后缀表达式的功能 MyBC.java
- 结对实现从上面功能中获取的表达式中实现后缀表达式求值的功能,调用MyDC.java
- 上传测试代码运行结果截图和码云链接
二、实验步骤:
1.参考娄老师提供的博客[http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA]中的MyDC.java,将31-40行的代码填充可得如下代码:
import java.util.StringTokenizer;
import java.util.Stack;
public class MyDC {
/**
* constant for addition symbol
*/
private final char ADD = '+';
/**
* constant for subtraction symbol
*/
private final char SUBTRACT = '-';
/**
* constant for multiplication symbol
*/
private final char MULTIPLY = '*';
/**
* constant for division symbol
*/
private final char DIVIDE = '/';
/**
* the stack
*/
private Stack<Integer> stack;
public MyDC() {
stack = new Stack<Integer>();
}
public int evaluate(String expr) {
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer(expr);
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
//如果是运算符,调用isOperator
if (isOperator(token)) {
//从栈中弹出操作数2
op2 = stack.pop();
//从栈中弹出操作数1
op1 = stack.pop();
//根据运算符和两个操作数调用evalSingleOp计算result;
result=evalSingleOp(token.charAt(0), op1, op2);
//计算result入栈;
stack.push(result);
} else//如果是操作数
//操作数入栈;
stack.push(Integer.parseInt(token));
}
return result;
}
private boolean isOperator(String token) {
return (token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/"));
}
private int evalSingleOp(char operation, int op1, int op2) {
int result = 0;
switch (operation) {
case ADD:
result = op1 + op2;
break;
case SUBTRACT:
result = op1 - op2;
break;
case MULTIPLY:
result = op1 * op2;
break;
case DIVIDE:
result = op1 / op2;
}
return result;
}
}
2.参考网上资料以及自己的对代码的理解后得出MyBC.java
public class MyBC {
private Stack theStack;
private String input;
private String output = "";
public MyBC(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String doTrans() {
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper(ch, 1);
break;
case '*':
case '/':
gotOper(ch, 2);
break;
case '(':
theStack.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
return output;
}
public void gotOper(char opThis, int prec1) {
while (!theStack.isEmpty()) {
char opTop = theStack.pop();
if (opTop == '(') {
theStack.push(opTop);
break;
}
else {
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStack.push(opTop);
break;
}
else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
while (!theStack.isEmpty()) {
char chx = theStack.pop();
if (chx == '(')
break;
else
output = output + chx;
}
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
3.运行后得到实验截图
三、实验截图:
四、码云链接:
MyBC:https://gitee.com/BESTI-IS-JAVA-2018/20165213zqh/blob/master/实验5/MyBC.java
MyDC:https://gitee.com/BESTI-IS-JAVA-2018/20165213zqh/blob/master/实验5/MyDC.java
MyDCTester:https://gitee.com/BESTI-IS-JAVA-2018/20165213zqh/blob/master/实验5/MyDCTester.java
任务二:
一、实验要求
结对编程:
1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式通过网络发送给服务器
- 服务器接收到后缀表达式,调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验步骤
1、首先建立server
import java.net.*;
import java.io.*;
public class Server{
public static void main(String srgs[]) throws Exception
{
ServerSocket sc = null;
Socket socket=null;
try
{
MyDC evaluator = new MyDC();
sc= new ServerSocket(10000);//创建服务器套接字
System.out.println("端口号:" + sc.getLocalPort());
System.out.println("服务器成功启动,等待客户端呼叫");
socket = sc.accept(); //等待客户端连接
System.out.println("已经建立连接");//获得网络输入流对象的引用
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//获得网络输出流对象的引用
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
String aline2=in.readLine();
System.out.println("客户端发来的信息为:"+aline2);
int ans = evaluator.evaluate(aline2);
out.println(ans);
System.out.println("result = "+ans);
} catch (Exception e) {
System.out.println(e);
}
}
//十六进制和十进制转换
public static byte[] parseHexStr2Byte(String hexStr)
{
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++)
{
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1 ), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
2.再建立client。
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String srgs[]) throws Exception
{
try
{
// 1、创建客户端Socket,指定服务器地址和端口
Socket socket=new Socket("127.0.0.1",10000);
System.out.println("客户端成功启动,等待服务器应答");
// 2、获取输出流,向服务器端发送信息
// 向本机的10001端口发出客户请求
System.out.println("请输入中缀表达式:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 由系统标准输入设备构造BufferedReader对象
PrintWriter write = new PrintWriter(socket.getOutputStream());
// 由Socket对象得到输出流,并构造PrintWriter对象
//3、获取输入流,并读取服务器端的响应信息
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
String readline, infix, expression;
readline = br.readLine(); // 从系统标准输入读入一字符串
MyBC theTrans = new MyBC(readline);
infix = theTrans.doTrans();
StringBuilder newInfix = new StringBuilder(infix.replace(" ",""));
for (int i = 1; i < infix.length()+(i+1)/2 ; i=i+2) {
newInfix.insert(i," ");
}
System.out.println("后缀表达式:" + newInfix);
expression=newInfix.toString();
while (!readline.equals("end")) {
// 若从标准输入读入的字符串为 "end"则停止循环
write.println(expression);
// 将从系统标准输入读入的字符串输出到Server
write.flush();
// 刷新输出流,使Server马上收到该字符串
System.out.println("收到服务器的消息:" + in.readLine());
// 从Server读入一字符串,并打印到标准输出上
readline = br.readLine(); // 从系统标准输入读入一字符串
} // 继续循环
//4、关闭资源
write.close(); // 关闭Socket输出流
in.close(); // 关闭Socket输入流
socket.close(); // 关闭Socket
}
catch (Exception e)
{
System.out.println(e);//输出异常
}
finally
{
}
}
}
3、先在同一个电脑上先运行server.java,再运行client.java,得到如下实验截图。
三、实验截图:![](https://images2018.cnblogs.com/blog/1296582/201806/1296582-20180603172631437-133980689.jpg)
四、码云链接 :https://gitee.com/BESTI-IS-JAVA-2018/20165213zqh/tree/master/实验5
任务三:
一、实验要求:
加密结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密后通过网络把密文发送给服务器
- 服务器接收到后缀表达式表达式后,进行解密(和客户端协商密钥,可以用数组保存),然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验步骤
1.首先创建密钥
import java.io.*;
import java.security.*;
public class Skey_kb{
public static void main(String args[]) throws Exception{
FileInputStream f=new FileInputStream("key1.dat");
ObjectInputStream b=new ObjectInputStream(f);
Key k=(Key)b.readObject( );
byte[ ] kb=k.getEncoded( );
FileOutputStream f2=new FileOutputStream("keykb1.dat");
f2.write(kb);
// 打印密钥编码中的内容
for(int i=0;i<kb.length;i++){
System.out.print(kb[i]+",");
}
}
}
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.security.*;
public class Skey {
public static void main(String args[]) throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey k = kg.generateKey();
FileOutputStream f = new FileOutputStream("key1.txt");
ObjectOutputStream b = new ObjectOutputStream(f);
b.writeObject(k);
}
}
2、建立服务器server
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server_2 {
public static void main(String args[]) {
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(3001);
} catch (IOException e1) {
System.out.println(e1);
}
try {
System.out.println("等待客户呼叫");
socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫
System.out.println("客户已连接");
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
String leng = in.readUTF(); // in读取信息,堵塞状态
byte ctext[] = new byte[Integer.parseInt(leng)];
for (int i = 0;i<Integer.parseInt(leng);i++) {
String temp = in.readUTF();
ctext[i] = Byte.parseByte(temp);
}
// 获取密钥
FileInputStream f2 = new FileInputStream("keykb1.txt");
int num2 = f2.available();
byte[] keykb = new byte[num2];
f2.read(keykb);
SecretKeySpec k = new SecretKeySpec(keykb, "DESede");
// 解密
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, k);
byte[] ptext = cp.doFinal(ctext);
System.out.println("后缀表达式已被解密:");
for (int i = 0; i < ptext.length; i++) {
System.out.print(ptext[i] + ",");
}
System.out.println("");
// 显示明文
String p = new String(ptext, "UTF8");
System.out.println("服务器收到客户的请求:计算后缀表达式" + p);
out.writeUTF(MyDC.jisuan(new StringBuffer(p))+"");
} catch (Exception e) {
System.out.println("客户已断开" + e);
}
}
}
3.建立client
import javax.crypto.Cipher;
import java.io.*;
import java.net.Socket;
import java.security.Key;
import java.util.Scanner;
public class Client_2 {
public static void main(String args[]) {
Socket mysocket;
DataInputStream in = null;
DataOutputStream out = null;
Scanner scanner = new Scanner(System.in);
String str;
try {
FileInputStream f = new FileInputStream("key1.txt");
ObjectInputStream b = new ObjectInputStream(f);
Key k = (Key) b.readObject();
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k);
mysocket = new Socket("192.168.1.125", 3001);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
System.out.println("已连接服务器,请输入中缀表达式:");
str = scanner.nextLine();
byte ptext[] = MyBC.tran(new StringBuffer(str)).toString().getBytes("UTF-8");
byte ctext[] = cp.doFinal(ptext);
System.out.println("后缀表达式已被加密:");
for (int i = 0; i < ctext.length; i++) {
System.out.print(ctext[i] + ",");
}
System.out.println("");
out.writeUTF(ctext.length + "");
for (int i = 0; i < ctext.length; i++) {
out.writeUTF(ctext[i] + "");
//System.out.print();
}
String s = in.readUTF(); //in读取信息,堵塞状态
System.out.println("客户收到服务器的回应:" + s);
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
}
}
4.运行后得到如下截图
三、实验截图:
四、码云链接:https://gitee.com/BESTI-IS-JAVA-2018/20165213zqh/tree/master/实验5
任务四:
一、实验要求:密钥分发结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验步骤
1、建立dh算法代码:
/**
* @20165213zqh
*/
import java.io.*;
import java.math.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
public class Key_DH{
private static final byte skip1024ModulusBytes[] = {
(byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
(byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
(byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
(byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
(byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
(byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
(byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
(byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
(byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
(byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
(byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
(byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
(byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
(byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
(byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
(byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
(byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
(byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
(byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
(byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
(byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
(byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
(byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
(byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
(byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
(byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
(byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
(byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
(byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
(byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
(byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
(byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
};
private static final BigInteger skip1024Modulus = new BigInteger(1, skip1024ModulusBytes);
private static final BigInteger skip1024Base = BigInteger.valueOf(2);
public static void fun(String s1,String s2) throws Exception{
DHParameterSpec DHP= new DHParameterSpec(skip1024Modulus,skip1024Base);
KeyPairGenerator kpg= KeyPairGenerator.getInstance("DH");
kpg.initialize(DHP);
KeyPair kp=kpg.genKeyPair();
PublicKey pbk=kp.getPublic();
PrivateKey prk=kp.getPrivate();
FileOutputStream f1=new FileOutputStream(s1);
ObjectOutputStream b1=new ObjectOutputStream(f1);
b1.writeObject(pbk); FileOutputStream f2=new FileOutputStream(s2);
ObjectOutputStream b2=new ObjectOutputStream(f2);
b2.writeObject(prk);
}
}
2.建立KeyAgree.java
/**
* @20165213zqh
*/
import java.io.*;
import java.math.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
public class KeyAgree{
public static void fun(String s1,String s2) throws Exception{
// 读取对方的DH公钥
FileInputStream f1=new FileInputStream(s1);
ObjectInputStream b1=new ObjectInputStream(f1);
PublicKey pbk=(PublicKey)b1.readObject( );
//读取自己的DH私钥
FileInputStream f2=new FileInputStream(s2);
ObjectInputStream b2=new ObjectInputStream(f2);
PrivateKey prk=(PrivateKey)b2.readObject( );
// 执行密钥协定
KeyAgreement ka=KeyAgreement.getInstance("DH");
ka.init(prk);
ka.doPhase(pbk,true);
//生成共享信息
byte[ ] sb=ka.generateSecret();
FileOutputStream fsb = new FileOutputStream("sb.txt");
fsb.write(sb);
}
}
3.建立server
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;
import java.util.Optional;
public class Server_3 {
public static void main(String args[]) {
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(3001);
} catch (IOException e1) {
System.out.println(e1);
}
try {
System.out.println("等待客户呼叫");
socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫
System.out.println("客户已连接");
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
Key_DH.fun("Spub.txt","Spri.txt");
int len = Integer.parseInt(in.readUTF());
byte np[] = new byte[len];
for (int i = 0;i<len;i++) {
String temp = in.readUTF();
np[i] = Byte.parseByte(temp);
}
ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (np));
Key k2 = (Key)ois.readObject();;
FileOutputStream f2 = new FileOutputStream("Cpub.txt");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k2);
FileInputStream fp = new FileInputStream("Spub.txt");
ObjectInputStream bp = new ObjectInputStream(fp);
Key kp = (Key) bp.readObject();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(kp);
byte[] kb = baos.toByteArray();
out.writeUTF(kb.length + "");
for (int i = 0; i < kb.length; i++) {
out.writeUTF(kb[i] + "");
}
KeyAgree.fun("Cpub.txt","Spri.txt");
String leng = in.readUTF(); // in读取信息,堵塞状态
byte ctext[] = new byte[Integer.parseInt(leng)];
for (int i = 0;i<Integer.parseInt(leng);i++) {
String temp = in.readUTF();
ctext[i] = Byte.parseByte(temp);
}
// 获取密钥
FileInputStream f = new FileInputStream("sb.txt");
byte[] keysb = new byte[24];
f.read(keysb);
System.out.println("公共密钥:");
for (int i = 0;i<24;i++) {
System.out.print(keysb[i]+",");
}
System.out.println("");
SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
// 解密
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, k);
byte[] ptext = cp.doFinal(ctext);
System.out.println("后缀表达式已被解密:");
for (int i = 0; i < ptext.length; i++) {
System.out.print(ptext[i] + ",");
}
System.out.println("");
// 显示明文
String p = new String(ptext, "UTF8");
System.out.println("服务器收到客户的请求:计算后缀表达式" + p);
out.writeUTF(MyDC.jisuan(new StringBuffer(p))+"");
} catch (Exception e) {
System.out.println("客户已断开" + e);
}
}
}
4、建立客户端 ,由结对编程伙伴完成。
5、运行程序得到结果。
三、实验截图:![](https://images2018.cnblogs.com/blog/1296582/201806/1296582-20180603181857745-737359895.png)
四、码云链接:https://gitee.com/BESTI-IS-JAVA-2018/20165213zqh/tree/master/实验5
任务五
一、实验要求:
完整性校验结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文和明文的MD5値发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,解密后计算明文的MD5值,和客户端传来的MD5进行比较,一致则调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验步骤:
import java.security.*;
public class DigestPass{
public static String fun(String ss) throws Exception{
String x=ss;
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(x.getBytes("UTF8"));
byte s[ ]=m.digest( );
String result="";
for (int i=0; i<s.length; i++){
result+=Integer.toHexString((0x000000ff & s[i]) |
0xffffff00).substring(6);
}
return result;
}
}
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;
public class Server_4 {
public static void main(String args[]) {
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(3001);
} catch (IOException e1) {
System.out.println(e1);
}
try {
System.out.println("等待客户呼叫");
socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫
System.out.println("客户已连接");
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
Key_DH.fun("Spub.txt","Spri.txt");
int len = Integer.parseInt(in.readUTF());
byte np[] = new byte[len];
for (int i = 0;i<len;i++) {
String temp = in.readUTF();
np[i] = Byte.parseByte(temp);
}
ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream(np));
Key k2 = (Key)ois.readObject();;
FileOutputStream f2 = new FileOutputStream("Cpub.txt");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k2);
FileInputStream fp = new FileInputStream("Spub.txt");
ObjectInputStream bp = new ObjectInputStream(fp);
Key kp = (Key) bp.readObject();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(kp);
byte[] kb = baos.toByteArray();
out.writeUTF(kb.length + "");
for (int i = 0; i < kb.length; i++) {
out.writeUTF(kb[i] + "");
}
KeyAgree.fun("Cpub.txt","Spri.txt");
String leng = in.readUTF(); // in读取信息,堵塞状态
byte ctext[] = new byte[Integer.parseInt(leng)];
for (int i = 0;i<Integer.parseInt(leng);i++) {
String temp = in.readUTF();
ctext[i] = Byte.parseByte(temp);
}
String check = in.readUTF();
// 获取密钥
FileInputStream f = new FileInputStream("sb.txt");
byte[] keysb = new byte[24];
f.read(keysb);
System.out.println("公共密钥:");
for (int i = 0;i<24;i++) {
System.out.print(keysb[i]+",");
}
System.out.println("");
SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
// 解密
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, k);
byte[] ptext = cp.doFinal(ctext);
System.out.println("后缀表达式已被解密:");
for (int i = 0; i < ptext.length; i++) {
System.out.print(ptext[i] + ",");
}
System.out.println("");
// 显示明文
String p = new String(ptext, "UTF8");
String pMd5 = DigestPass.fun(p);
System.out.println("解密后明文的MD5值:"+pMd5);
if (pMd5.equals(check)){
System.out.println("和客户端的MD5值一致");
System.out.println("服务器收到客户的请求:计算后缀表达式" + p);
out.writeUTF(MyDC.jisuan(new StringBuffer(p))+"");
}
else {
System.out.println("警告:和客户端的MD5值不一致!");
}
} catch (Exception e) {
System.out.println("客户已断开" + e);
}
}
}
3、client由结对伙伴完成,运行程序。
三、实验截图:
四、码云链接:https://gitee.com/BESTI-IS-JAVA-2018/20165213zqh/tree/master/实验5