實驗五實驗報告

1、實驗報告封面

課程:Java程序設計 班級:1752班 姓名:羅樂琦 學號:20175219
指導教師:婁嘉鵬 實驗日期:2019年5月28日
實驗時間:--- 實驗序號:實驗五
實驗名稱:網絡編程與安全html

2、實驗內容與步驟

任務一要求

  • 參考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA
  • 結對實現中綴表達式轉後綴表達式的功能 MyBC.java
  • 結對實現從上面功能中獲取的表達式中實現後綴表達式求值的功能,調用MyDC.java
  • 上傳測試代碼運行結果截圖和碼雲連接

實驗代碼

getHostAddress.javajava

import java.net.*;
public class getHostAddress {
    public static void main(String[] args) {
        try{
            InetAddress hostaddress = InetAddress.getLocalHost();
            System.out.println(hostaddress.toString());
        }catch (UnknownHostException e){
            System.out.println(e);
        }
    }
}

MyBC.javagit

import java.io.*;
import java.util.Stack;

public class MyBC {
    public static void main(String[] args) {
        int i, f;
        double result;
        int zuokuohao1 = 0;
        String ch2 = new String();
        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        try {
            String str = buf.readLine();
            f = chu0.chu0(str);
            if (f == 0) {
                char[] ch1 = str.toCharArray();
                int len1 = ch1.length;
                Stack<Character> operators = new Stack<>();
                Stack output = new Stack<>();
                zuokuohao1 = rpn(operators, output, str);
                for (i = 0; i < len1 - 2 * zuokuohao1; i++) {
                    ch2 = output.pop() + ch2;
                }
                System.out.println(ch2);
            } else {
                System.out.println("除數爲0");
            }
        } catch (IOException e) {
        }
    }

    public static int rpn(Stack<Character> operators, Stack output, String str) {
        char[] chars = str.toCharArray();
        int pre = 0;
        boolean digital;
        int zuokuohao = 0;
        int len = chars.length;
        int bracket = 0;
        for (int i = 0; i < len; ) {
            pre = i;
            digital = Boolean.FALSE;
            while (i < len && !Operator.isOperator(chars[i])) {
                i++;
                digital = Boolean.TRUE;
            }
            if (digital) {
                output.push(str.substring(pre, i));
            } else {
                char o = chars[i++];
                if (o == '(') {
                    bracket++;
                    zuokuohao++;
                }
                if (bracket > 0) {
                    if (o == ')') {
                        while (!operators.empty()) {
                            char top = operators.pop();
                            if (top == '(') {
                                break;
                            }
                            output.push(top);
                        }
                        bracket--;
                    } else {
                        while (!operators.empty() && operators.peek() != '(' && Operator.cmp(o, operators.peek()) <= 0) {
                            output.push(operators.pop());
                        }
                        operators.push(o);
                    }
                } else {
                    while (!operators.empty() && Operator.cmp(o, operators.peek()) <= 0) {
                        output.push(operators.pop());
                    }
                    operators.push(o);
                }
            }
        }
        while (!operators.empty()) {
            output.push(operators.pop());
        }
        return zuokuohao;
    }
}

enum Operator {
    ADD('+', 1), SUBTRACT('-', 1),
    MULTIPLY('*', 2), DIVIDE('/', 2),
    LEFT_BRACKET('(', 3), RIGHT_BRACKET(')', 3);
    char value;
    int priority;

    Operator(char value, int priority) {
        this.value = value;
        this.priority = priority;
    }

    public static int cmp(char c1, char c2) {
        int p1 = 0;
        int p2 = 0;
        for (Operator o : Operator.values()) {
            if (o.value == c1) {
                p1 = o.priority;
            }
            if (o.value == c2) {
                p2 = o.priority;
            }
        }
        return p1 - p2;
    }

    public static boolean isOperator(char c) {
        for (Operator o : Operator.values()) {
            if (o.value == c) {
                return true;
            }
        }
        return false;
    }
}

