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

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

实验报告封面

课程:Java程序设计 班级:1753 姓名:柴轩达 学号:20175303
指导教师:娄嘉鹏 实验日期:2019年5月26日-5月31日 实验序号:5
实验名称:网络编程与安全

实验内容

网络编程与安全-1

实验要求

两人一组结对编程:
0. 参考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA

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

实验步骤

1.找到之前结对项目的四则运算,拿出之前的Fraction类、ChangeSuffix类与Calculation类,将ChangeSuffix改名为MyBC,Calculation类改名为MyDC,再重新写一个Main函数就行,运行截图:

实验代码

Fraction

package task_1;
public class Fraction {

    private long Numerator; // 分子
    private long Denominator; // 分母

    public Fraction(long Numerator, long Denominator) {
        this.Numerator = Numerator;     //将传过来的参数Numerator赋值给类中的Numerator
        if (Denominator == 0) {
            throw new ArithmeticException("分母不能为零");     //如果分母为0,抛出问题“分母不能为零”
        } else {
            this.Denominator = Denominator;       //如果分母不为0,将传过来的参数Denominator赋值给类中的Denominator
        }
        change();
    }

    public Fraction() {              //将分数初始化
        this(0, 1);
    }
    public long getNumerator() {     //返回分子Numerator
        return Numerator;
    }
    public void setNumerator(long numerator) {
        Numerator = numerator;       //设置分子,将传过来的参数numerator赋值给类中的Numerator
    }
    public long getDenominator() {
        return Denominator;       //返回分母Denominator
    }
    public void setDenominator(long denominator) {
        Denominator = denominator;       //设置分母,将传过来的参数denominator赋值给类中的Denominator
    }
    private Fraction change() {
        long gcd = gcd(Numerator,Denominator);    //求分子和分母的最大公因子并将公因子的值赋给gcd
        Numerator /= gcd;           //将分子Numerator的值除以gcd的值赋给Numerator
        Denominator /= gcd;           //将分母Denominator的值除以gcd的值赋给Denominator
        return this;
    }
    private long gcd(long a, long b) {    //求a和b的最大公因数
        long mod = a % b;
        if (mod == 0) {
            return b;          //如果余数mod为0,返回除数即为最大公因数
        } else {
            return gcd(b, mod);   //如果余数mod不等于0,将除数b看做被除数,把余数看做除数递归调用gdc(b,mod)
        }
    }
    public Fraction add(Fraction second) {       //一个分数加一个分数的加法法则
        return new Fraction(this.Numerator * second.Denominator + second.Numerator * this.Denominator,
                this.Denominator * second.Denominator);
    }

    public Fraction minus(Fraction second) {      //一个分数减一个分数的减法法则
        return new Fraction(this.Numerator * second.Denominator - second.Numerator * this.Denominator,
                this.Denominator * second.Denominator);
    }

    public Fraction multiply(Fraction second) {          //一个分数乘一个分数的乘法法则
        return new Fraction(this.Numerator*second.Numerator,
                this.Denominator * second.Denominator);
    }

    public Fraction divide(Fraction second) {       //一个分数除以一个分数的除法法则
        return new Fraction(this.Numerator*second.Denominator,
                this.Denominator * second.Numerator);
    }
    public String toString() {     //讲分数以字符串的形式返回
        if(this.Denominator==1){
            return String.format("%d",this.Numerator);     //如果分母为1,输出分子
        }
        else {
            return String.format("%d/%d", this.Numerator, this.Denominator);     //如果分母不为1,输出"分子/分母"
        }
    }

}

MyDC

