2018-2019-2 20175207 实验五《实验五 网络编程与安全》实验报告


- [实验步骤及截图](#jump2)
    - [网络编程与安全-1](#jump2.1)
    - [网络编程与安全-2](#jump2.2)
    - [网络编程与安全-3](#jump2.3)
    - [网络编程与安全-4](#jump2.4)
    - [网络编程与安全-5](#jump2.5)

前中后缀表达式

实验步骤及截图

网络编程与安全-1

  1. 参考
    1. 实现中缀表达式转后缀表达式的功能 MyBC.java
    2. 实现从上面功能中获取的表达式中实现后缀表达式求值的功能,调用MyDC.java
    3. 上传测试代码运行结果截图和码云链接

网络编程与安全-2

  1. 注意责任归宿,要会通过测试证明自己没有问题
    1. 基于Java Socket实现客户端/服务器功能,传输方式用TCP
    2. 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式通过网络发送给服务器
    3. 服务器接收到后缀表达式,调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
    4. 客户端显示服务器发送过来的结果
    5. 上传测试结果截图和码云链接

网络编程与安全-3

  1. 注意责任归宿,要会通过测试证明自己没有问题
    1. 基于Java Socket实现客户端/服务器功能,传输方式用TCP
    2. 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密后通过网络把密文发送给服务器
    3. 服务器接收到后缀表达式表达式后,进行解密(和客户端协商密钥,可以用数组保存),然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
    4. 客户端显示服务器发送过来的结果
    5. 上传测试结果截图和码云链接

网络编程与安全-4

网络编程与安全-5

代码

MyDC

import java.util.StringTokenizer;
import java.util.Stack;
public class MyDC {
  String q;
  Stack stack;
  public MyDC() {
    stack = new Stack();
  }
  void set(String question) {   //输入后续排列的字符串
    q = question;
  }
  public Rational get() {
    Rational op1 = new Rational();
    Rational op2 = new Rational();
    Rational result = new Rational();
    result.setNumerator(0);
    StringTokenizer token = new StringTokenizer(q, " ");
    String temp;
    while (token.hasMoreTokens()) {
      temp = token.nextToken();
      if (Isop(temp) == 1) {     //遇到操作符,弹出栈顶的两个数进行运算
        op2 = (Rational) stack.pop();
        op1 = (Rational) stack.pop();//弹出最上面两个操作数
        result = cal(temp.charAt(0), op1, op2);//根据运算符进行运算
        stack.push(result);//将计算结果压栈
      }
      else {
        Rational num = new Rational();
        num.setNumerator(Integer.parseInt(temp));
        stack.push(num);//操作数入栈
      }
    }
    return result;
  }
  Rational cal(char op, Rational a, Rational b) {           //对栈顶弹出的两个数进行运算
    Rational c = new Rational();
    switch (op) {
      case '+':
        c = a.add(b);
        break;
      case '-':
        c = a.sub(b);
        break;
      case '*':
        c = a.muti(b);
        break;
      case '÷':
      case '/':
        if(b.getNumerator()==0) {
          System.out.println("生成的算式计算时出现了分母为0的情况!");
          System.exit(0);
        }
        else {
          c = a.div(b);
          break;
        }
      default:
        System.out.println("Wrong!");
    }
    return c;
  }
  int Isop(String op) {       //判断是不是运算符
    if (op.equals("+") || op.equals("-") || op.equals("*") || op.equals("÷") || op.equals("/")) {
      return 1;
    }
    else {
      return 0;
    }
  }
}

MyDCTester

import java.util.Scanner;

public class MyDCTester  {

   public static void main (String[] args) {

    String expression, again;

    int result;

     try
     {
          Scanner in = new Scanner(System.in);

          do
              {
                MyDC evaluator = new MyDC();
                System.out.println ("Enter a valid postfix expression: ");
                expression = in.nextLine();

                result = evaluator.evaluate (expression);
                System.out.println();
                System.out.println ("That expression equals " + result);

                System.out.print ("Evaluate another expression [Y/N]? ");
                again = in.nextLine();
                System.out.println();
              }
          while (again.equalsIgnoreCase("y"));
        }
     catch (Exception IOException)
     {
       System.out.println("Input exception reported");
     }
   }
}

MyBC

import java.util.Stack;
public class MyBC {
    String C = new String();
    String End = "";            //存储数字的字符串
    public void ChangeString(String str) {
        C = str;
    }
    public String ChangeOrder() {
        Stack store = new Stack();     //创建一个存储字符的栈
        for (int i = 0; i < C.length(); i++) {
            char op = C.charAt(i);     //将索引值为i处的字符的值返回
            if (op >= '0' && op <= '9') {
                End = End + op;
            }
            else if (op == '(') {
                store.push(op);
            }
            else if (op == '+' || op == '-' || op == '*' || op == '÷'|| op == '/') {
                End = End + " ";
                if (store.empty()) {
                    store.push(op);
                }
                else if (compareValue(op) > compareValue((char) store.peek())) {     //比较运算符优先级
                    store.push(op);
                }
                else {
                    End = End + String.valueOf(store.pop());
                    i--;
                }
            }
            else if (op == ')') {
                while ((char) store.peek() != '(') {
                    End = End + " " + String.valueOf(store.pop());
                }
                store.pop();
            }
        }
        while (!store.empty()) {
            End = End + " " + String.valueOf(store.pop());
        }
        return End;
    }
    public int compareValue(char chi) {
        int number = 0;
        switch (chi) {
            case '(':
                number = 1;
                break;
            case '+':
            case '-':
                number = 2;
                break;
            case '*':
            case '÷':
                number = 3;
                break;
            case '/':
                number = 4;
                break;
            case ')':
                number = 5;
                break;
            default:
                number = 0;
                break;
        }
        return number;
    }
}

MyBCTester

import java.util.*;
public class MyBCTester {
    public static void main(String[] args) {
        String question = "";
        String question1 = "";
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入题目:");
        question = scanner.nextLine();
        MyBC change = new MyBC();
        change.ChangeString(question);
        question1 = change.ChangeOrder();
        System.out.println(question1);
        MyDC getanswer = new MyDC();
        getanswer.set(question1);
        Rational answer = getanswer.get();
        int a = answer.getNumerator();
        int b = answer.getDenominator();
        float result = (float)a/b;
        System.out.println("结果为(保留两位小数):");
        System.out.println(String.format("%.2f",result));
    }
}

Server

import java.io.*;
import java.net.*;
public class Server {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        String question = "";
        try {
            serverForClient = new ServerSocket(2010);
        } catch (IOException e) {
            System.out.println(e);
        }
        System.out.println("等待客户呼叫");
        try {
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            while(true) {
                question = in.readUTF(); // in读取信息,堵塞状态
                System.out.println("服务器收到客户传递的后缀表达式为:" + question);
                MyDC getanswer = new MyDC();
                getanswer.set(question);
                Rational answer = getanswer.get();
                int a = answer.getNumerator();
                int b = answer.getDenominator();
                float result = (float) a / b;
                System.out.println("计算出的结果为"+String.format("%.2f",result));
                out.writeUTF(String.format("%.2f",result));
                Thread.sleep(500);
            }
        } catch (Exception e) {
            System.out.println("客户已断开" + e);
        }
    }
}

Client

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client{
    public static void main(String args[]) {
        Socket mysocket;
        DataInputStream in=null;
        DataOutputStream out=null;
        Scanner scanner = new Scanner(System.in);
        try{
            System.out.print("输入服务器的IP:");
            String IP = scanner.nextLine();
            InetAddress address=InetAddress.getByName(IP);
            mysocket = new Socket(address, 2010);
            in=new DataInputStream(mysocket.getInputStream());
            out=new DataOutputStream(mysocket.getOutputStream());
            System.out.println("请输入中缀表达式:");
            while (scanner.hasNext()) {
                String question = scanner.next();
                MyBC change = new MyBC();
                change.ChangeString(question);
                String question1 = change.ChangeOrder();
                System.out.println("后缀表达式为:"+question1);
                out.writeUTF(question1);
                String s=in.readUTF(); //in读取信息,堵塞状态
                System.out.println("客户收到服务器的回答:"+s);
                Thread.sleep(500);
                System.out.println("请输入中缀表达式:");
            }
        }
        catch(Exception e) {
            System.out.println("服务器已断开"+e);
        }
    }
}

Serverx

import java.io.*;
import java.net.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Serverx {
    public static void main(String[] args) throws Exception{
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(2010);
        } catch (IOException e) {
            System.out.println(e);
        }
        System.out.println("等待客户呼叫");
        try {
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String keylength = in.readUTF();
            byte []kb = new byte[Integer.parseInt(keylength)];
            System.out.println("收到的密钥为:");
            for(int i = 0;i<Integer.parseInt(keylength);i++) {
                String str = in.readUTF();
                kb[i] = Byte.parseByte(str);
                System.out.print(kb[i] + " ");
            }
            while(true) {
                SecretKeySpec k = new SecretKeySpec(kb, "DESede");
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.DECRYPT_MODE, k);
                String clength = in.readUTF();
                byte ctext[] = new byte[Integer.parseInt(clength)];
                for (int i = 0;i<Integer.parseInt(clength);i++) {
                    String temp = in.readUTF();
                    ctext[i] = Byte.parseByte(temp);
                }
                byte[] ptext = cp.doFinal(ctext);
                String question = new String(ptext,"UTF8");
                System.out.print("\n后缀表达式为:"+ question);
                MyDC getanswer = new MyDC();
                getanswer.set(question);
                Rational answer = getanswer.get();
                int a = answer.getNumerator();
                int b = answer.getDenominator();
                float result = (float) a / b;
                System.out.println("\n计算出的结果为"+String.format("%.2f",result));
                out.writeUTF(String.format("%.2f",result));
                Thread.sleep(500);
            }
        } catch (IOException e) {
            System.out.println("客户已断开" + e);
        }
    }
}

Clientx

import java.io.*;
import java.net.*;
import javax.crypto.*;
import java.util.Scanner;
public class Clientx {
    public static void main(String args[]) throws Exception{
        Socket mysocket;
        DataInputStream in=null;
        DataOutputStream out=null;
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("输入服务器的IP:");
            String IP = scanner.nextLine();
            InetAddress address=InetAddress.getByName(IP);
            mysocket = new Socket(address, 2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            KeyGenerator kg = KeyGenerator.getInstance("DESede");
            kg.init(168);
            SecretKey k = kg.generateKey();
            byte []kb = k.getEncoded();
            out.writeUTF(kb.length+ "");
            System.out.println("产生的密钥为");
            for(int i=0;i<kb.length;i++) {
                System.out.print(kb[i]+ " ");
                out.writeUTF(kb[i] +"");
            }
            System.out.println("\n请输入中缀表达式:");
            while(scanner.hasNext()) {
                String question = scanner.next();
                MyBC change = new MyBC();
                change.ChangeString(question);
                String question1 = change.ChangeOrder();
                System.out.println("后缀表达式为:"+question1);
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.ENCRYPT_MODE,k);
                byte ptext[] = question1.getBytes("UTF8");
                byte ctext[] = cp.doFinal(ptext);
                out.writeUTF(ctext.length + "");
                for(int i=0;i<ctext.length;i++) {
                    out.writeUTF(ctext[i] +"");
                }
                String s=in.readUTF(); //in读取信息,堵塞状态
                System.out.println("客户收到服务器的回答:"+s);
                Thread.sleep(500);
                System.out.println("请输入中缀表达式:");
            }
        }
        catch (IOException e) {
            System.out.println("服务器已断开"+e);
        }
    }
}

Serverxx

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;

public class Serverxx {
    public static void main(String[] args) throws Exception {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(2010);
        } catch (IOException e) {
            System.out.println(e);
        }
        System.out.println("等待客户呼叫");
        try {
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            Key_DH.DH("Wpub.dat","Wpri.dat");
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k1 = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("Lpub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k1);
            FileInputStream my = new FileInputStream("Wpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            KeyAgree.Agree("Lpub.dat","Wpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            byte[] keysb = new byte[24];
            f.read(keysb);
            System.out.println("公共密钥为:");
            for (int i = 0;i<24;i++) {
                System.out.print(keysb[i]+" ");
            }
            while(true) {
                SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.DECRYPT_MODE, k);
                String clength = in.readUTF();
                byte ctext[] = new byte[Integer.parseInt(clength)];
                for (int i = 0; i < Integer.parseInt(clength); i++) {
                    String temp = in.readUTF();
                    ctext[i] = Byte.parseByte(temp);
                }
                byte[] ptext = cp.doFinal(ctext);
                String question = new String(ptext, "UTF8");
                System.out.print("\n解密后的后缀表达式为:" + question);
                MyDC getanswer = new MyDC();
                getanswer.set(question);
                Rational answer = getanswer.get();
                int a = answer.getNumerator();
                int b = answer.getDenominator();
                float result = (float) a / b;
                System.out.println("\n计算出的结果为"+String.format("%.2f",result));
                out.writeUTF(String.format("%.2f",result));
                Thread.sleep(500);
            }
        }
        catch(Exception e) {
            System.out.println("客户已断开" + e);
        }
    }
}

Clientxx

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;
import java.util.Scanner;
import  java.net.*;
public class Clientxx {
    public static void main(String[] args) {
        Socket mysocket;
        DataInputStream in=null;
        DataOutputStream out=null;
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("输入服务器的IP:");
            String IP = scanner.nextLine();
            InetAddress  address=InetAddress.getByName(IP);
            mysocket = new Socket(address, 2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            Key_DH.DH("Lpub.dat","Lpri.dat");
            FileInputStream my = new FileInputStream("Lpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            Thread.sleep(1000);
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("W1pub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k);
            KeyAgree.Agree("W1pub.dat","Lpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            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("\n请输入中缀表达式:");
            while(scanner.hasNext()) {
                String question = scanner.next();
                MyBC change = new MyBC();
                change.ChangeString(question);
                String question1 = change.ChangeOrder();
                System.out.println("后缀表达式为:" + question1);
                SecretKeySpec k1 = new SecretKeySpec(keysb, "DESede");
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.ENCRYPT_MODE, k1);
                byte ptext[] = question1.getBytes("UTF8");
                byte ctext[] = cp.doFinal(ptext);
                System.out.println("加密后的后缀表达式为:");
                for (int i = 0; i < ctext.length; i++) {
                    System.out.print(ctext[i] + " ");
                }
                out.writeUTF(ctext.length + "");
                for (int i = 0; i < ctext.length; i++) {
                    out.writeUTF(ctext[i] + "");
                }
                String  s=in.readUTF();   //in读取信息,堵塞状态
                System.out.println("\n客户收到服务器的回答:"+s);
                Thread.sleep(500);
                System.out.println("请输入中缀表达式:");
            }
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

KeyAgree

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 Agree(String str1,String str2) throws Exception{
        // 读取对方的DH公钥
        FileInputStream f1=new FileInputStream(str1);
        ObjectInputStream b1=new ObjectInputStream(f1);
        PublicKey  pbk=(PublicKey)b1.readObject( );
//读取自己的DH私钥
        FileInputStream f2=new FileInputStream(str2);
        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.dat");
        fsb.write(sb);
    }
}

Key_DH

import java.io.*;
import java.math.*;
import java.security.*;
import javax.crypto.spec.*;

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
    };
    // The SKIP 1024 bit modulus
    private static final BigInteger skip1024Modulus
            = new BigInteger(1, skip1024ModulusBytes);
    // The base used with the SKIP 1024 bit modulus
    private static final BigInteger skip1024Base = BigInteger.valueOf(2);
    public static void DH(String str1,String str2) 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(str1);
        ObjectOutputStream b1=new  ObjectOutputStream(f1);
        b1.writeObject(pbk);
        // 保存私钥
        FileOutputStream  f2=new FileOutputStream(str2);
        ObjectOutputStream b2=new  ObjectOutputStream(f2);
        b2.writeObject(prk);
    }
}

Serverxxx

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;

public class Serverxxx {
    public static void main(String[] args) throws Exception {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(2010);
        } catch (IOException e) {
            System.out.println(e);
        }
        System.out.println("等待客户呼叫");
        try {
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            Key_DH.DH("Wpub.dat","Wpri.dat");
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k1 = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("L1pub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k1);
            FileInputStream my = new FileInputStream("Wpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            KeyAgree.Agree("L1pub.dat","Wpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            byte[] keysb = new byte[24];
            f.read(keysb);
            System.out.println("公共密钥为:");
            for (int i = 0;i<24;i++) {
                System.out.print(keysb[i]+" ");
            }
            while(true) {
                String c = in.readUTF();
                SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.DECRYPT_MODE, k);
                String clength = in.readUTF();
                byte ctext[] = new byte[Integer.parseInt(clength)];
                for (int i = 0; i < Integer.parseInt(clength); i++) {
                    String temp = in.readUTF();
                    ctext[i] = Byte.parseByte(temp);
                }
                byte[] ptext = cp.doFinal(ctext);
                String question = new String(ptext, "UTF8");
                System.out.println("\n解密后的后缀表达式为:" + question);
                String mtoMD5 = DigestPass.MD5(question);
                System.out.println("MD5的值为"+ mtoMD5);
                if(mtoMD5.equals(c)) {
                    System.out.println("传递的MD5值和解密的后缀表达式的MD5值相同,可以解密!");
                    MyDC getanswer = new MyDC();
                    getanswer.set(question);
                    Rational answer = getanswer.get();
                    int a = answer.getNumerator();
                    int b = answer.getDenominator();
                    float result = (float) a / b;
                    System.out.println("计算出的结果为"+String.format("%.2f",result));
                    out.writeUTF(String.format("%.2f",result));
                }
                else {
                    System.out.println("密文有误,不能解密!");
                }
                Thread.sleep(500);
            }
        }
        catch(Exception e) {
            System.out.println("客户已断开" + e);
        }
    }
}

Clientxxx

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.Socket;
import java.security.*;
import java.util.Scanner;
import java.net.*;
public class Clientxxx {
    public static void main(String[] args) {
        Socket mysocket;
        DataInputStream in=null;
        DataOutputStream out=null;
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("输入服务器的IP:");
            String IP = scanner.nextLine();
            InetAddress  address=InetAddress.getByName(IP);
            mysocket = new Socket(address, 2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            Key_DH.DH("Lpub.dat","Lpri.dat");
            FileInputStream my = new FileInputStream("Lpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            Thread.sleep(1000);
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("W1pub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k);
            KeyAgree.Agree("W1pub.dat","Lpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            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("\n请输入中缀表达式:");
            while(scanner.hasNext()) {
                String question = scanner.next();
                MyBC change = new MyBC();
                change.ChangeString(question);
                String question1 = change.ChangeOrder();
                System.out.println("后缀表达式为:" + question1);
                String mtoMD5 = DigestPass.MD5(question1);
                System.out.println("明文的MD5值为:"+mtoMD5);
                out.writeUTF(mtoMD5);
                SecretKeySpec k1 = new SecretKeySpec(keysb, "DESede");
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.ENCRYPT_MODE, k1);
                byte ptext[] = question1.getBytes("UTF8");
                byte ctext[] = cp.doFinal(ptext);
                System.out.println("加密后的后缀表达式为:");
                for (int i = 0; i < ctext.length; i++) {
                    System.out.print(ctext[i] + " ");
                }
                out.writeUTF(ctext.length + "");
                for (int i = 0; i < ctext.length; i++) {
                    out.writeUTF(ctext[i] + "");
                }
                String  s=in.readUTF();   //in读取信息,堵塞状态
                System.out.println("\n客户收到服务器的回答:"+s);
                Thread.sleep(500);
                System.out.println("请输入中缀表达式:");
            }
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

DigestPass

import java.security.*;

public class DigestPass{
    public static String MD5(String str) throws Exception{
        String x=str;
        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;
    }
}
posted @ 2019-05-31 15:06  20175207冷南  阅读(282)  评论(0编辑  收藏  举报