一、實驗五 網絡編程與安全-1
1.實驗要求:
兩人一組結對編程:
(1)參考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA ;
(2)結對實現中綴表達式轉后綴表達式的功能 MyBC.java;
(3)結對實現從上面功能中獲取的表達式中實現后綴表達式求值的功能,調用MyDC.java;
(4)上傳測試代碼運行結果截圖和碼云鏈接;
2.實驗過程:
(1)MyDC代碼:
import java.util.*;public class MyDC {private final char ADD = '+';private final char SUBTRACT = '-';private final char MUTIPLY = '*';private final char DIVIDE = '/';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();if (isOperator(token)) {op2 = (stack.pop().intValue());op1 = (stack.pop().intValue());result = evalSingleOp(token.charAt(0), op1, op2);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 MUTIPLY:result = op1 * op2;break;case DIVIDE:result = op1 / op2;}return result;}
}
(2)MyDCTest代碼:
import java.util.Scanner;public class MyDCTest {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");}}}
(3)MyBC代碼:
import java.util.*;
public class MyBC {public String result(String s) {Stack<String> sta = new Stack<String>(); //新建棧String str = "";StringTokenizer t=new StringTokenizer(s);while (t.hasMoreTokens()){ //依次遍歷元素,轉為后綴表達式String temp;String c;c=t.nextToken();if (c.equals("+") || c.equals("-")) { //遇到優先級最低的“+”、“-”,彈出“(”之前的所有元素while (sta.size() != 0) {temp = sta.pop();if (temp.equals("(")) {sta.push("(");break;}str = str + temp + " ";}sta.push(c);} else if (c.equals("*")|| c.equals("÷")) { //遇到優先級高的“*”、“/”,彈出“(”之前的“*”、“/”while (sta.size() != 0) {temp = sta.pop();if (temp.equals("(") || temp.equals("+") || temp.equals("-")) {sta.push(temp);break;} else {str = str + temp + " ";}}sta.push(c);} else if (c.equals("(")) { //遇到“(”直接入棧sta.push(c);} else if (c.equals(")")) { //遇到“)”,彈出“(”之前的所有元素while (sta.size() != 0) {temp = sta.pop();if (temp.equals("(")) {break;} else {str = str + temp + " ";}}} else //遇到數字,直接存入數組{str = str + c + " ";}}while (sta.size()!=0){ //彈出棧中剩余的元素str=str+sta.pop()+" ";}return str;}
}
(4)Calculate代碼:
import java.util.Scanner;
public class Caculate {public static void main(String[] args) {MyDC a = new MyDC();MyBC b = new MyBC();String str;int result;System.out.println("輸入算式:");Scanner reader = new Scanner(System.in);str = reader.nextLine();str = b.result(str);result = a.evaluate(str);System.out.println("答案為:"+result);}
}
3.實驗截圖:
(1)測試MyDC截圖:
(2)計算結果截圖:
4.碼云鏈接:
https://gitee.com/zzm-zcc/zhang_zhi_min/tree/master/%E5%AE%9E%E9%AA%8C5--1
二、實驗五 網絡編程與安全-2
1.實驗要求:
結對編程:1人負責客戶端,一人負責服務器;
(1)注意責任歸宿,要會通過測試證明自己沒有問題;
(2)基于Java Socket實現客戶端/服務器功能,傳輸方式用TCP;
(3)客戶端讓用戶輸入中綴表達式,然后把中綴表達式調用MyBC.java的功能轉化為后綴表達式,把后綴表達式通過網絡發送給服務器;
(4)服務器接收到后綴表達式,調用MyDC.java的功能計算后綴表達式的值,把結果發送給客戶端;
(5)客戶端顯示服務器發送過來的結果;
(6)上傳測試結果截圖和碼云鏈接;
2.實驗過程:
(1)Server代碼(服務器端):
import java.io.*;
import java.net.*;
public class Server {public static void main(String args[]) {int answer;ServerSocket serverForClient=null;Socket socketOnServer=null;DataOutputStream out=null;DataInputStream in=null;try { serverForClient = new ServerSocket(2010);}catch(IOException e1) {System.out.println(e1);}try{ System.out.println("等待客戶呼叫");socketOnServer = serverForClient.accept(); //堵塞狀態,除非有客戶呼叫out=new DataOutputStream(socketOnServer.getOutputStream());in=new DataInputStream(socketOnServer.getInputStream());String s=in.readUTF(); // in讀取信息,堵塞狀態System.out.println("服務器收到客戶的提問:"+s);MyDC d=new MyDC();answer=d.evaluate(s);out.writeUTF(answer+"");Thread.sleep(500);}catch(Exception e) {System.out.println("客戶已斷開"+e);}}
}
(2)Client代碼(客戶端):
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.Scanner;public class Client {public static void main(String args[]) {Socket mysocket;DataInputStream in=null;DataOutputStream out=null;try{ mysocket=new Socket("127.1.0.0",2010);in=new DataInputStream(mysocket.getInputStream());out=new DataOutputStream(mysocket.getOutputStream());System.out.println("請輸入算式:");Scanner scanner=new Scanner(System.in);String str=scanner.nextLine();MyBC b=new MyBC();str=b.result(str);out.writeUTF(str);String s=in.readUTF(); //in讀取信息,堵塞狀態System.out.println("客戶收到服務器的回答:"+s);Thread.sleep(500);}catch(Exception e) {System.out.println("服務器已斷開"+e);}}
}
注:任然需要MyDC代碼與MyBC代碼。
3.實驗截圖:
(1)服務器端截圖:
(2)客戶端截圖:
4.碼云鏈接:
https://gitee.com/zzm-zcc/zhang_zhi_min/commit/5377d0290f76f29daae2099b11936647409ae965
三、實驗五 網絡編程與安全-3
1.實驗要求:
加密結對編程:1人負責客戶端,一人負責服務器;
(1)注意責任歸宿,要會通過測試證明自己沒有問題;
(2)基于Java Socket實現客戶端/服務器功能,傳輸方式用TCP;
(3)客戶端讓用戶輸入中綴表達式,然后把中綴表達式調用MyBC.java的功能轉化為后綴表達式,把后綴表達式用3DES或AES算法加密后通過網絡把密文發送給服務器;
(4)服務器接收到后綴表達式表達式后,進行解密(和客戶端協商密鑰,可以用數組保存),然后調用MyDC.java的功能計算后綴表達式的值,把結果發送給客戶端;
(5)客戶端顯示服務器發送過來的結果;
(6)上傳測試結果截圖和碼云鏈接;
2.實驗過程:
(1)ServerOne代碼(服務器端)
import java.io.*;
import java.net.*;
public class ServerOne {public static void main (String args[]) throws Exception {/*String key="";int n=-1;byte [] a=new byte[128];try{ File f=new File("key1.dat");InputStream in = new FileInputStream(f);while((n=in.read(a,0,100))!=-1) {key=key+new String (a,0,n);}in.close();}catch(IOException e) {System.out.println("File read Error"+e);}*/ServerSocket serverForClient=null;Socket socketOnServer=null;DataOutputStream out=null;DataInputStream in=null;try { serverForClient = new ServerSocket(2010);}catch(IOException e1) {System.out.println(e1);}try{ System.out.println("等待客戶呼叫");socketOnServer = serverForClient.accept(); //堵塞狀態,除非有客戶呼叫out=new DataOutputStream(socketOnServer.getOutputStream());in=new DataInputStream(socketOnServer.getInputStream());String key = in.readUTF();String s=in.readUTF(); // in讀取信息,堵塞狀態System.out.println("服務器收到的信息:"+s);String clear=Encoder.AESDncode(key,s);MyDC d=new MyDC();System.out.println("服務器收到客戶的提問:"+clear);int answer=d.evaluate(clear);out.writeUTF(answer+"");Thread.sleep(500);}catch(Exception e) {System.out.println("客戶已斷開"+e);}}
}
(2) ClientOne代碼(客戶端)
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.Scanner;public class ClientOne {public static void main(String args[]) throws Exception {String key = "";int n = -1;byte[] a = new byte[128];try {File f = new File("key1.dat");InputStream in = new FileInputStream(f);while ((n = in.read(a, 0, 100)) != -1) {key = key + new String(a, 0, n);}in.close();} catch (IOException e) {System.out.println("File read Error" + e);}Socket mysocket;DataInputStream in = null;DataOutputStream out = null;System.out.println("請輸入算式:");Scanner scanner = new Scanner(System.in);String str = scanner.nextLine();//輸入算式MyBC b = new MyBC();str = b.result(str);String secret=Encoder.AESEncode(key,str);//客戶端進行加密try {mysocket = new Socket("127.1.0.0", 2010);in = new DataInputStream(mysocket.getInputStream());out = new DataOutputStream(mysocket.getOutputStream());out.writeUTF(key);out.writeUTF(secret);String s = in.readUTF(); //in讀取信息,堵塞狀態System.out.println("客戶收到服務器的回答:" + s);Thread.sleep(500);} catch (Exception e) {System.out.println("服務器已斷開" + e);}}
}
(3) Encoder代碼(加解密代碼)
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Scanner;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;/** AES對稱加密和解密*/
public class Encoder {/** 加密* 1.構造密鑰生成器* 2.根據ecnodeRules規則初始化密鑰生成器* 3.產生密鑰* 4.創建和初始化密碼器* 5.內容加密* 6.返回字符串*/public static String AESEncode(String encodeRules,String content){try {//1.構造密鑰生成器,指定為AES算法,不區分大小寫KeyGenerator keygen=KeyGenerator.getInstance("AES");//2.根據ecnodeRules規則初始化密鑰生成器//生成一個128位的隨機源,根據傳入的字節數組keygen.init(128, new SecureRandom(encodeRules.getBytes()));//3.產生原始對稱密鑰SecretKey original_key=keygen.generateKey();//4.獲得原始對稱密鑰的字節數組byte [] raw=original_key.getEncoded();//5.根據字節數組生成AES密鑰SecretKey key=new SecretKeySpec(raw, "AES");//6.根據指定算法AES自成密碼器Cipher cipher=Cipher.getInstance("AES");//7.初始化密碼器,第一個參數為加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二個參數為使用的KEYcipher.init(Cipher.ENCRYPT_MODE, key);//8.獲取加密內容的字節數組(這里要設置為utf-8)不然內容中如果有中文和英文混合中文就會解密為亂碼byte [] byte_encode=content.getBytes("utf-8");//9.根據密碼器的初始化方式--加密:將數據加密byte [] byte_AES=cipher.doFinal(byte_encode);//10.將加密后的數據轉換為字符串//這里用Base64Encoder中會找不到包//解決辦法://在項目的Build path中先移除JRE System Library,再添加庫JRE System Library,重新編譯后就一切正常了。String AES_encode=new String(new BASE64Encoder().encode(byte_AES));//11.將字符串返回return AES_encode;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}//如果有錯就返加nulllreturn null;}/** 解密* 解密過程:* 1.同加密1-4步* 2.將加密后的字符串反紡成byte[]數組* 3.將加密內容解密*/public static String AESDncode(String encodeRules,String content){try {//1.構造密鑰生成器,指定為AES算法,不區分大小寫KeyGenerator keygen=KeyGenerator.getInstance("AES");//2.根據ecnodeRules規則初始化密鑰生成器//生成一個128位的隨機源,根據傳入的字節數組keygen.init(128, new SecureRandom(encodeRules.getBytes()));//3.產生原始對稱密鑰SecretKey original_key=keygen.generateKey();//4.獲得原始對稱密鑰的字節數組byte [] raw=original_key.getEncoded();//5.根據字節數組生成AES密鑰SecretKey key=new SecretKeySpec(raw, "AES");//6.根據指定算法AES自成密碼器Cipher cipher=Cipher.getInstance("AES");//7.初始化密碼器,第一個參數為加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二個參數為使用的KEYcipher.init(Cipher.DECRYPT_MODE, key);//8.將加密并編碼后的內容解碼成字節數組byte [] byte_content= new BASE64Decoder().decodeBuffer(content);/** 解密*/byte [] byte_decode=cipher.doFinal(byte_content);String AES_decode=new String(byte_decode,"utf-8");return AES_decode;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();}//如果有錯就返加nulllreturn null;}}
(4)Skey_AES代碼(AES調用代碼)
import java.io.*;
import javax.crypto.*;
public class Skey_AES{public static void main(String args[]) throws Exception{KeyGenerator kg=KeyGenerator.getInstance("AES");kg.init(128);SecretKey k=kg.generateKey( );FileOutputStream f=new FileOutputStream("key1.dat");ObjectOutputStream b=new ObjectOutputStream(f);b.writeObject(k);}
}
注: Encoder代碼和Skey_AES代碼為參考網上的代碼,在運行ServerOne代碼和ClientOne代碼前應先運行Skey_AES代碼,任然需要MyDC代碼與MyBC代碼。
3.實驗截圖:
(1)服務器端截圖:
(2)客戶端截圖:
4.碼云鏈接:
https://gitee.com/zzm-zcc/zhang_zhi_min/commit/c3d15a343490157a6c1eda6e6c102c2590fa526b
四、實驗五 網絡編程與安全-4
1.實驗要求:
密鑰分發結對編程:1人負責客戶端,一人負責服務器;
(1)注意責任歸宿,要會通過測試證明自己沒有問題;
(2)基于Java Socket實現客戶端/服務器功能,傳輸方式用TCP;
(3)客戶端讓用戶輸入中綴表達式,然后把中綴表達式調用MyBC.java的功能轉化為后綴表達式,把后綴表達式用3DES或AES算法加密通過網絡把密文發送給服務器;
(4)客戶端和服務器用DH算法進行3DES或AES算法的密鑰交換;
(5)服務器接收到后綴表達式表達式后,進行解密,然后調用MyDC.java的功能計算后綴表達式的值,把結果發送給客戶端;
(6)客戶端顯示服務器發送過來的結果;
(7)上傳測試結果截圖和碼云鏈接;
2.實驗過程:
(1)Key_DH代碼:
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 SKIPprivate 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);}
}
(2)KeyAgree代碼:
import java.security.PublicKey;
import java.security.PrivateKey;
import java.io.*;
import javax.crypto.KeyAgreement;
import javax.crypto.spec.*;public class KeyAgree{public static void main(String args[ ]) throws Exception{File file=new File("Sharekey.dat");// 讀取對方的DH公鑰FileInputStream f1=new FileInputStream("Apub.dat");ObjectInputStream b1=new ObjectInputStream(f1);PublicKey pbk=(PublicKey)b1.readObject( );//讀取自己的DH私鑰FileInputStream f2=new FileInputStream("Bpri.dat");ObjectInputStream b2=new ObjectInputStream(f2);PrivateKey prk=(PrivateKey)b2.readObject( );// 執行密鑰協定KeyAgreement ka=KeyAgreement.getInstance("DH");ka.init(prk);ka.doPhase(pbk,true);//生成共享信息byte[ ] sb=ka.generateSecret();for(int i=0;i<sb.length;i++){System.out.print(sb[i]+",");}OutputStream out=new FileOutputStream(file);out.write(sb);out.close();SecretKeySpec k=new SecretKeySpec(sb,"AES");}
}
(3)ServerTwo代碼(服務器端):
import java.io.*;
import java.net.*;
public class ServerTwo {public static void main(String args[]) throws IOException{String sharekey="";int n=-1;byte [] a=new byte[128];try{ File f=new File("Sharekey.dat");InputStream in = new FileInputStream(f);while((n=in.read(a,0,100))!=-1) {sharekey=sharekey+new String (a,0,n);}in.close();}catch(IOException e) {System.out.println("File read Error"+e);}ServerSocket serverForClient=null;Socket socketOnServer=null;DataOutputStream out=null;DataInputStream in=null;try { serverForClient = new ServerSocket(2010);}catch(IOException e1) {System.out.println(e1);}try{ System.out.println("等待客戶呼叫");socketOnServer = serverForClient.accept(); //堵塞狀態,除非有客戶呼叫out=new DataOutputStream(socketOnServer.getOutputStream());in=new DataInputStream(socketOnServer.getInputStream());String keyone =in.readUTF();//讀取被DH算法加密的密鑰String truekey = Encoder.AESDncode(sharekey,keyone);//使用共享密鑰對被加密的原密鑰解密。String secret =in.readUTF(); // in讀取信息,堵塞狀態System.out.println("服務器收到的信息:"+secret);String clear = Encoder.AESDncode(truekey,secret);//使用原密鑰解密表達式MyDC d=new MyDC();int answer=d.evaluate(clear);out.writeUTF(answer+"");System.out.println("服務器提供的解密:"+clear);Thread.sleep(500);}catch(Exception e) {System.out.println("客戶已斷開"+e);}}
}
(4)ClientTwo代碼(客戶端):
import java.io.*;
import java.net.*;
import java.util.Scanner;public class ClientTwo {public static void main(String args[]) throws Exception {String key1="";int n1=-1;byte [] a1=new byte[128];try{ File f=new File("key1.dat");InputStream in = new FileInputStream(f);while((n1=in.read(a1,0,100))!=-1) {key1=key1+new String (a1,0,n1);}in.close();}catch(IOException e) {System.out.println("File read Error"+e);}String sharekey="";int n=-1;byte [] a=new byte[128];try{ File f=new File("Sharekey.dat");InputStream in = new FileInputStream(f);while((n=in.read(a,0,100))!=-1) {sharekey=sharekey+new String (a,0,n);}in.close();}catch(IOException e) {System.out.println("File read Error"+e);}Socket mysocket;DataInputStream in=null;DataOutputStream out=null;System.out.println("請輸入算式:");Scanner scanner = new Scanner(System.in);String str = scanner.nextLine();//輸入算式MyBC b=new MyBC();str=b.result(str);String secret=Encoder.AESEncode(key1, str);//客戶端對表達式進行加密key1 = Encoder.AESEncode(sharekey,key1);//客戶端對密鑰進行DH加密try{ mysocket=new Socket("127.1.0.0",2010);in=new DataInputStream(mysocket.getInputStream());out=new DataOutputStream(mysocket.getOutputStream());out.writeUTF(key1);out.writeUTF(secret);String s=in.readUTF(); //in讀取信息,堵塞狀態System.out.println("客戶收到服務器的回答:"+s);Thread.sleep(50000);}catch(Exception e) {System.out.println("服務器已斷開"+e);}}
}
注:任然需要MyDC代碼與MyBC代碼和Encoder代碼,在運行ServerTwo代碼和ClientTwo代碼前應先運行Key_DH代碼、再運行KeyAgree代碼、最后運行ServerTwo代碼和ClientTwo代碼。
3.實驗截圖:
(1)運行Key_DH代碼的截圖(需要通過命令行):
(2)運行KeyAgree代碼的截圖:
(3)服務器端運行截圖:
(4)客戶端運行截圖:
4.碼云鏈接:
https://gitee.com/zzm-zcc/zhang_zhi_min/commit/bba1a88b5ede8025aeb19f22c4254300c2cee901
五、實驗五 網絡編程與安全-5
1.實驗要求:
完整性校驗結對編程:1人負責客戶端,一人負責服務器;
(1)注意責任歸宿,要會通過測試證明自己沒有問題;
(2)基于Java Socket實現客戶端/服務器功能,傳輸方式用TCP;
(3)客戶端讓用戶輸入中綴表達式,然后把中綴表達式調用MyBC.java的功能轉化為后綴表達式,把后綴表達式用3DES或AES算法加密通過網絡把密文和明文的MD5値發送給服務器;
(4)客戶端和服務器用DH算法進行3DES或AES算法的密鑰交換;
(5)服務器接收到后綴表達式表達式后,進行解密,解密后計算明文的MD5值,和客戶端傳來的MD5進行比較,一致則調用MyDC.java的功能計算后綴表達式的值,把結果發送給客戶端;
(6)客戶端顯示服務器發送過來的結果;
(7)上傳測試結果截圖和碼云鏈接;
2.實驗過程:
(1)DigestPass代碼:
import java.security.*;
public class DigestPass{static String MD5(String str) throws Exception{MessageDigest m=MessageDigest.getInstance("MD5");m.update(str.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;}
}
(2)ServerThree代碼(服務器端):
import java.io.*;
import java.net.*;
public class ServerThree {public static void main(String args[]) throws IOException{String sharekey="";int n=-1;byte [] a=new byte[128];try{ File f=new File("Sharekey.dat");InputStream in = new FileInputStream(f);while((n=in.read(a,0,100))!=-1) {sharekey=sharekey+new String (a,0,n);}in.close();}catch(IOException e) {System.out.println("File read Error"+e);}ServerSocket serverForClient=null;Socket socketOnServer=null;DataOutputStream out=null;DataInputStream in=null;try { serverForClient = new ServerSocket(2010);}catch(IOException e1) {System.out.println(e1);}try{ System.out.println("等待客戶呼叫");socketOnServer = serverForClient.accept(); //堵塞狀態,除非有客戶呼叫out=new DataOutputStream(socketOnServer.getOutputStream());in=new DataInputStream(socketOnServer.getInputStream());String keyone =in.readUTF();//讀取被DH算法加密的密鑰String truekey = Encoder.AESDncode(sharekey,keyone);//使用共享密鑰對被加密的原密鑰解密。String secret =in.readUTF(); // in讀取信息,堵塞狀態System.out.println("服務器收到的信息:"+secret);String mdClient=in.readUTF();System.out.println("客戶端提供的MD5為:"+ mdClient);String clear = Encoder.AESDncode(truekey,secret);//使用原密鑰解密表達式MyDC d=new MyDC();int answer=d.evaluate(clear);if((mdClient.equals(DigestPass.MD5(clear)))==true) {//判斷MD5值是否相等,若相等,則返回答案System.out.println("MD5值匹配");System.out.println("服務器提供的解密:" + clear);System.out.println("服務器解出密文的MD5為:" + DigestPass.MD5(clear));out.writeUTF(answer + "");}Thread.sleep(500);}catch(Exception e) {System.out.println("客戶已斷開"+e);}}
}
(3)ClientThree代碼(客戶端):
import java.io.*;
import java.net.*;
import java.util.Scanner;public class ClientThree {public static void main(String args[]) throws Exception {String key1="";int n1=-1;byte [] a1=new byte[128];try{ File f=new File("key1.dat");InputStream in = new FileInputStream(f);while((n1=in.read(a1,0,100))!=-1) {key1=key1+new String (a1,0,n1);}in.close();}catch(IOException e) {System.out.println("File read Error"+e);}String sharekey="";int n=-1;byte [] a=new byte[128];try{ File f=new File("Sharekey.dat");InputStream in = new FileInputStream(f);while((n=in.read(a,0,100))!=-1) {sharekey=sharekey+new String (a,0,n);}in.close();}catch(IOException e) {System.out.println("File read Error"+e);}Socket mysocket;DataInputStream in=null;DataOutputStream out=null;System.out.println("請輸入算式:");Scanner scanner = new Scanner(System.in);String str = scanner.nextLine();//輸入算式MyBC b=new MyBC();str=b.result(str);String secret=Encoder.AESEncode(key1, str);//客戶端對表達式進行加密String md=DigestPass.MD5(str);//客戶端提供的MD5key1 = Encoder.AESEncode(sharekey,key1);//客戶端對密鑰進行DH加密try{ mysocket=new Socket("127.1.0.0",2010);in=new DataInputStream(mysocket.getInputStream());out=new DataOutputStream(mysocket.getOutputStream());out.writeUTF(key1);out.writeUTF(secret);out.writeUTF(md);String s=in.readUTF(); //in讀取信息,堵塞狀態System.out.println("客戶收到服務器的回答:"+s);Thread.sleep(50000);}catch(Exception e) {System.out.println("服務器已斷開"+e);}}
}
注:任然需要MyDC代碼、MyBC代碼、Encoder代碼、Key_DH代碼和KeyAgree代碼,在運行ServerThree代碼和ClientThree代碼前應先運行Key_DH代碼(與實驗五 網絡編程與安全-4中相同)、再運行KeyAgree代碼、最后運行ServerThree代碼和ClientThree代碼。
3.實驗截圖:
(1)服務器端截圖:
(2)客戶端截圖:
4.碼云鏈接:
https://gitee.com/zzm-zcc/zhang_zhi_min/commit/33995dbe0838b1eebdceff7f6bb1b8a6b86e3922
六、實驗感想:
通過此次實驗,充分了解了各種加密算法的結構與思想,也加深了密碼學的部分知識,拓展了知識面。