class chu0 {
    public static int chu0(String s) {
        int i;
        int flag = 0;
        char[] ch = s.toCharArray();
        for (i = 0; i < ch.length; i++) {
            if (ch[i] == '/' && ch[i + 1] == '0') {
                flag = 1;
            }
        }
        return flag;
    }
}

MyDC.java算法

import java.util.StringTokenizer;
import java.util.Stack;

public class MyDC {
    /**
     * constant for addition symbol
     */
    private final char ADD = '+';
    /**
     * constant for subtraction symbol
     */
    private final char SUBTRACT = '-';
    /**
     * constant for multiplication symbol
     */
    private final char MULTIPLY = '*';
    /**
     * constant for division symbol
     */
    private final char DIVIDE = '/';
    /**
     * the stack
     */
    private Stack<Integer> stack;

    public MyDC() {
        stack = new Stack<Integer>();
    }

    public int evaluate(String expr) {
        int op1, op2, result = 0;
        String token;
        StringTokenizer tokenizer = new StringTokenizer(expr);
        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();
            //若是是運算符,調用isOperator
            if (isOperator(token)) {
                //從棧中彈出操做數2
                op2 = stack.pop();
                //從棧中彈出操做數1
                op1 = stack.pop();
                //根據運算符和兩個操做數調用evalSingleOp計算result;
                result = evalSingleOp(token.charAt(0), op1, op2);
                //計算result入棧;
                stack.push(result);
            } else//若是是操做數
                //操做數入棧;
                stack.push(Integer.parseInt(token));
        }

        return result;
    }

    private boolean isOperator(String token) {
        return (token.equals("+") || token.equals("-") ||
                token.equals("*") || token.equals("/"));
    }

    private int evalSingleOp(char operation, int op1, int op2) {
        int result = 0;

        switch (operation) {
            case ADD:
                result = op1 + op2;
                break;
            case SUBTRACT:
                result = op1 - op2;
                break;
            case MULTIPLY:
                result = op1 * op2;
                break;
            case DIVIDE:
                result = op1 / op2;
        }

        return result;
    }
}

MyDCTester.javaexpress

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

實驗截圖

任務二要求

  • 1人負責客戶端,1人負責服務器。
  • 注意責任歸宿,要會經過測試證實本身沒有問題
  • 基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式經過網絡發送給服務器
  • 服務器接收到後綴表達式,調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
  • 客戶端顯示服務器發送過來的結果
  • 上傳測試結果截圖和碼雲連接

實驗代碼

對MyBC.java稍作修改編程

import java.io.*;
import java.util.Stack;

public class MyBC {
    public static String transform(String str) {
        int i, f;
        double result;
        int zuokuohao1 = 0;
        String ch2 = new String();
        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        f = chu0.chu0(str);
        if (f == 0) {
            char[] ch1 = str.toCharArray();
            int len1 = ch1.length;
            Stack<Character> operators = new Stack<>();
            Stack output = new Stack<>();
            zuokuohao1 = rpn(operators, output, str);
            for (i = 0; i < len1 - 2 * zuokuohao1; i++) {
                ch2 = output.pop() +" "+ ch2;
            }
            System.out.println("轉換成後綴表達式:"+ ch2);
        } else {
            System.out.println("除數爲0");
        }
        return ch2;
    }

