20175212童皓桢 实验五 网络编程与安全

时间:2022-09-16 19:22:27

20175212童皓桢 实验五 网络编程与安全

实验内容

  • 结对编程,完成网络编程与安全相关内容

    实验步骤

    任务一

    任务一要求:
  1. 结对实现中缀表达式转后缀表达式的功能 MyBC.java
  2. 结对实现从上面功能中获取的表达式中实现后缀表达式求值的功能,调用MyDC.java
    实验过程:
    由中缀式求得后缀式可以使用栈,伪代码如下:
-   设立一个栈,存放运算符,首先栈为空;
-   从左到右扫描中缀式,若遇到操作数,直接输出,并输出一个空格作为两个操作数的分隔符;
-   若遇到运算符,则与栈顶比较,比栈*别高则进栈,否则退出栈顶元素并输出,然后输出一个空格作分隔符;
-   若遇到左括号,进栈;若遇到右括号,则一直退栈输出,直到退到左括号止。
-   当栈变成空时,输出的结果即为后缀表达式
后缀表达式求值伪代码如下:
-   设置一个操作数栈,开始栈为空;
-   从左到右遍历后缀表达式,遇操作数,进栈;
-   若遇运算符,则从栈中退出两个元素,先退出的放到运算符的右边,后退出的放到运算符左边,运算后的结果再进栈,直到后缀表达式遍历完毕。
-   重复以上步骤,直至后缀表达式结束,栈中最后一个数字就是表达式的值。

实验代码:

  • MyDC
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 '-':
                    getOp(ch, 1);
                    break;
                case '*':
                case '/':
                    getOp(ch, 2);
                    break;
                case '(':
                    theStack.push(ch);
                    break;
                case ')':
                    getParen(ch);
                    break;
                default:
                    output = output + ch;
                    break;
            }
        }
        while (!theStack.isEmpty()) {
            output = output + theStack.pop();
        }
        return output;
    }

    public void getOp(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 getParen(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);
        }
    }
}
  • MyDC
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 str)
    {
        int op1, op2, result = 0;
        String token;
        StringTokenizer tokenizer = new StringTokenizer (str);

        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;
    }
}

  • MyBCTest
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 str)
    {
        int op1, op2, result = 0;
        String token;
        StringTokenizer tokenizer = new StringTokenizer (str);

        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;
    }
}

运行结果:
20175212童皓桢 实验五 网络编程与安全

任务二

任务二要求:

1人负责客户端,一人负责服务器

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

实验过程

  • java.net.Socket:

  • 套接字是一个网络连接的端点。在java中,使用java.net.Socket对象来表示一个套接字。
  • 要创建一个套接字,可以使用Socket的构造方法,如:public Socket(java.lang.String host, int port)。其中,host是远程机器名或IP地址,port是远程应用程序的端口号。
  • 一旦成功创建了Socket类的一个实例,就可以使用它发送或接收字节流。要发送字节流,必须先调用Socket类的getOutputStream方法来获取一个java.io.OutputStream对象。要向远程应用程序发送文本,通常要从返回的OutputStream对象构建一个java.io.PrintWriter对象。要接收来自连接的另一端的字节流,可以调用Socket类的getInputStream方法,它返回一个java.io.InputStream。
    『java.net.ServerSocket』:
  • ServerSocket是服务器套接字的一个实现。ServerSocket和Socket不同,服务器套接字的角色是,等待来自客户端的连接请求。一旦服务器套接字获得了一个连接请求,它就会创建一个Socket实例,以处理和客户端的通信。

  • Address

import java.net.*;

public class Address {

    public static void main(String[] args) throws UnknownHostException {

        InetAddress net = InetAddress.getLocalHost();

        System.out.println(net.toString());

    }

}
  • Client
import java.io.*;
import java.net.*;

