20165230 《Java程序設計》實驗五《網絡編程與安全》實驗報告
一、實驗報告封面
課程:Java程序設計 班級:1652班 姓名:田坤燁 學號:20165230 成績:
指導教師:婁嘉鵬 實驗日期:2018年5月28日
實驗時間:13:45 - 15:25
實驗序號:實驗五 實驗名稱:網絡編程與安全
實驗要求:
沒有Linux基礎的同學建議先學習《Linux基礎入門(新版)》《Vim編輯器》 課程;完成實驗、撰寫實驗報告,注意實驗報告重點是運行結果,遇到的問題(工具查找,安裝,使用,程序的編輯,調試,運行等)、解決辦法(空洞的方法如“查網絡”、“問同學”、“看書”等一律得0分)以及分析(從中可以得到什么啟示,有什么收獲,教訓等);實驗報告中統計自己的PSP(Personal Software Process)時間;嚴禁抄襲。二、實驗內容及步驟
(一)實現中綴表達式轉后綴表達式并實現后綴表達式求值的功能
結對實現中綴表達式轉后綴表達式的功能 MyBC.java結對實現從上面功能中獲取的表達式中實現后綴表達式求值的功能,調用MyDC.java上傳測試代碼運行結果截圖和碼云鏈接MyBC.java
import java.util.Stack;
import java.util.StringTokenizer;public class MyBC{private Stack<Character> stack1;public char Precede(char a,char b){if(a=='#')if(b!='#')return '<';elsereturn '=';if(a==')')return '>';if(a=='(')if(b!=')')return '<';elsereturn '=';if(a=='/'||a=='*')if(b!='(')return '>';elsereturn '<';if(a=='-'||a=='+')if(b!='*'&&b!='/'&&b!='(')return '>';elsereturn '<';return '>';}public MyBC() {stack1 = new Stack<Character>();stack1.push('#');}public String turn(String expr) {int result = 0;String token;char topelem,optr;char[] exper1 = new char[100];int i = 0;StringTokenizer tokenizer = new StringTokenizer (expr);while (tokenizer.hasMoreTokens()){token = tokenizer.nextToken();//如果是運算符,調用isOperatorif (isOperator(token)){//調用Precede比較優先級topelem=stack1.peek();optr = token.charAt(0);if(Precede(topelem,optr)=='<'){stack1.push(optr);}else if(Precede(topelem,optr)=='='){optr =stack1.pop();exper1[i++] = optr;exper1[i++] = ' ';}else if(Precede(topelem,optr)=='>'){optr =stack1.pop();//從運算符棧中退出棧頂元素并放入后綴表達式exper1exper1[i++] = optr;exper1[i++] = ' ';}}//如果是(則入棧else if(token.equals("(")) {optr = token.charAt(0);stack1.push(optr);}//如果是)則退棧直到出現第一個(else if(token.equals(")")) {optr = stack1.pop();while(optr!='('){exper1[i++] = optr;exper1[i++] = ' ';optr = stack1.pop();}}else//如果是操作數//操作數放入后綴表達式exper1{optr = token.charAt(0);//System.out.println(optr);exper1[i++]=optr;exper1[i++] = ' ';}}while(!stack1.isEmpty()){optr = stack1.pop();if(optr!='#'){exper1[i++] = optr;exper1[i++] = ' ';}}//System.out.println(exper1);return ToString(exper1);}//@Overrideprivate boolean isOperator(String token){return (token.equals("+") || token.equals("-") ||token.equals("*") || token.equals("/") );}public static String ToString(char[] exper1){int length = exper1.length;String str=" ";for(int i=0;i<length;i++){str=str+exper1[i];}return str;}}
(二) 基于Java Socket實現客戶端/服務器功能
基于Java Socket實現客戶端/服務器功能,傳輸方式用TCP客戶端讓用戶輸入中綴表達式,然后把中綴表達式調用MyBC.java的功能轉化為后綴表達式,把后綴表達式通過網絡發送給服務器服務器接收到后綴表達式,調用MyDC.java的功能計算后綴表達式的值,把結果發送給客戶端客戶端顯示服務器發送過來的結果上傳測試結果截圖和碼云鏈接import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;public class Server {public static final int PORT = 12345;//監聽的端口號public static void main(String[] args) {System.out.println("服務器啟動...\n");Server server = new Server();server.init();}public void init() {try {ServerSocket serverSocket = new ServerSocket(PORT);while (true) {// 一旦有堵塞, 則表示服務器與客戶端獲得了連接Socket client = serverSocket.accept();// 處理這次連接new HandlerThread(client);}} catch (Exception e) {System.out.println("服務器異常: " + e.getMessage());}}private class HandlerThread implements Runnable {private Socket socket;public HandlerThread(Socket client) {socket = client;new Thread(this).start();}public void run() {try {// 讀取客戶端數據DataInputStream input = new DataInputStream(socket.getInputStream());String clientInputStr = input.readUTF();//這里要注意和客戶端輸出流的寫方法對應,否則會拋 EOFException// 處理客戶端數據System.out.println("客戶端發過來的內容:" + clientInputStr);MyDC evalute = new MyDC();int result = evalute.evaluate(clientInputStr);// 向客戶端回復信息DataOutputStream out = new DataOutputStream(socket.getOutputStream());System.out.print("計算結果:\t");// 發送鍵盤輸入的一行//String s = new BufferedReader(new InputStreamReader(System.in)).readLine();out.writeUTF(String.valueOf(result));out.close();input.close();} catch (Exception e) {System.out.println("服務器 run 異常: " + e.getMessage());} finally {if (socket != null) {try {socket.close();} catch (Exception e) {socket = null;System.out.println("服務端 finally 異常:" + e.getMessage());}}}}}
}
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;public class Client {public static final String IP_ADDR = "127.0.0.1";//服務器地址public static final int PORT = 12345;//服務器端口號public static void main(String[] args) {System.out.println("客戶端啟動...");System.out.println("當接收到服務器端字符為 \"OK\" 的時候, 客戶端將終止\n");while (true) {Socket socket = null;try {socket = new Socket(IP_ADDR, PORT);DataInputStream input = new DataInputStream(socket.getInputStream());DataOutputStream out = new DataOutputStream(socket.getOutputStream());System.out.print("請輸入: \t");String str = new BufferedReader(new InputStreamReader(System.in)).readLine();MyBC turner = new MyBC();String str1 = turner.turn(str);int length=0,i=0;while(str1.charAt(i)!='\0'){length++;i++;}String str2 = str1.substring(1,length-1);out.writeUTF(str2);String ret = input.readUTF();System.out.println("服務器端返回過來的是: " + ret);out.close();input.close();} catch (Exception e) {System.out.println("客戶端異常:" + e.getMessage());} finally {if (socket != null) {try {socket.close();} catch (IOException e) {socket = null;System.out.println("客戶端 finally 異常:" + e.getMessage());}}}}}
}
(三)加密結對編程
基于Java Socket實現客戶端/服務器功能,傳輸方式用TCP客戶端讓用戶輸入中綴表達式,然后把中綴表達式調用MyBC.java的功能轉化為后綴表達式,把后綴表達式用3DES或AES算法加密后通過網絡把密文發送給服務器服務器接收到后綴表達式表達式后,進行解密(和客戶端協商密鑰,可以用數組保存),然后調用MyDC.java的功能計算后綴表達式的值,把結果發送給客戶端客戶端顯示服務器發送過來的結果上傳測試結果截圖和碼云鏈接import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;public class ServerReceive{public static final int PORT = 12345;//監聽的端口號public static void main(String[] args) {System.out.println("服務器啟動...\n");Server server = new Server();server.init();}public void init() {try {ServerSocket serverSocket = new ServerSocket(PORT);while (true) {// 一旦有堵塞, 則表示服務器與客戶端獲得了連接Socket client = serverSocket.accept();// 處理這次連接new HandlerThread(client);}} catch (Exception e) {System.out.println("服務器異常: " + e.getMessage());}}private class HandlerThread implements Runnable {private Socket socket;public HandlerThread(Socket client) {socket = client;new Thread(this).start();}public void run() {try {/*讀取客戶端數據*/DataInputStream input = new DataInputStream(socket.getInputStream());String clientInputStr = input.readUTF();/*處理客戶端數據*/System.out.println("客戶端發過來的內容:" + clientInputStr);MyDC evalute = new MyDC();SDec sDec = new SDec();//解密int result = evalute.evaluate(clientInputStr);/* 向客戶端回復信息*/DataOutputStream out = new DataOutputStream(socket.getOutputStream());System.out.print("計算結果:\t");/*發送鍵盤輸入的一行*/out.writeUTF(String.valueOf(result));out.close();input.close();} catch (Exception e) {System.out.println("服務器 run 異常: " + e.getMessage());} finally {if (socket != null) {try {socket.close();} catch (Exception e) {socket = null;System.out.println("服務端 finally 異常:" + e.getMessage());}}}}}
}
import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;public class Client2 {public static final String IP_ADDR = "127.0.0.1";//服務器地址public static final int PORT = 12345;//服務器端口號public static void main(String[] args) {System.out.println("客戶端啟動...");System.out.println("當接收到服務器端字符為 \"OK\" 的時候, 客戶端將終止\n");while (true) {Socket socket = null;try {//創建一個流套接字并將其連接到指定主機上的指定端口號socket = new Socket(IP_ADDR, PORT);//讀取服務器端數據DataInputStream input = new DataInputStream(socket.getInputStream());//向服務器端發送數據DataOutputStream out = new DataOutputStream(socket.getOutputStream());System.out.print("請輸入: \t");String str = new BufferedReader(new InputStreamReader(System.in)).readLine();MyBC turner = new MyBC();Skey_DES skey_des = new Skey_DES();skey_des.key_DES();Skey_kb skey_kb = new Skey_kb();skey_kb.key();/*產生密鑰*/SEnc sEnc = new SEnc();String str1 = turner.turn(str);int length=0,i=0;while(str1.charAt(i)!='\0'){length++;i++;}String str2 = str1.substring(1,length-1);out.writeUTF(str2);String ret = input.readUTF();System.out.println("服務器端返回過來的是: " + ret);out.close();input.close();} catch (Exception e) {System.out.println("客戶端異常:" + e.getMessage());} finally {if (socket != null) {try {socket.close();} catch (IOException e) {socket = null;System.out.println("客戶端 finally 異常:" + e.getMessage());}}}}}
}
(四)客戶端和服務器用DH算法進行3DES或AES算法的密鑰交換
- 服務器和客戶端分別運行Key_DH.java代碼產生各自的公鑰和私鑰,然后將公鑰通過網絡發送給對方,,客戶端和服務器利用對方發送的公鑰和自己私鑰運行 KeyAgree.java生成相同的共享密鑰,各自利用共享密鑰進行加解密工作。
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{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 modulusprivate static final BigInteger skip1024Modulus= new BigInteger(1, skip1024ModulusBytes);// The base used with the SKIP 1024 bit modulusprivate 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(args[0]);ObjectOutputStream b1=new ObjectOutputStream(f1);b1.writeObject(pbk);// 保存私鑰FileOutputStream f2=new FileOutputStream(args[1]);ObjectOutputStream b2=new ObjectOutputStream(f2);b2.writeObject(prk);}
}
(五)解密后計算明文的MD5值,和客戶端傳來的MD5進行比較,一致則調用MyDC.java的功能計算后綴表達式的值,把結果發送給客戶端
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
public class Server5 {public static void main(String args[]) {MyDC evalute = new MyDC();SDec sDec = new SDec();try {ServerSocket server = null;try {server = new ServerSocket(12345);//創建一個ServerSocket在端口4700監聽客戶請求} catch (Exception e) {System.out.println("can not listen to:" + e);//出錯,打印出錯信息}Socket socket = null;try {socket = server.accept();//使用accept()阻塞等待客戶請求,有客戶//請求到來則產生一個Socket對象,并繼續執行} catch (Exception e) {System.out.println("Error." + e);//出錯,打印出錯信息}String line;BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));//由Socket對象得到輸入流,并構造相應的BufferedReader對象PrintWriter os = new PrintWriter(socket.getOutputStream());//由Socket對象得到輸出流,并構造PrintWriter對象BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));//由系統標準輸入設備構造BufferedReader對象//使用Hash函數檢測明文完整性String x = sin.readLine();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(result);String match = is.readLine();if (match.equals(result)) {System.out.println("匹配成功");}System.out.println("Client:" + is.readLine());//在標準輸出上打印從客戶端讀入的字符串line = sin.readLine();//從標準輸入讀入一字符串while (!line.equals("bye")) {//如果該字符串為 "bye",則停止循環os.println(evalute.evaluate(line));//向客戶端輸出該字符串os.flush();//刷新輸出流,使Client馬上收到該字符串System.out.println("Server:" + evalute.evaluate(line));//在系統標準輸出上打印讀入的字符串System.out.println("Client:" + is.readLine());//從Client讀入一字符串,并打印到標準輸出上line = sin.readLine();//從系統標準輸入讀入一字符串} //繼續循環os.close(); //關閉Socket輸出流is.close(); //關閉Socket輸入流socket.close(); //關閉Socketserver.close(); //關閉ServerSocket} catch (Exception e) {System.out.println("Error:" + e);
//出錯,打印出錯信息}}
}
import java.io.*;import java.net.*;import java.security.MessageDigest;
/*** Created by lxkj on 2017/6/2.*/public class Client5 {public static void main(String args[]) throws Exception {MyBC turner = new MyBC();Skey_DES skey_des = new Skey_DES();skey_des.key_DES();Skey_kb skey_kb = new Skey_kb();skey_kb.key();/*產生密鑰*/SEnc sEnc = new SEnc();try {Socket socket = new Socket("127.0.0.1", 12345);
//向本機的4700端口發出客戶請求BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//由系統標準輸入設備構造BufferedReader對象PrintWriter os = new PrintWriter(socket.getOutputStream());//由Socket對象得到輸出流,并構造PrintWriter對象BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,并構造相應的BufferedReader對象String readline;System.out.println("請輸入:");readline =sin.readLine();//從系統標準輸入讀入一字符串String x = readline;// 將客戶端明文的Hash值傳送給服務器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);os.println(result);//通過網絡將明文的Hash函數值傳送到服務器// String str = is.readLine();// 從網絡輸入流讀取結果System.out.println("從服務器接收到的結果為:" + result); // 輸出服務器返回的結果while (!readline.equals("ok")) {//若從標準輸入讀入的字符串為 "ok"則停止循環readline = SEnc.Enc(turner.turn(readline));os.println(readline);/*把中綴表達式調用MyBC.java的功能轉化為后綴表達式,把后綴表達式用3DES加密后通過網絡發送給服務器*///將從系統標準輸入讀入的字符串輸出到Serveros.flush();//刷新輸出流,使Server馬上收到該字符串System.out.println("Client:" + readline);//在系統標準輸出上打印讀入的字符串System.out.println("Server:" + is.readLine());//從Server讀入一字符串,并打印到標準輸出上readline = sin.readLine(); //從系統標準輸入讀入一字符串} //繼續循環os.close(); //關閉Socket輸出流is.close(); //關閉Socket輸入流socket.close(); //關閉Socket} catch (Exception e) {System.out.println("Error" + e); //出錯,則打印出錯信息}}}
三、實驗遇到的問題
四、PSP時間
| 需求分析 | 30min | 12% |
| 設計 | 40min | 15% |
| 代碼實現 | 90min | 34% |
| 測試 | 45min | 17% |
| 分析總結 | 60min | 23% |
六、代碼鏈接
七、參考資料
轉載于:https://www.cnblogs.com/tiankunye/p/9097237.html
總結
以上是生活随笔為你收集整理的20165230 《Java程序设计》实验五《网络编程与安全》实验报告的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。