2018-2019-2 20175226 實驗五《網絡編程與安全》實驗報告

2018-2019-2 20175226 實驗五《網絡編程與安全》實驗報告

任務一

實驗要求

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

實驗原理

  • 中綴轉後綴表達式
    • 遇到數字,咱們就直接將其輸出。
    • 遇到非數字時,若棧爲空或者該符號爲左括號或者棧頂元素爲括號,直接入棧。
    • 遇到一個右括號,持續出棧並輸出符號,直到棧頂元素爲左括號,而後將左括號出棧(注意,左括號只出棧,不輸出),右括號不入棧。
    • 遇到運算符號且棧非空,查看棧頂元素,若是棧頂元素的運算優先級大於或者等於該運算符號,則持續出棧,直到棧頂元素優先級小於該運算符。最後將該元素入棧。
    • 咱們讀到了輸入的末尾,則將棧中全部元素依次彈出。
  • 經過後綴表達式計算結果
    • 創建一個空棧,遇到數字就入棧,遇到符號就以符號前面的兩個數爲運算數進行計算

實驗代碼

  • 中綴轉後綴表達式MyBC.java
package 實驗五;

import java.util.Stack;
public class MyBC{
    String jieguo = "";
    public MyBC (String[] args) {
        Stack<String> z = new Stack<String>();
        String t = "";
        for (int i = 0; i < args.length; i++) {
            switch (args[i]) {
                case "(":
                    z.push(args[i]);
                    break;
                case "+":
                case "-":
                    while(z.empty() != true) {
                        t = z.pop();
                        if (t.equals("(")) {
                            z.push(t);
                            break;
                        }
                        jieguo = jieguo + t + " ";
                    }
                    z.push(args[i]);
                    break;
                case "*":
                case "/":
                    while(z.empty() != true) {
                        t = z.pop();
                        if (t.equals("+") || t.equals("-") || t.equals("(")) {
                            z.push(t);
                            break;
                        }
                        jieguo = jieguo + t + " ";
                    }
                    z.push(args[i]);
                    break;
                case ")":
                    while (z.empty()== false) {
                        t = z.pop();
                        if (t.equals("(")) {
                            break;
                        } else {
                            jieguo = jieguo + t + " ";
                        }
                    }
                    break;
                case" ":
                    break;

                default:
                    jieguo = jieguo + args[i] + " ";
                    break;
            }

        }

        while (z.empty() == false) {
            jieguo = jieguo + z.pop() + " ";
        }
        System.out.println(jieguo);
    }
}
  • 後綴表達式計算MyDC.java
package 實驗五;

import java.util.Stack;
public class MyDC{
    private static Integer answer;
    public MyDC (String[] args) {
        Stack<String> z = new Stack<String>();
        int num1,num2,d;
        for(int i=0;i<args.length;i++) {
            switch (args[i]){
                case"+":
                    num2 = Integer.valueOf(z.pop());
                    num1 = Integer.valueOf(z.pop());
                    d = num1+num2;
                    z.push(String.valueOf(d));
                    break;
                case"-":
                    num2 = Integer.valueOf(z.pop());
                    num1 = Integer.valueOf(z.pop());
                    d = num1-num2;
                    z.push(String.valueOf(d));
                    break;
                case"*":
                    num2 = Integer.valueOf(z.pop());
                    num1 = Integer.valueOf(z.pop());
                    d = num1*num2;
                    z.push(String.valueOf(d));
                    break;
                case"/":
                    num2 = Integer.valueOf(z.pop());
                    num1 = Integer.valueOf(z.pop());
                    d = num1/num2;
                    z.push(String.valueOf(d));
                    break;
                case"":
                case" ":
                    break;

                default:
                    z.push(args[i]);
                    break;
            }
        }
        while (z.empty() == false) {
            answer =  Integer.valueOf(z.pop());
        }
        System.out.println(answer);
    }
}
  • 測試代碼shiyan5_1 .java
package 實驗五;