public class Client {
    public static void main(String args[]) {
        System.out.println("客户端启动...");
        //while (true) {
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            mysocket = new Socket("192.168.56.1", 2019);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            System.out.println("请输入:");
            String str = new BufferedReader(new InputStreamReader(System.in)).readLine();

            MyBC turner = new MyBC(str);
            String infix;
            infix=turner.doTrans();
            StringBuilder newInfix = new StringBuilder(infix.replace(" ",""));
            for (int i = 1; i < infix.length()+(i+1)/2 ; i=i+2) {
                newInfix.insert(i," ");
            }
            out.writeUTF(newInfix.toString());//调用toString()方法,返回newInflx的String值,以便调用writeUTF方法

            String s = in.readUTF();   //in读取信息,堵塞状态
            System.out.println("客户收到服务器的回答:" + s);
            Thread.sleep(500);//在500毫秒数让当前正在执行的线程休眠
        } catch (Exception e) {
            System.out.println("服务器已断开" + e);
        }
        //}
    }
}
  • Server
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        int answer;
        //while (true) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(2019);
        } 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 s = in.readUTF(); // in读取信息,堵塞状态
            System.out.println("服务器收到客户的提问:" + s);
            MyDC myDC = new MyDC();
            answer = myDC.evaluate(s);
            out.writeUTF(answer + "");
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println("客户已断开" + e);
        }
        //}
    }
}

运行结果:
20175212童皓桢 实验五 网络编程与安全
20175212童皓桢 实验五 网络编程与安全

任务三

任务三要求:

1人负责客户端,一人负责服务器

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

public class Client {
    public static void main(String args[]) {
        System.out.println("客户端启动...");
        //while (true) {
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            mysocket = new Socket("192.168.56.1", 2019);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            System.out.println("请输入:");
            String str = new BufferedReader(new InputStreamReader(System.in)).readLine();

            MyBC turner = new MyBC(str);
            String infix;
            infix=turner.doTrans();
            StringBuilder newInfix = new StringBuilder(infix.replace(" ",""));
            for (int i = 1; i < infix.length()+(i+1)/2 ; i=i+2) {
                newInfix.insert(i," ");
            }

            String str1=newInfix.toString();//DES加密
            String a=null;
            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[]=str1.getBytes("UTF8");
            byte ctext[]=cp.doFinal(ptext);
            for(int i=0;i<ctext.length;i++){
                a+=String.valueOf(ctext[i]);
            }
            FileOutputStream f2=new FileOutputStream("SEnc.dat");
            f2.write(ctext);

            out.writeUTF(a);//调用toString()方法,返回newInflx的String值,以便调用writeUTF方法
            String s = in.readUTF();   //in读取信息,堵塞状态
            System.out.println("客户收到服务器的回答:" + s);
            Thread.sleep(500);//在500毫秒数让当前正在执行的线程休眠
        } catch (Exception e) {
            System.out.println("服务器已断开" + e);
        }
        //}
    }
}
  • Server.java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        int answer;
        //while (true) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(2019);
        } 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 s = in.readUTF(); // in读取信息,堵塞状态

            // 获取密文
            FileInputStream f=new FileInputStream("SEnc.dat");
            int num=f.available();
            byte[ ] ctext=new byte[num];
            f.read(ctext);
            // 获取密钥
            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);
            MyDC myDC = new MyDC();
            answer = myDC.evaluate(p);
            out.writeUTF(answer + "");
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println("客户已断开" + e);
        }
        //}
    }
}
  • Skey_DES.java
import java.io.*;
import javax.crypto.*;
public class Skey_DES{
    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.dat");
        ObjectOutputStream b=new  ObjectOutputStream(f);
        b.writeObject(k);
    }
}
  • Skey_kb.java
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]+",");
        }
    }
}

运行结果:
20175212童皓桢 实验五 网络编程与安全
20175212童皓桢 实验五 网络编程与安全

任务四

任务四要求:

1人负责客户端,一人负责服务器

  1. 注意责任归宿,要会通过测试证明自己没有问题
  2. 基于Java Socket实现客户端/服务器功能,传输方式用TCP
  3. 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文发送给服务器
  4. 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
  5. 服务器接收到后缀表达式表达式后,进行解密,然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
  6. 客户端显示服务器发送过来的结果
  • Client
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Client {
    public static void main(String []args) throws Exception
    {
        try
        {
            // 1、创建客户端Socket,指定服务器地址和端口
            Socket socket=new Socket("192.168.56.1",2019);

            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();

            // 读取对方的DH公钥
            FileInputStream f1=new FileInputStream("Bpub");
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
            //读取自己的DH私钥
            FileInputStream f2=new FileInputStream("Asec");
            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();
            //System.out.println(sb.length);
            byte[]ssb=new byte[24];
            for(int i=0;i<24;i++)
                ssb[i]=sb[i];
            Key k=new SecretKeySpec(ssb,"DESede");
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[]=expression.getBytes("UTF-8");
            byte ctext[]=cp.doFinal(ptext);
            String Str=new String(ctext,"ISO-8859-1");


            while (!readline.equals("end")) {
                // 若从标准输入读入的字符串为 "end"则停止循环
                write.println(Str);
                // 将从系统标准输入读入的字符串输出到Server
                write.flush();
                // 刷新输出流,使Server马上收到该字符串
                System.out.println("加密后的信息:" + Str);
                // 在系统标准输出上打印读入的字符串
                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
        {

        }

    }
}
  • Serve
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Server{
    public static void main(String []args) throws Exception
    {
        ServerSocket sc = null;
        Socket socket=null;
        try
        {
            MyDC evaluator = new MyDC();

            sc= new ServerSocket(2019);//创建服务器套接字
            //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);
            //使用服务器端RSA的私钥对DES的密钥进行解密
            String aline2=in.readLine();
            System.out.println("客户端发来的信息为:"+aline2);


            // 获取密钥
            byte[]ctext=aline2.getBytes("ISO-8859-1");
            // 读取对方的DH公钥
            FileInputStream f1=new FileInputStream("Bpub");
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
            //读取自己的DH私钥
            FileInputStream f2=new FileInputStream("Asec");
            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[]ssb=new byte[24];
            for(int i=0;i<24;i++)
                ssb[i]=sb[i];
            SecretKeySpec k=new  SecretKeySpec(ssb,"DESede");

            // 解密
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            byte []ptext=cp.doFinal(ctext);
            // 显示明文
            String p=new String(ptext,"UTF8");
            int ans = evaluator.evaluate(p);
            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;
    }
}
  • 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 main(String args[ ]) throws Exception{
        // 读取对方的DH公钥
        FileInputStream f1=new FileInputStream("Bpub");
        ObjectInputStream b1=new ObjectInputStream(f1);
        PublicKey  pbk=(PublicKey)b1.readObject( );
//读取自己的DH私钥
        FileInputStream f2=new FileInputStream("Asec");
        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();
        for(int i=0;i<sb.length;i++){
            System.out.print(sb[i]+",");
        }
        SecretKeySpec k=new  SecretKeySpec(sb,"DESede");
    }
}
  • Key_DH.java
import java.io.*;
import java.math.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;

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{
    //三个静态变量的定义从
// C:\j2sdk-1_4_0-doc\docs\guide\security\jce\JCERefGuide.html
// 拷贝而来
// The 1024 bit Diffie-Hellman modulus values used by SKIP
    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 main(String args[ ]) 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("Bpub");
        ObjectOutputStream b1=new  ObjectOutputStream(f1);
        b1.writeObject(pbk);
        // 保存私钥
        FileOutputStream  f2=new FileOutputStream("Asec");
        ObjectOutputStream b2=new  ObjectOutputStream(f2);
        b2.writeObject(prk);
    }
}

运行结果:
20175212童皓桢 实验五 网络编程与安全
20175212童皓桢 实验五 网络编程与安全

任务五

完整性校验结对编程:

1人负责客户端,一人负责服务器

  1. 注意责任归宿,要会通过测试证明自己没有问题
  2. 基于Java Socket实现客户端/服务器功能,传输方式用TCP
  3. 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文和明文的MD5値发送给服务器
  4. 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
  5. 服务器接收到后缀表达式表达式后,进行解密,解密后计算明文的MD5值,和客户端传来的MD5进行比较,一致则调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
  6. 客户端显示服务器发送过来的结果
  7. 上传测试结果截图和码云链接
  • Serve
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.interfaces.*;
import java.math.*;

public class Server {
    public static void main(String args[]) throws Exception {
        ServerSocket link = null;
        Socket socket = null;
        try {
            link = new ServerSocket(3);// 创建服务器套接字
            //System.out.println("端口号:" + link.getLocalPort());
            System.out.println("等待客户连接");
            socket = link.accept(); // 等待客户端连接
            System.out.println("已经建立连接");
            //获得网络输入流对象的引用
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //获得网络输出流对象的引用
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            // 使用服务器端RSA的私钥对DES的密钥进行解密

            String line = in.readLine();
            BigInteger cipher = new BigInteger(line);
            FileInputStream f = new FileInputStream("Skey_RSA_priv.dat");
            ObjectInputStream b = new ObjectInputStream(f);
            RSAPrivateKey prk = (RSAPrivateKey) b.readObject();
            BigInteger d = prk.getPrivateExponent();
            BigInteger n = prk.getModulus();//mod n
            BigInteger m = cipher.modPow(d, n);//m=d (mod n)
            System.out.println("d= " + d);
            System.out.println("n= " + n);
            System.out.println("m= " + m);
            byte[] keykb = m.toByteArray();
            // 使用DES对密文进行解密
            String readline = in.readLine();//读取客户端传送来的数据
            FileInputStream f2 = new FileInputStream("keykb1.dat");
            int num2 = f2.available();
            byte[] ctext = parseHexStr2Byte(readline);
            Key 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); //打印解密结果
            // 使用Hash函数检测明文完整性
            String aline3 = in.readLine();
            String x = p;
            MessageDigest m2 = MessageDigest.getInstance("MD5");//使用MD5算法返回实现指定摘要算法的 MessageDigest对象
            m2.update(x.getBytes());
            byte a[] = m2.digest();
            String result = "";
            for (int i = 0; i < a.length; i++) {
                result += Integer.toHexString((0x000000ff & a[i]) | 0xffffff00).substring(6);
            }
            System.out.println("MD5:"+result);
            if (aline3.equals(result)) {
                System.out.println("匹配成功");
            }
            MyDC evaluator = new MyDC();
            int _result = evaluator.value(p);
            out.println(_result);
            out.close();
            in.close();
            link.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    //二进制转换成十六进制,防止byte[]数字转换成string类型时造成的数据损失
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());//将字符串中的小写字母转换成大写字母,然后加在字符串上
        }
        return sb.toString();
    }
    //将十六进制转换为二进制
    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;
    }

}