package task_1;
import java.util.*;
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 = '÷';
    private final char SEMICON= '/';
    /** the stack */
    private Stack<String > stack;

    public MyDC() {
        stack = new Stack<String>();    //创建一个String类型的栈
    }

    public String evaluate (String expr)
    {
        String op1,op2;
        Fraction p1;
        Fraction p2;
        String token;
        String result ="";
        StringTokenizer tokenizer = new StringTokenizer (expr);  //将expr后缀表达式传进StringTokenizer方法

        while (tokenizer.hasMoreTokens())
        {
            token = tokenizer.nextToken();    //将StringTokenizer分解出的字符串赋给token

            //如果是运算符,调用isOperator
            if (isOperator(token))
            {
                //从栈中弹出操作数2
                op2=stack.pop();
                p2 = toFraction(op2);
                //从栈中弹出操作数1
                op1=stack.pop();
                p1 =toFraction(op1);
                //根据运算符和两个操作数调用evalSingleOp计算result;
                result=evalSingleOp(token.toCharArray()[0],p1,p2);
                //计算result入栈;
                stack.push(result);
            }
            else//如果是操作数,入栈
                stack.push(token);
        }

        return result;
    }

    private boolean isOperator (String token)
    {
        return ( token.equals("+") || token.equals("-") ||
                token.equals("*") || token.equals("÷")||token.equals("/") );    //若token是运算符,返回true
    }

    private String evalSingleOp (char operation, Fraction p1, Fraction p2)
    {
        Fraction result = new Fraction(0,1);     //初始化result

        switch (operation)    //根据运算符选择运算
        {
            case ADD:
                result =p1.add(p2);
                break;
            case SUBTRACT:
                result = p1.minus(p2);
                break;
            case MULTIPLY:
                result = p1.multiply(p2);
                break;
            case DIVIDE:
            case SEMICON:
                result = p1.divide(p2);
        }

        return result.toString();     //将结果变成字符串
    }
    private Fraction toFraction(String m){
        String token1, token2;
        Fraction r = new Fraction(0,1);
        StringTokenizer tokenizer1 = new StringTokenizer(m, "/");//把操作数以"/"为标记分割开来
        token1 = tokenizer1.nextToken();
        if (tokenizer1.hasMoreTokens()) {//如果有第二个元素就把token1放在分子的位置,token2放在分母的位置
            token2 = tokenizer1.nextToken();
            int toke1 =Integer.valueOf(token1).intValue();
            int toke2 =Integer.valueOf(token2).intValue();
            r =new Fraction(toke1,toke2);
        }
        else {//如果没有第二个元素就把token1放在分子的位置,分母固定为1
            int toke1 = Integer.valueOf(token1).intValue();
            r =new Fraction(toke1,1);
        }
        return r;

    }
}

MyBC

package task_1;
import java.util.*;
public class MyBC {
    String questions;
    String after_questions= "";
    public String toSuffix(String questions){
        this.questions=questions;
        Stack stack=new Stack();     //新建一个栈
        for (int i=0;i<questions.length();i++) {
            char ele=questions.charAt(i);   //取出字符串的第i个字符
            if (ele>='0'&&ele<='9'){
                after_questions=after_questions+ele;   //如果第i个字符为数字,直接写入到后缀表达式中
            }
            else if (ele=='+'||ele=='-'||ele=='*'||ele=='÷'||ele=='/') {
                after_questions=after_questions+" ";       //如果遇到运算符
                if (stack.empty()){
                    stack.push(ele);
                }      //若栈为空,字符进栈
                else if (priority(ele)>priority((char)stack.peek())) {
                    stack.push(ele);
                }       //如果栈顶元素的运算优先级小于当前字符的运算优先级,当前元素进栈
                else{
                    after_questions=after_questions+ String.valueOf(stack.pop())+" ";
                    i--;
                }     //其他情况即如果栈顶元素的运算优先级大于或等于当前字符的运算优先级,将该元素出栈,变成字符串类型
            }
            else if(ele=='('){
                stack.push(ele);
            }     //如果当前元素为左括号,进栈
            else if(ele==')'){
                after_questions+=" ";
                while((char)stack.peek()!='('){
                    after_questions=after_questions+ String.valueOf(stack.pop())+" ";
                }    //如果栈顶元素不是左括号,连续将栈顶元素弹出变成字符串类型写入到后缀表达式中
                stack.pop();  //将左括号弹出
            }
        }
        after_questions+=" ";
        while(!stack.empty()){
            after_questions=after_questions+String.valueOf(stack.pop())+" ";
        }    //如果栈顶元素非空,连续弹出栈顶元素变成字符串类型写入到后缀表达式中
        return after_questions;
    }
    public int priority (char c){       //定义运算符的优先级
        int pt =0;
        switch(c){
            case '(':
                pt=1;
                break;case '+':
            case '-':
                pt=2;
                break;
            case '*':
            case '÷':
                pt=3;
                break;
            case '/':
                pt=4;
                break;case ')':
                pt=5;
                break;
            default:
                pt=0;
                break;
        }
        return pt;
    }
}