import java.util.Scanner;

public class shiyan5_1 {
    public static void main(String[] args) {
        String question = "";
        int result;
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入題目:");
        question = scanner.nextLine();
        String [] str = question.split(" ");
        System.out.println("轉置結果以下:");
        MyBC translate = new MyBC(str);
        String [] str2 = translate.jieguo.split(" ");
        System.out.println("計算結果以下:");
        MyDC answer = new MyDC(str2);
    }
}

實驗截圖

任務二

實驗要求

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

實驗過程及原理

  • 使用InetAddress類的靜態方法getLocalHost()得到一個InetAddress的對象,該對象含有本地機器的IP地址
  • 客戶端套接字:Socket clientSocket = new Socket("服務器的IP地址",一個端口號)
  • SeverSocket對象與服務器端套接字:SeverSocket severForClient = new SeverSocket(端口號)
  • 使用accept()方法將客戶端和服務器的套接字鏈接起來:Socket sc = severForClient.accept()

實驗代碼

  • 訪問本機IPgetHostAddress.java
package 實驗五;

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);
        }
    }
}
  • 客戶端Client.java
package 實驗五;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("169.254.92.198",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            System.out.println("請輸入中綴表達式:");
            String infix = inn.nextLine();
            String [] str = infix.split(" ");
            System.out.println("已傳遞後綴表達式");
            MyBC suffix =new MyBC(str);
            out.writeUTF(suffix.jieguo);
            String result = in.readUTF();
            System.out.println("已收到計算結果"+result);
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("雙方已斷開鏈接"+e);
        }
    }
}
  • 服務器Sever.java
package 實驗五;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.io.*;
import java.net.*;
public class Sever {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;

        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();
            String [] str = suffix.split(" ");
            System.out.println("收到問題,正在解決:"+suffix);
            System.out.println("已傳輸得出結果:");
            MyDC myDC = new MyDC(str);
            String answer =  String.valueOf(myDC.answer);
            out.writeUTF(answer+"");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("雙方已斷開鏈接");
        }
    }
}

實驗截圖

  • 訪問本機IP
    java

  • 客戶端
    git

  • 服務器
    算法

任務三

實驗要求

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

實驗原理及過程

  • 客戶端
    • 獲取並初始化密鑰生成器KeyGenerator kg=KeyGenerator.getInstance("DESede")kg.init(168);
    • 生成密鑰SecretKey k=kg.generateKey( );
    • 傳送密鑰長度及密鑰內容
    • 建立並初始化密碼器Cipher cp=Cipher.getInstance("DESede")cp.init(Cipher.ENCRYPT_MODE, k);
    • 執行加密byte []ptext=cp.doFinal(ctext)
  • 服務器
    • 接收密鑰長度、密鑰內容
    • 建立並初始化密碼器Cipher cp=Cipher.getInstance("DESede")cp.init(Cipher.DECRYPT_MODE, k);
    • 執行解密byte []ptext=cp.doFinal(ctext)

實驗代碼

  • 客戶端Client.java
package 實驗五;

import java.io.*;
import java.net.*;
import javax.crypto.*;
import java.util.Scanner;

public class Client5_3 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("169.254.92.198",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            KeyGenerator kg = KeyGenerator.getInstance("DESede");
            kg.init(168);
            SecretKey k = kg.generateKey();
            byte []kb = k.getEncoded();
            out.writeUTF(kb.length+ "");
            System.out.println("產生的密鑰爲");
            for(int i=0;i<kb.length;i++) {
                System.out.print(kb[i]+ " ");
                out.writeUTF(kb[i] +"");
            }
            System.out.println("\n請輸入中綴表達式:");
            String infix = inn.nextLine();
            String [] str = infix.split(" ");
            System.out.println("後綴表達式爲");
            MyBC suffix =new MyBC(str);
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE,k);
            byte ptext[] = suffix.jieguo.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("雙方已斷開鏈接"+e);
        }
    }
}
  • 服務器Sever,java