Client

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

public class Client {
    public static void main(String args[]) throws Exception {
        try {
            KeyGenerator kg = KeyGenerator.getInstance("DESede");
            kg.init(168);
            SecretKey k = kg.generateKey();
            byte[] ptext2 = k.getEncoded();
            Socket socket = new Socket("127.0.0.1", 3);
            System.out.println("客户端成功启动,等待客户端呼叫");
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            //RSA算法,使用服务器端的公钥对DES的密钥进行加密
            FileInputStream f3 = new FileInputStream("Skey_RSA_pub.dat");
            ObjectInputStream b2 = new ObjectInputStream(f3);
            RSAPublicKey pbk = (RSAPublicKey) b2.readObject();
            BigInteger e = pbk.getPublicExponent();
            BigInteger n = pbk.getModulus();
            BigInteger m = new BigInteger(ptext2);
            BigInteger c = m.modPow(e, n);
            String cs = c.toString();
            out.println(cs); // 通过网络将加密后的秘钥传送到服务器
            System.out.println("请输入中缀表达式:");
            //用DES加密明文得到密文
            String s = stdin.readLine(); // 从键盘读入待发送的数据
            String postfix = MyBC.toPostfix(s);
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[] = postfix.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext);
            String str = parseByte2HexStr(ctext);
            out.println(str); // 通过网络将密文传送到服务器

            // 将客户端明文的Hash值传送给服务器
            String x = postfix;
            MessageDigest m2 = MessageDigest.getInstance("MD5");
            m2.update(x.getBytes());
            byte a[] = m2.digest();
            String result = "";
            for (int i = 0; i < a.length; i++) {
                result += Integer.toHexString((0x000000ff & a[i]) | 0xffffff00).substring(6);
            }
            System.out.println("MD5:"+result);
            out.println(result);//通过网络将明文的Hash函数值传送到服务器
            str = in.readLine();// 从网络输入流读取结果
            System.out.println("从服务器接收到的结果为:" + str); // 输出服务器返回的结果
        } catch (Exception e) {
            System.out.println(e);//输出异常
        } finally {
        }

    }

    //将十六进制转换成二进制
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}

运行结果:
20175212童皓桢 实验五 网络编程与安全
20175212童皓桢 实验五 网络编程与安全

实验中遇到的问题

问题一:输入表达算式时提示断开连接
20175212童皓桢 实验五 网络编程与安全
解决办法:输入表达式时一气呵成,而不能像平常一样对已输入的括号内的内容进行修改

参考博客

https://www.cnblogs.com/zxy20175227/p/10923041.html
http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA

结对伙伴及博客链接

20175227