Main

package task_1;
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String f = "";
        System.out.println("Please input the expression");
        String s = in.nextLine();
        MyDC mydc = new MyDC();
        MyBC mybc = new MyBC();
        mybc.toSuffix(s);
        f=mydc.evaluate(mybc.after_questions);
        System.out.println("the result is:"+f);
    }
}

实验截图

网络编程与安全-2

实验要求

结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题

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

实验步骤

1、创建数据输入以及输出流对象in和out用于建立连接后的数据传输。
2、客户端创建套接字对象mysocket,并用构造方法Socket(String host,int port)给mysocket创建实体,然后让mysocket调用getInputStream以及getoutputStream方法与服务器端建立连接。服务器端的步骤与客户端类似,但在创建套接字时服务器端先创建一个ServerSocket对象,并用该对象调用accept方法来创建Socket类的实例。
3、客户端与服务器端分别用对象out调用writeUTF方法来发送数据,对象in调用readUTF来接收数据。客户端在输入中缀表达式后转化为后缀表达式并通过out对象发送给服务器,服务器用in对象接收客户端发送过来的后缀表达式进行计算,并将计算结果使用out对象发送给客户端,客户端使用in对象接收客户端发来的数据并输出。

实验代码

客户端

package task_2;
import task_1.MyBC;
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Socket mySocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mySocket =new Socket("172.30.6.68",2010);
            in = new DataInputStream(mySocket.getInputStream());
            out = new DataOutputStream(mySocket.getOutputStream());
            System.out.println("请输入中缀表达式");
            String question = scanner.nextLine();
            MyBC myBC = new MyBC();
            String suffixquestion = myBC.toSuffix(question);
            out.writeUTF(suffixquestion);
            String result = in.readUTF();
            System.out.println("客户端收到答案:"+result);
            Thread.sleep(500);
        }
        catch (Exception e){
            System.out.println("服务器已断开");
        }

    }
}

服务器端

package task_2;
import task_1.*;
import java.io.*;
import java.net.*;
public class Sever {
    public static void main(String[] args) {
        ServerSocket serverSocket =null;
        Socket socket = null;
        DataOutputStream out = null;
        DataInputStream in =null;
        try{
            serverSocket =new ServerSocket(2010);
        }
        catch (IOException e){
            System.out.println(e);
        }
        try{
            System.out.println("等待客户呼叫");
            socket = serverSocket.accept();
            out = new DataOutputStream(socket.getOutputStream());
            in = new DataInputStream(socket.getInputStream());
            String suffixquestion = in.readUTF();
            MyDC myDC= new MyDC();
            String result = myDC.evaluate(suffixquestion);
            out.writeUTF(result);
            System.out.println("答案已传输至客户端");
            Thread.sleep(500);
        }
        catch (Exception e){
            System.out.println("客户已断开连接");
        }

    }
}

实验截图

客户端

服务器端

网络编程与安全-3

实验要求

加密结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题

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

实验步骤

1.在2的基础上参考娄老师密码学博客的Skey_kb类产生加密密钥Key1.dat和解密密钥Keykb1.dat;
2.在客户端参考娄老师密码学博客加入加密算法,在加密后把密文转换成字节数组通过循环传输到服务器端;
3.在服务器端加入解密算法,把计算结果传到客户端

实验代码

客户端