package 實驗五;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.io.*;
import java.net.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Sever5_3 {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        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 keylength = in.readUTF();
            byte []kb = new byte[Integer.parseInt(keylength)];
            System.out.println("收到的密鑰爲:");
            for(int i = 0;i<Integer.parseInt(keylength);i++) {
                String str = in.readUTF();
                kb[i] = Byte.parseByte(str);
                System.out.print(kb[i] + " ");
            }
            SecretKeySpec k = new SecretKeySpec(kb, "DESede");
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            String clength = in.readUTF();
            byte ctext[] = new byte[Integer.parseInt(clength)];
            for (int i = 0;i<Integer.parseInt(clength);i++) {
                String temp = in.readUTF();
                ctext[i] = Byte.parseByte(temp);
            }
            byte[] ptext = cp.doFinal(ctext);
            String suffix = new String(ptext,"UTF8");
            String [] str = suffix.split(" ");
            System.out.println("\n收到問題,解密後的後綴表達式爲:"+suffix);
            System.out.println("已傳輸得出結果:");
            MyDC myDC = new MyDC(str);
            String answer =  String.valueOf(myDC.answer);
            out.writeUTF(answer+"");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("雙方已斷開鏈接");
        }
    }
}

實驗截圖

  • 客戶端
    編程

  • 服務器
    數組

任務四

實驗要求

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

實驗原理及過程

  • 客戶端和服務器分別產生本身的公鑰和私鑰,並用過字節數組的形式分別向另外一方傳遞本身的公鑰;
  • 客戶端和服務器接受對方的公鑰後利用本身的私鑰建立共享密鑰;
  • 建立並初始化密鑰協定對象KeyAgreement ka=KeyAgreement.getInstance("DH")ka.init(prk);
  • 執行密鑰協定ka.doPhase(pbk,true);
  • 生成共享信息byte[ ] sb=ka.generateSecret();
  • 從文件中讀取信息並給出共享密鑰

實驗代碼

  • key_DH.javakeyAgree.java
package 實驗五;

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