    public static int rpn(Stack<Character> operators, Stack output, String str) {
        char[] chars = str.toCharArray();
        int pre = 0;
        boolean digital;
        int zuokuohao = 0;
        int len = chars.length;
        int bracket = 0;
        for (int i = 0; i < len; ) {
            pre = i;
            digital = Boolean.FALSE;
            while (i < len && !Operator.isOperator(chars[i])) {
                i++;
                digital = Boolean.TRUE;
            }
            if (digital) {
                output.push(str.substring(pre, i));
            } else {
                char o = chars[i++];
                if (o == '(') {
                    bracket++;
                    zuokuohao++;
                }
                if (bracket > 0) {
                    if (o == ')') {
                        while (!operators.empty()) {
                            char top = operators.pop();
                            if (top == '(') {
                                break;
                            }
                            output.push(top);
                        }
                        bracket--;
                    } else {
                        while (!operators.empty() && operators.peek() != '(' && Operator.cmp(o, operators.peek()) <= 0) {
                            output.push(operators.pop());
                        }
                        operators.push(o);
                    }
                } else {
                    while (!operators.empty() && Operator.cmp(o, operators.peek()) <= 0) {
                        output.push(operators.pop());
                    }
                    operators.push(o);
                }
            }
        }
        while (!operators.empty()) {
            output.push(operators.pop());
        }
        return zuokuohao;
    }
}

enum Operator {
    ADD('+', 1), SUBTRACT('-', 1),
    MULTIPLY('*', 2), DIVIDE('/', 2),
    LEFT_BRACKET('(', 3), RIGHT_BRACKET(')', 3);
    char value;
    int priority;

    Operator(char value, int priority) {
        this.value = value;
        this.priority = priority;
    }

    public static int cmp(char c1, char c2) {
        int p1 = 0;
        int p2 = 0;
        for (Operator o : Operator.values()) {
            if (o.value == c1) {
                p1 = o.priority;
            }
            if (o.value == c2) {
                p2 = o.priority;
            }
        }
        return p1 - p2;
    }

    public static boolean isOperator(char c) {
        for (Operator o : Operator.values()) {
            if (o.value == c) {
                return true;
            }
        }
        return false;
    }
}

class chu0 {
    public static int chu0(String s) {
        int i;
        int flag = 0;
        char[] ch = s.toCharArray();
        for (i = 0; i < ch.length; i++) {
            if (ch[i] == '/' && ch[i + 1] == '0') {
                flag = 1;
            }
        }
        return flag;
    }
}

Sever2.java數組

import java.io.*;
import java.net.*;
public class Sever2 {
    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 e){
            System.out.println("端口已被佔用"+e);
        }
        try{
            System.out.println("等待客戶呼叫");
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String suffix = in.readUTF();
            System.out.println("收到後綴表達式:"+suffix);
            out.writeUTF(myDC.evaluate(suffix)+"");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("客戶已斷開"+e);
        }
    }
}

Client2.java安全

import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.Stack;

public class Client2 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("192.168.56.1",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            System.out.println("請輸入運算式:");
            String str = inn.nextLine();
            String suffix = MyBC.transform(str);
            out.writeUTF(suffix);
            String result = in.readUTF();
            System.out.println("求值爲:"+result);
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("服務器已斷開"+e)#;
        }
    }
}

實驗截圖

任務三要求

  • 1人負責客戶端,1人負責服務器
  • 注意責任歸宿,要會經過測試證實本身沒有問題
  • 基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密後經過網絡把密文發送給服務器
  • 服務器接收到後綴表達式表達式後,進行解密(和客戶端協商密鑰,能夠用數組保存),而後調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
  • 客戶端顯示服務器發送過來的結果
  • 上傳測試結果截圖和碼雲連接

實驗代碼

Client3.java服務器

import java.io.*;
import java.net.*;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Client3 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("192.168.56.1",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            KeyGenerator kg=KeyGenerator.getInstance("AES");
            kg.init(128);
            SecretKey k=kg.generateKey();
            Cipher cp=Cipher.getInstance("AES");
            cp.init(Cipher.ENCRYPT_MODE,k);
            System.out.println("請輸入運算式:");
            String str = inn.nextLine();
            String suffix = MyBC.transform(str);
            byte[]ptext=suffix.getBytes();
            byte[]ctext=cp.doFinal(ptext);
            byte kb[] = k.getEncoded();
            String str1 = Binary.parseByte2HexStr(ctext);
            String str2 = Binary.parseByte2HexStr(kb);
            out.writeUTF(str1);
            out.writeUTF(str2);
            String result = in.readUTF();
            System.out.println("求值爲:"+result);
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("服務器已斷開"+e);
        }
    }
}