package task_3;
import task_1.MyBC;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.crypto.*;
import java.security.*;
public class Client {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Socket mySocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mySocket =new Socket("192.168.43.59",2010);
            in = new DataInputStream(mySocket.getInputStream());
            out = new DataOutputStream(mySocket.getOutputStream());
            System.out.println("请输入中缀表达式");
            String question = scanner.nextLine();
            MyBC myBC = new MyBC();
            String suffixquestion = myBC.toSuffix(question);
            FileInputStream f=new FileInputStream("key1.dat");
            ObjectInputStream b=new ObjectInputStream(f);
            Key k=(Key)b.readObject( );
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[]=suffixquestion.getBytes("UTF8");
            byte ctext[]=cp.doFinal(ptext);
            out.writeUTF(ctext.length+"");
            for(int i = 0;i<ctext.length;i++){
                out.writeUTF(ctext[i]+"");
            }
            String result =in.readUTF();
            System.out.println("收到服务器答案:"+result);
            Thread.sleep(500);
        }
        catch (Exception e){
            System.out.println("服务器已断开");
        }

    }
}

服务器端

package task_3;
import task_1.*;
import java.io.*;
import java.net.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class Sever{
    public static void main(String[] args) {
        ServerSocket serverSocket =null;
        Socket socket = null;
        DataOutputStream out = null;
        DataInputStream in =null;
        try{
            serverSocket =new ServerSocket(2010);
        }
        catch (IOException e){
            System.out.println(e);
        }
        try{
            MyDC myDC = new MyDC();
            System.out.println("等待客户呼叫");
            socket = serverSocket.accept();
            out = new DataOutputStream(socket.getOutputStream());
            in = new DataInputStream(socket.getInputStream());
            int length = Integer.valueOf(in.readUTF());
            byte ctext[] = new byte[length];
            for(int i =0;i<length;i++){
                String temp = in.readUTF();
                ctext[i] = Byte.parseByte(temp);
            }
            FileInputStream f2 = new FileInputStream("keykb1.dat");
            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);
            String p = new String(ptext,"UTF8");
            System.out.println("被解密的后缀表达式:" + p);
            System.out.println("计算后缀表达式" + p);
            out.writeUTF(myDC.evaluate(p));
            Thread.sleep(500);
        }
        catch (Exception e){
            System.out.println("客户已断开连接");
        }

    }
}

运行截图

客户端

服务器端

网络编程与安全-4

实验要求

密钥分发结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题

  1. 基于Java Socket实现客户端/服务器功能,传输方式用TCP
  2. 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文发送给服务器
  3. 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
  4. 服务器接收到后缀表达式表达式后,进行解密,然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
  5. 客户端显示服务器发送过来的结果
  6. 上传测试结果截图和码云链接

实验步骤

1.在3的基础上参考娄老师密码学博客的Key_DH类分别产生客户端和服务器端的公钥和私钥。
2.在客户端用客户端私钥和服务器端公钥产生共享密钥对原密钥进行加密产生新密文转换成字节数组传到服务器端。
3.在服务器端用服务器端私钥和客户端公钥产生共享密钥解密传过来的密文得到原密钥,对后缀表达式密文进行解密得到后缀表达式的原文,计算得到结果传到客户端。

实验代码

package task_4;

import task_1.MyBC;