public class Key_DH{
    private static final byte skip1024ModulusBytes[] = {
            (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
            (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
            (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
            (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
            (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
            (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
            (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
            (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
            (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
            (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
            (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
            (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
            (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
            (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
            (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
            (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
            (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
            (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
            (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
            (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
            (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
            (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
            (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
            (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
            (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
            (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
            (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
            (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
            (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
            (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
            (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
            (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
    };
    // The SKIP 1024 bit modulus
    private static final BigInteger skip1024Modulus
            = new BigInteger(1, skip1024ModulusBytes);
    // The base used with the SKIP 1024 bit modulus
    private static final BigInteger skip1024Base = BigInteger.valueOf(2);
    public static void DH(String str1,String str2) throws Exception{
        DHParameterSpec DHP=
                new DHParameterSpec(skip1024Modulus,skip1024Base);

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

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

package 實驗五;

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

public class KeyAgree {
    public static void Agree(String str1,String str2) throws Exception{
        // 讀取對方的DH公鑰
        FileInputStream f1=new FileInputStream(str1);
        ObjectInputStream b1=new ObjectInputStream(f1);
        PublicKey  pbk=(PublicKey)b1.readObject( );
//讀取本身的DH私鑰
        FileInputStream f2=new FileInputStream(str2);
        ObjectInputStream b2=new ObjectInputStream(f2);
        PrivateKey  prk=(PrivateKey)b2.readObject( );
        // 執行密鑰協定
        KeyAgreement ka=KeyAgreement.getInstance("DH");
        ka.init(prk);
        ka.doPhase(pbk,true);
        //生成共享信息
        byte[ ] sb=ka.generateSecret();
        FileOutputStream fsb = new FileOutputStream("sb.dat");
        fsb.write(sb);
    }
}
  • 客戶端Client5_4.java
package 實驗五;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;
import java.util.Scanner;
import java.net.*;
public class Client5_4 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("169.254.92.198",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            Key_DH.DH ("Lpub.dat","Lpri.dat");
            FileInputStream my = new FileInputStream("Lpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            Thread.sleep(1000);
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("W1pub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k);
            KeyAgree.Agree("W1pub.dat","Lpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            byte[] keysb = new byte[24];
            f.read(keysb);
            System.out.println("公共密鑰爲:");
            for (int i = 0;i<24;i++) {
                System.out.print(keysb[i]+" ");
            }
            System.out.println("\n請輸入中綴表達式:");
            String infix = inn.nextLine();
            String [] str = infix.split(" ");
            System.out.println("已傳遞後綴表達式");
            MyBC suffix =new MyBC(str);
            SecretKeySpec k1 = new SecretKeySpec(keysb, "DESede");
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k1);
            byte ptext[] = suffix.jieguo.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext);
            System.out.println("加密後的後綴表達式爲:");
            for (int i = 0; i < ctext.length; i++) {
                System.out.print(ctext[i] + " ");
            }
            out.writeUTF(ctext.length + "");
            for (int i = 0; i < ctext.length; i++) {
                out.writeUTF(ctext[i] + "");
            }
            String result = in.readUTF();
            System.out.println("\n已收到計算結果"+result);
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("雙方已斷開鏈接"+e);
        }
    }
}
  • 服務器Sever5_4,java
package 實驗五;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;
public class Sever5_4 {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        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());
            Key_DH.DH("Wpub.dat","Wpri.dat");
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k1 = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("Lpub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k1);
            FileInputStream my = new FileInputStream("Wpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            KeyAgree.Agree("Lpub.dat","Wpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            byte[] keysb = new byte[24];
            f.read(keysb);
            System.out.println("公共密鑰爲:");
            for (int i = 0;i<24;i++) {
                System.out.print(keysb[i]+" ");
            }
            SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            String clength = in.readUTF();
            byte ctext[] = new byte[Integer.parseInt(clength)];
            for (int i = 0; i < Integer.parseInt(clength); i++) {
                String temp = in.readUTF();
                ctext[i] = Byte.parseByte(temp);
            }
            byte[] ptext = cp.doFinal(ctext);
            String suffix = new String(ptext, "UTF8");
            String [] str = suffix.split(" ");
            System.out.println("\n收到問題,正在解密後綴表達式:"+suffix);
            System.out.println("已傳輸得出結果:");
            MyDC myDC = new MyDC(str);
            String answer =  String.valueOf(myDC.answer);
            out.writeUTF(answer+"");
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("雙方已斷開鏈接");
        }
    }
}

實驗截圖

  • 客戶端
    安全

  • 服務器
    服務器

任務五

實驗要求

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

實驗原理

  • Java密碼學算法中「Java摘要算法- MD5」部分的內容

實驗代碼

  • MD5DigestPass.java
package 實驗五;

import java.security.*;

public class DigestPass{
    public static String MD5(String str) throws Exception{
        String x=str;
        MessageDigest m=MessageDigest.getInstance("MD5");
        m.update(x.getBytes("UTF8"));
        byte s[ ]=m.digest( );
        String result="";
        for (int i=0; i<s.length; i++){
            result+=Integer.toHexString((0x000000ff & s[i]) |
                    0xffffff00).substring(6);
        }
        return result;
    }
}
  • 客戶端Client5_5
package 實驗五;

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

public class Client5_5 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try{
            mysocket = new Socket("169.254.92.198",2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            Key_DH.DH("Lpub.dat","Lpri.dat");
            FileInputStream my = new FileInputStream("Lpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            Thread.sleep(1000);
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("W1pub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k);
            KeyAgree.Agree("W1pub.dat","Lpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            byte[] keysb = new byte[24];
            f.read(keysb);
            System.out.println("公共密鑰爲:");
            for (int i = 0;i<24;i++) {
                System.out.print(keysb[i]+" ");
            }
            System.out.println("\n請輸入中綴表達式:");
            String infix = inn.nextLine();
            String [] str = infix.split(" ");
            System.out.println("已傳遞後綴表達式");
            MyBC suffix =new MyBC(str);
            String mtoMD5 = DigestPass.MD5(suffix.jieguo);
            System.out.println("明文的MD5值爲:"+mtoMD5);
            out.writeUTF(mtoMD5);
            SecretKeySpec k1 = new SecretKeySpec(keysb, "DESede");
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k1);
            byte ptext[] = suffix.jieguo.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext);
            System.out.println("加密後的後綴表達式爲:");
            for (int i = 0; i < ctext.length; i++) {
                System.out.print(ctext[i] + " ");
            }
            out.writeUTF(ctext.length + "");
            for (int i = 0; i < ctext.length; i++) {
                out.writeUTF(ctext[i] + "");
            }
            String result = in.readUTF();
            System.out.println("\n已收到計算結果"+result);
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("雙方已斷開鏈接"+e);
        }
    }
}
  • 服務器Sever.java
package 實驗五;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;
public class Sever5_5 {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;

        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());
            Key_DH.DH("Wpub.dat","Wpri.dat");
            int length = Integer.parseInt(in.readUTF());
            byte cpub[] = new byte[length];
            for(int i=0;i<length;i++) {
                String temp = in.readUTF();
                cpub[i] = Byte.parseByte(temp);
            }
            ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
            ObjectInputStream ckey = new ObjectInputStream(ckey1);
            Key k1 = (Key) ckey.readObject();
            FileOutputStream f2 = new FileOutputStream("L1pub.dat");
            ObjectOutputStream b2 = new ObjectOutputStream(f2);
            b2.writeObject(k1);
            FileInputStream my = new FileInputStream("Wpub.dat");
            ObjectInputStream mypub = new ObjectInputStream(my);
            Key kp = (Key) mypub.readObject();
            ByteArrayOutputStream DH = new ByteArrayOutputStream();
            ObjectOutputStream myDH = new ObjectOutputStream(DH);
            myDH.writeObject(kp);
            byte []pub = DH.toByteArray();
            out.writeUTF(pub.length+"");
            for(int i=0;i<pub.length;i++) {
                out.writeUTF(pub[i]+ "");
            }
            KeyAgree.Agree("L1pub.dat","Wpri.dat");
            FileInputStream f = new FileInputStream("sb.dat");
            byte[] keysb = new byte[24];
            f.read(keysb);
            System.out.println("公共密鑰爲:");
            for (int i = 0;i<24;i++) {
                System.out.print(keysb[i]+" ");
            }
            String c = in.readUTF();
            SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            String clength = in.readUTF();
            byte ctext[] = new byte[Integer.parseInt(clength)];
            for (int i = 0; i < Integer.parseInt(clength); i++) {
                String temp = in.readUTF();
                ctext[i] = Byte.parseByte(temp);
            }
            byte[] ptext = cp.doFinal(ctext);
            String suffix = new String(ptext, "UTF8");
            String [] str = suffix.split(" ");
            System.out.println("\n收到問題,解密後綴表達式爲:"+suffix);
            String mtoMD5 = DigestPass.MD5(suffix);
            System.out.println("MD5的值爲"+ mtoMD5);
            if(mtoMD5.equals(c)) {
                System.out.println("傳遞的MD5值和解密的後綴表達式的MD5值相同,能夠解密!");
                System.out.println("已傳輸得出結果:");
                MyDC myDC = new MyDC(str);
                String answer = String.valueOf(myDC.answer);
                out.writeUTF(answer + "");
            }
            else {
                System.out.println("密文有誤,不能解密!");
            }
            Thread.sleep(500);
        }catch (Exception e){
            System.out.println("雙方已斷開鏈接");
        }
    }
}

實驗截圖

  • 客戶端
    網絡

  • 服務器
    socket

跳轉連接

碼雲連接

搭檔博客連接

相關文章
相關標籤/搜索