Sever3.java網絡

import java.io.*;
import java.net.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.*;
public class Sever3 {
    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 e){
            System.out.println("端口已被佔用"+e);
        }
        try{
            System.out.println("等待客戶呼叫");
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String str1= in.readUTF();
            byte cipher[] = Binary.parseHexStr2Byte(str1);
            System.out.println("收到密文:"+str1);
            String str2 = in.readUTF();
            byte keyb[] = Binary.parseHexStr2Byte(str2);
            Cipher cp=Cipher.getInstance("AES");
            SecretKeySpec key = new SecretKeySpec(keyb,"AES");
            cp.init(Cipher.DECRYPT_MODE,key);
            byte []ptext=cp.doFinal(cipher);
            String suffix = new String(ptext,"UTF8");
            out.writeUTF(myDC.evaluate(suffix)+"");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("客戶已斷開"+e);
        }
    }
}

Binary.java

public class Binary {
    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;
    }
}

實驗截圖

任務四要求

  • 1人負責客戶端,1人負責服務器
  • 注意責任歸宿,要會經過測試證實本身沒有問題
  • 基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密經過網絡把密文發送給服務器
  • 客戶端和服務器用DH算法進行3DES或AES算法的密鑰交換
  • 服務器接收到後綴表達式表達式後,進行解密,而後調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
  • 客戶端顯示服務器發送過來的結果
  • 上傳測試結果截圖和碼雲連接

實驗代碼

Client4.java

import java.io.*;
import java.net.*;
import java.security.Key;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Client4 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("192.168.56.1",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            KeyGenerator kg=KeyGenerator.getInstance("AES");
            kg.init(128);
            SecretKey k=kg.generateKey();
            Cipher cp=Cipher.getInstance("AES");
            cp.init(Cipher.ENCRYPT_MODE,k);
            System.out.println("請輸入運算式:");
            String str = inn.nextLine();
            String suffix = MyBC.transform(str);
            byte[]ptext=suffix.getBytes();
            byte[]ctext=cp.doFinal(ptext);
            byte kb[] = k.getEncoded();
            String str1 = Binary.parseByte2HexStr(ctext);
            String str2 = Binary.parseByte2HexStr(kb);
            out.writeUTF(str1);
            out.writeUTF(str2);
            Thread.sleep(500);

            Key_DH.createPubAndPriKey("Clientpub.txt","Clientpri.txt");
            FileInputStream fp = new FileInputStream("Clientpub.txt");
            ObjectInputStream bp = new ObjectInputStream(fp);
            Key kp = (Key) bp.readObject();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(kp);
            byte[] kb1 = baos.toByteArray();
            String PubKey1 = Binary.parseByte2HexStr(kb1);
            out.writeUTF(PubKey1);
            Thread.sleep(500);

            String push = in.readUTF();
            byte [] np1= Binary.parseHexStr2Byte(push);
            ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (np1));
            Key k2 = (Key)ois.readObject();;
            FileOutputStream f2 = new FileOutputStream("Serverpub.txt");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k2);
            Thread.sleep(500);

            SecretKeySpec key = KeyAgre.createKey("Serverpub.txt", "Clientpri.txt");

            String result = in.readUTF();
            System.out.println("\n求值爲:"+result);
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("服務器已斷開"+e);
        }
    }
}

Sever4.java