import java.io.*;
import java.net.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
public class Client {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            mysocket = new Socket("172.20.10.5", 5308);
            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();
            System.out.println("请输入中缀表达式:");
            String question = scanner.nextLine();
            MyBC myBC = new MyBC();
            String suffix = myBC.toSuffix(question);
            System.out.println(suffix);
            //中缀表达式加密
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[] = suffix.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext);
            out.writeUTF(ctext.length + "");
            for (int i = 0; i < ctext.length; i++) {
                out.writeUTF(ctext[i] + "");
            }
            //对密钥进行加密
            FileInputStream f1=new FileInputStream("Severpub.dat");
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
            //读取自己的DH私钥
            FileInputStream f2=new FileInputStream("Clientpri.dat");
            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();
            //取共享密钥的24位
            byte[] sb2 = new byte[24];
            for(int i =0;i<24;i++){
                sb2[i]=sb[i];
            }
            System.out.println("共享密钥为:");
            for(int i =0;i<sb2.length;i++){
                System.out.print(sb2[i]+" ");
            }
            SecretKeySpec k1=new  SecretKeySpec(sb2,"DESede");
            cp.init(Cipher.ENCRYPT_MODE, k1);
            //对原密钥执行加密
            byte ckey[] = cp.doFinal(kb);
            //传输加密后密钥的长度
            out.writeUTF(ckey.length + "");
            //传输加密后的密钥
            for (int i = 0; i < ckey.length; i++) {
                out.writeUTF(ckey[i] + "");
            }
            System.out.println();
            String result = in.readUTF();
            System.out.println("客户端收到回答" + result);
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println("服务器连接断开" + e);
        }
    }
}

服务器端

package task_4;
import task_1.MyDC;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
public class Sever {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        MyDC myDC = new MyDC();
        try{
            serverForClient = new ServerSocket(5308);
        }catch (IOException e1){
            System.out.println(e1);
        }
        try{
            System.out.println("等待客户呼叫");
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            //获取密文
            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);
            }
            //获取密钥
            String keylength = in.readUTF();
            byte []ckey = new byte[Integer.parseInt(keylength)];
            for(int i=0; i<Integer.parseInt(keylength); i++){
                String temp = in.readUTF();
                ckey[i] = Byte.parseByte(temp);
            }
            FileInputStream f1=new FileInputStream("Clientpub.dat");
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
            //读取自己的DH私钥
            FileInputStream f2=new FileInputStream("Severpri.dat");
            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();
            byte[] sb2 = new byte[24];
            for(int i =0;i<24;i++){
                sb2[i]=sb[i];
            }
            System.out.println("共享密钥为:");
            for(int i =0;i<sb2.length;i++){
                System.out.print(sb2[i]+" ");
            }
            SecretKeySpec k1=new  SecretKeySpec(sb2,"DESede");
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k1);
            //对密钥进行解密
            byte []pkey=cp.doFinal(ckey);
            //密文解密
            SecretKeySpec k=new  SecretKeySpec(pkey,"DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            byte []ptext=cp.doFinal(ctext);
            String suffix = new String(ptext,"UTF8");
            System.out.println();
            System.out.println("客户端收到提问:"+suffix);
            out.writeUTF(myDC.evaluate(suffix)+"");
            System.out.println("已将结果发送至客户端");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("连接断开"+e);
        }
    }
}

运行截图

客户端

服务器端

网络编程与安全-5

实验要求

完整性校验结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题

  1. 基于Java Socket实现客户端/服务器功能,传输方式用TCP
  2. 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文和明文的MD5値发送给服务器
  3. 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
  4. 服务器接收到后缀表达式表达式后,进行解密,解密后计算明文的MD5值,和客户端传来的MD5进行比较,一致则调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
  5. 客户端显示服务器发送过来的结果
  6. 上传测试结果截图和码云链接

实验步骤

1.在3的基础上参考娄老师密码学博客的MD-5的DigestPass代码,计算明文和密文的摘要信息并通过网络传输就行

实验代码

客户端

package task_5;

import task_1.MyBC;