import java.io.*;
import java.net.*;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.*;
public class Sever4 {
    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 e){
            System.out.println("端口已被佔用"+e);
        }
        try{
            System.out.println("等待客戶呼叫");
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String str1= in.readUTF();
            byte cipher[] = Binary.parseHexStr2Byte(str1);
            System.out.println("收到密文:"+str1);
            String str2 = in.readUTF();
            byte keyb[] = Binary.parseHexStr2Byte(str2);

            String PubKey = in.readUTF();
            byte np[] = Binary.parseHexStr2Byte(PubKey);

            Key_DH.createPubAndPriKey("Serverpub.txt","Serverpri.txt");

            FileInputStream fp = new FileInputStream("Serverpub.txt");
            ObjectInputStream bp = new ObjectInputStream(fp);
            Key kp = (Key) bp.readObject();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(kp);
            byte[] kb = baos.toByteArray();
            String pop = Binary.parseByte2HexStr(kb);
            out.writeUTF(pop);
            Thread.sleep(500);

            SecretKeySpec key = KeyAgre.createKey("Serverpub.txt","Clientpri.txt");

            Cipher cp=Cipher.getInstance("AES");
            SecretKeySpec key1 = new SecretKeySpec(keyb,"AES");
            cp.init(Cipher.DECRYPT_MODE,key1);
            byte []ptext=cp.doFinal(cipher);
            String suffix = new String(ptext,"UTF8");
            out.writeUTF(myDC.evaluate(suffix)+"");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("客戶已斷開"+e);
        }
    }
}

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.*;

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 createPubAndPriKey(String s1,String s2) throws Exception{
        DHParameterSpec DHP=
                new DHParameterSpec(skip1024Modulus,skip1024Base);

        KeyPairGenerator kpg= KeyPairGenerator.getInstance("DH");
        kpg.initialize(DHP);
        KeyPair kp=kpg.genKeyPair();

        PublicKey pbk=kp.getPublic();
        PrivateKey prk=kp.getPrivate();
        // 保存公鑰
        FileOutputStream  f1=new FileOutputStream(s1);
        ObjectOutputStream b1=new  ObjectOutputStream(f1);
        b1.writeObject(pbk);
        // 保存私鑰
        FileOutputStream  f2=new FileOutputStream(s2);
        ObjectOutputStream b2=new  ObjectOutputStream(f2);
        b2.writeObject(prk);
    }
}

KeyAgre.java

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

public class KeyAgre{
    public static SecretKeySpec createKey(String s1, String s2) throws Exception{
        // 讀取對方的DH公鑰
        FileInputStream f1=new FileInputStream(s1);
        ObjectInputStream b1=new ObjectInputStream(f1);
        PublicKey  pbk=(PublicKey)b1.readObject( );
//讀取本身的DH私鑰
        FileInputStream f2=new FileInputStream(s2);
        ObjectInputStream b2=new ObjectInputStream(f2);
        PrivateKey  prk=(PrivateKey)b2.readObject( );
        // 執行密鑰協定
        KeyAgreement ka=KeyAgreement.getInstance("DH");
        ka.init(prk);
        ka.doPhase(pbk,true);
        //生成共享信息
        System.out.println("共享信息爲:");
        byte[] sb=ka.generateSecret();
        for(int i=0;i<sb.length;i++){
            System.out.print(sb[i]+" ");
        }
        SecretKeySpec k=new  SecretKeySpec(sb,"DESede");
        return k;
    }
}

實驗截圖

任務五要求

  • 1人負責客戶端,1人負責服務器
  • 注意責任歸宿,要會經過測試證實本身沒有問題
  • 基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密經過網絡把密文和明文的MD5値發送給服務器
  • 客戶端和服務器用DH算法進行3DES或AES算法的密鑰交換
  • 服務器接收到後綴表達式表達式後,進行解密,解密後計算明文的MD5值,和客戶端傳來的MD5進行比較,一致則調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
  • 客戶端顯示服務器發送過來的結果
  • 上傳測試結果截圖和碼雲連接

實驗代碼

Client5.java

import java.io.*;
import java.net.*;
import java.security.Key;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Client5 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("192.168.56.1",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            KeyGenerator kg=KeyGenerator.getInstance("AES");
            kg.init(128);
            SecretKey k=kg.generateKey();
            Cipher cp=Cipher.getInstance("AES");
            cp.init(Cipher.ENCRYPT_MODE,k);
            System.out.println("請輸入運算式:");
            String str = inn.nextLine();
            String suffix = MyBC.transform(str);
            byte[]ptext=suffix.getBytes();
            byte[]ctext=cp.doFinal(ptext);
            byte kb[] = k.getEncoded();
            String str1 = Binary.parseByte2HexStr(ctext);
            String str2 = Binary.parseByte2HexStr(kb);
            out.writeUTF(str1);
            out.writeUTF(str2);
            Thread.sleep(500);

            Key_DH.createPubAndPriKey("Clientpub.txt","Clientpri.txt");
            FileInputStream fp = new FileInputStream("Clientpub.txt");
            ObjectInputStream bp = new ObjectInputStream(fp);
            Key kp = (Key) bp.readObject();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(kp);
            byte[] kb1 = baos.toByteArray();
            String PubKey1 = Binary.parseByte2HexStr(kb1);
            out.writeUTF(PubKey1);
            Thread.sleep(500);

            String push = in.readUTF();
            byte [] np1= Binary.parseHexStr2Byte(push);
            ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (np1));
            Key k2 = (Key)ois.readObject();;
            FileOutputStream f2 = new FileOutputStream("Serverpub.txt");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k2);
            Thread.sleep(500);

            SecretKeySpec key = KeyAgre.createKey("Serverpub.txt", "Clientpri.txt");

            String clientMD5 = DigestPass.digestPass(suffix);
            System.out.println("明文MD5值爲:"+ clientMD5);
            out.writeUTF(clientMD5);
            Thread.sleep(500);

            String result = in.readUTF();
            System.out.println("求值爲:"+result);
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("服務器已斷開"+e);
        }
    }
}

Sever5.java

import java.io.*;
import java.net.*;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.*;
public class Sever5 {
    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 e){
            System.out.println("端口已被佔用"+e);
        }
        try{
            System.out.println("等待客戶呼叫");
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String str1= in.readUTF();
            byte cipher[] = Binary.parseHexStr2Byte(str1);
            System.out.println("收到密文:"+str1);
            String str2 = in.readUTF();
            byte keyb[] = Binary.parseHexStr2Byte(str2);

            String PubKey = in.readUTF();
            byte np[] = Binary.parseHexStr2Byte(PubKey);

            Key_DH.createPubAndPriKey("Serverpub.txt","Serverpri.txt");

            FileInputStream fp = new FileInputStream("Serverpub.txt");
            ObjectInputStream bp = new ObjectInputStream(fp);
            Key kp = (Key) bp.readObject();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(kp);
            byte[] kb = baos.toByteArray();
            String pop = Binary.parseByte2HexStr(kb);
            out.writeUTF(pop);
            Thread.sleep(500);

            SecretKeySpec key = KeyAgre.createKey("Serverpub.txt","Clientpri.txt");

            Cipher cp=Cipher.getInstance("AES");
            SecretKeySpec key1 = new SecretKeySpec(keyb,"AES");
            cp.init(Cipher.DECRYPT_MODE,key1);
            byte []ptext=cp.doFinal(cipher);
            String suffix = new String(ptext,"UTF8");
            String serverMD5 = DigestPass.digestPass(suffix);
            System.out.println("解密的MD5值爲:"+serverMD5);
            String clientMD5 = in.readUTF();
            if(serverMD5.equals(clientMD5)) {
                System.out.println("兩組MD5值相等");
                out.writeUTF(myDC.evaluate(suffix) + "");
            }
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("客戶已斷開"+e);
        }
    }
}

DigestPass.java

import java.security.*;
public class DigestPass{
    public static String digestPass(String x) throws Exception{

        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);
        }
        System.out.println(result);
        return result;
    }
}

實驗截圖

相關文章
相關標籤/搜索