import java.io.*;
import java.net.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
public class Client {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            mysocket = new Socket("172.30.6.68", 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();
            System.out.println("请输入中缀表达式:");
            String question = scanner.nextLine();
            MyBC myBC = new MyBC();
            String suffix = myBC.toSuffix(question);
            System.out.println(suffix);
            String x=suffix;
            MessageDigest m=MessageDigest.getInstance("MD5");
            m.update(x.getBytes("UTF8"));
            byte s[ ]=m.digest( );
            String md5m="";
            for (int i=0; i<s.length; i++){
                md5m+=Integer.toHexString((0x000000ff & s[i]) |
                        0xffffff00).substring(6);
            }
            System.out.println(md5m);
            byte md5mb[] = md5m.getBytes("UTF8");
            out.writeUTF(md5mb.length + "");
            for (int i = 0; i < md5mb.length; i++) {
                out.writeUTF(md5mb[i] + "");
            }
            //中缀表达式加密
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[] = suffix.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext);
            out.writeUTF(ctext.length + "");
            for (int i = 0; i < ctext.length; i++) {
                out.writeUTF(ctext[i] + "");
            }
            //对密钥进行加密
            FileInputStream f1=new FileInputStream("Severpub.dat");
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
            //读取自己的DH私钥
            FileInputStream f2=new FileInputStream("Clientpri.dat");
            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();
            //取共享密钥的24位
            byte[] sb2 = new byte[24];
            for(int i =0;i<24;i++){
                sb2[i]=sb[i];
            }
            System.out.println("共享密钥为:");
            for(int i =0;i<sb2.length;i++){
                System.out.print(sb2[i]+" ");
            }
            SecretKeySpec k1=new  SecretKeySpec(sb2,"DESede");
            cp.init(Cipher.ENCRYPT_MODE, k1);
            //对原密钥执行加密
            byte ckey[] = cp.doFinal(kb);
            //传输加密后密钥的长度
            out.writeUTF(ckey.length + "");
            //传输加密后的密钥
            for (int i = 0; i < ckey.length; i++) {
                out.writeUTF(ckey[i] + "");
            }
            System.out.println();
            String result = in.readUTF();
            System.out.println("客户端收到回答" + result);
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println("服务器连接断开" + e);
        }
    }
}

服务器端

package task_5;
import task_1.*;
import java.io.*;
import java.net.*;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
public class Sever {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        MyDC myDC = new MyDC();
        try{
            serverForClient = new ServerSocket(2010);
        }catch (IOException e1){
            System.out.println(e1);
        }
        try{
            System.out.println("等待客户接入");
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            //获取明文MD5
            String MD5length = in.readUTF();
            byte []MD5 = new byte[Integer.parseInt(MD5length)];
            for(int i=0; i<Integer.parseInt(MD5length); i++){
                String temp1 = in.readUTF();
                MD5[i] = Byte.parseByte(temp1);
            }
            //获取密文
            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);
            }
            //获取密钥
            String keylength = in.readUTF();
            byte []ckey = new byte[Integer.parseInt(keylength)];
            for(int i=0; i<Integer.parseInt(keylength); i++){
                String temp = in.readUTF();
                ckey[i] = Byte.parseByte(temp);
            }
            //密钥解密
            FileInputStream f1=new FileInputStream("Clientpub.dat");
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
            //读取自己的DH私钥
            FileInputStream f2=new FileInputStream("Severpri.dat");
            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();
            byte[] sb2 = new byte[24];
            for(int i =0;i<24;i++){
                sb2[i]=sb[i];
            }
            SecretKeySpec k1=new  SecretKeySpec(sb2,"DESede");
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k1);
            byte []pkey=cp.doFinal(ckey);
            //密文解密
            SecretKeySpec k=new  SecretKeySpec(pkey,"DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            byte []ptext=cp.doFinal(ctext);
            String suffixquestion = new String(ptext,"UTF8");
            //解密后的MD5
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(suffixquestion.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);
            }
            System.out.println("解密后的MD5");
            System.out.println(result);
            System.out.println("服务器收到提问"+suffixquestion);
            out.writeUTF(myDC.evaluate(suffixquestion)+"");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("连接断开!"+e);
        }
    }
}

运行截图:

客户端

服务器端

问题与解决方案

问题1:第4个在生成共享密钥给原密钥加密的时候,总是出错
问题1解决方法:在参考学长学姐的博客后,发现给原秘钥加密,只需要使用共享密钥的前24位,截取前24位共享密钥给原密钥加密就不会报错了。

posted on 2019-06-02 11:55  5303柴轩达  阅读(159)  评论(0编辑  收藏  举报

导航