兩人一組結對編程:html
參考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSAjava
結對實現中綴表達式轉後綴表達式的功能 MyBC.javanode
結對實現從上面功能中獲取的表達式中實現後綴表達式求值的功能,調用MyDC.javagit
上傳測試代碼運行結果截圖和碼雲連接算法
棧的一個應用是用來對四則運算表達式進行求值。express
表達式Exp = S1 + OP + S2(S1 ,S2是兩個操做數,OP爲運算符)有三種標識方法:編程
OP + S1 + S2 爲前綴表示法數組
S1 + OP + S2 爲中綴表示法安全
S1 + S2 + OP 爲後綴表示法服務器
例如:Exp = a * b + (c - d / e) * f
前綴式: + * a b * - c / d e f
中綴式: a * b + c - d / e * f
後綴式: a b * c d e / - f * +
咱們能夠看出:
1.操做數之間的相對次序不變;
2.運算符的相對次序不一樣;
3.中綴式丟失了括弧信息,導致運算次序不肯定;
4.前綴式的運算規則爲:連續出現的兩個操做數和在它們以前且緊靠它們的運算符構成一個最小表達式;
5.後綴式的運算規則爲:運算符在式中出現的順序恰爲表達式的運算順序;每一個運算符和在它以前出現且緊靠它的兩個操做數構成一個最小表達式。
項目編譯和運行
MyDC.java
/** * @Author 16487 */ 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; // MyDC my= new MyDC(); 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(); //System.out.println(token); //若是是運算符,調用isOperator if (isOperator(token)) { char []c=token.toCharArray(); op1=stack.pop(); //從棧中彈出操做數2 op2=stack.pop(); //從棧中彈出操做數1 result=evalSingleOp(c[0],op1,op2); //根據運算符和兩個操做數調用evalSingleOp計算result; stack.push(result); //計算result入棧; } else{ //若是是操做數 if(token.matches("[0-9]+")) { int number=Integer.parseInt(token); stack.push(number); } } } 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.java
/** * @Author 16487 */ 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 ("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"); } } }
Caculate.java
/** * @Author 16487 */ 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); } }
MyBC.java
/** * @Author 16487 */ 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; } }
結對編程:1人負責客戶端,一人負責服務器
注意責任歸宿,要會經過測試證實本身沒有問題
基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式經過網絡發送給服務器
服務器接收到後綴表達式,調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
客戶端顯示服務器發送過來的結果
上傳測試結果截圖和碼雲連接
Java爲TCP協議提供了兩個類,分別在客戶端編程和服務器端編程中使用它們。在應用程序開始通訊以前,須要先建立一個鏈接,由客戶端程序發起;而服務器端的程序須要一直監聽着主機的特定端口號,等待客戶端的鏈接。在客戶端中咱們只須要使用Socket實例,而服務端要同時處理ServerSocket實例和Socket實例;兩者而且都使用OutputStream和InpuStream來發送和接收數據。
項目編譯和運行
Client.java
/** * @Author 16487 */ 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); } } }
Server.java
/** * @Author 16487 */ 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); } } }
加密結對編程:1人負責客戶端,一人負責服務器
注意責任歸宿,要會經過測試證實本身沒有問題
基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密後經過網絡把密文發送給服務器
服務器接收到後綴表達式表達式後,進行解密(和客戶端協商密鑰,能夠用數組保存),而後調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
客戶端顯示服務器發送過來的結果
上傳測試結果截圖和碼雲連接
項目編譯和運行
Client1.java
/** * @Author 16487 */ import java.io.*; import java.net.*; import java.lang.*; import java.util.Scanner; public class Client1 { 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= Encorder.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); } } }
Server1.java
/** * @Author 16487 */ import java.io.*; import java.net.*; public class Server1 { 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= Encorder.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); } } }
Encorder.java
/** * @Author 16487 */ 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 Encorder { /* * 加密 * 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)操做,第二個參數爲使用的KEY cipher.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(); } //若是有錯就返加nulll return 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)操做,第二個參數爲使用的KEY cipher.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(); } //若是有錯就返加nulll return null; } }
Skey_AES.java
/** * @Author 16487 */ 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); } }
密鑰分發結對編程:1人負責客戶端,一人負責服務器
注意責任歸宿,要會經過測試證實本身沒有問題
基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密經過網絡把密文發送給服務器
客戶端和服務器用DH算法進行3DES或AES算法的密鑰交換
服務器接收到後綴表達式表達式後,進行解密,而後調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
客戶端顯示服務器發送過來的結果
上傳測試結果截圖和碼雲連接
以甲乙雙方發送數據爲模型進行分析
一、甲方(消息發送方,下同)構建密鑰對(公鑰+私鑰),甲方公佈公鑰給乙方(消息接收方,下同)
二、乙方以甲方發送過來的公鑰做爲參數構造密鑰對(公鑰+私鑰),將構造出來的公鑰公佈給甲方
三、甲方用「甲方的私鑰+乙方的公鑰」構造本地密鑰
四、乙方用「乙方的私鑰+甲方的公鑰」構造本地的密鑰
五、這個時候,甲乙兩方本地新構造出來的密鑰應該同樣,甲乙雙方能夠經過本地密鑰進行數據的加密和解密
六、而後就可使用AES這類對稱加密算法進行數據的安全傳送了。
項目編譯和運行
Client2.java
/** * @Author 16487 */ import javax.crypto.spec.*; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; import java.util.Scanner; 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("127.1.0.0", 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(); System.out.println("請輸入中綴表達式:"); String infix = inn.nextLine(); MyBC1 myBC1 = new MyBC1(); String suffix = myBC1.infixToSuffix(infix); System.out.println(suffix); //中綴表達式加密 Cipher cp = Cipher.getInstance("DESede"); cp.init(Cipher.ENCRYPT_MODE, k); byte ptext[] = suffix.getBytes("UTF8"); byte ctext[] = cp.doFinal(ptext); out.writeUTF(ctext.length + ""); for (int i = 0; i < ctext.length; i++) { out.writeUTF(ctext[i] + ""); } //對密鑰進行加密 KeyAgree keyAgree = new KeyAgree(); SecretKeySpec k1 = keyAgree.KeyAgree("Serverpub.dat","Clientpri.dat"); cp.init(Cipher.ENCRYPT_MODE, k1); byte ckey[] = cp.doFinal(kb); out.writeUTF(ckey.length + ""); for (int i = 0; i < ckey.length; i++) { out.writeUTF(ckey[i] + ""); } String result = in.readUTF(); System.out.println("收到客戶回答" + result); Thread.sleep(500); } catch (Exception e) { System.out.println("服務器已斷開" + e); } } }
Server2.java
/** * @Author 16487 */ import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.net.*; public class Server2 { 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 e1){ System.out.println("等待客戶呼叫"+e1); } try{ System.out.println("服務器收到的信息"); socketOnServer = serverForClient.accept(); out = new DataOutputStream(socketOnServer.getOutputStream()); in = new DataInputStream(socketOnServer.getInputStream()); //獲取密文 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); } //獲取密鑰 String keylength = in.readUTF(); byte []ckey = new byte[Integer.parseInt(keylength)]; for(int i=0; i<Integer.parseInt(keylength); i++){ String temp = in.readUTF(); ckey[i] = Byte.parseByte(temp); } //密鑰解密 SecretKeySpec k1 = KeyAgree.KeyAgree("Clientpub.dat","Serverpri.dat"); Cipher cp=Cipher.getInstance("DESede"); cp.init(Cipher.DECRYPT_MODE, k1); byte []pkey=cp.doFinal(ckey); //密文解密 SecretKeySpec k=new SecretKeySpec(pkey,"DESede"); cp.init(Cipher.DECRYPT_MODE, k); byte []ptext=cp.doFinal(ctext); String suffix = new String(ptext,"UTF8"); System.out.println("服務器提供的解密"+suffix); out.writeUTF(myDC.evaluate(suffix)+""); Thread.sleep(500); }catch (Exception e){ System.out.println("客戶已斷開"); } } }
MyBC1.java
/** * @Author 16487 */ import java.util.Stack; public class MyBC1 { public MyBC1(){} public static String infixToSuffix(String exp){ Stack<String> s = new Stack<String>(); // 建立操做符堆棧 String suffix = ""; // 要輸出的後綴表達式字符串 String suffix1 = ""; //上一次的後綴表達式 String suffix2 = ""; String str[] = exp.split(" "); int length = str.length; // 輸入的中綴表達式的長度 String temp=""; for (int i = 0; i < length; i++) { // 對該中綴表達式的每個字符並進行判斷 switch (str[i]) { case " ":break; // 忽略空格 case "(": s.push(str[i]); // 若是是左括號直接壓入堆棧 break; case "+": case "-": if(s.size() != 0){ // 碰到'+' '-',將棧中的全部運算符所有彈出去,直至碰到左括號爲止,輸出到隊列中去 temp = s.pop(); if (temp.equals("(")) { // 將左括號放回堆棧,終止循環 s.push(temp); s.push(str[i]); break; } else{ s.push(str[i]); suffix2 = suffix2 + temp + " "; break; } } else{ s.push(str[i]); // 說明是當前爲第一次進入或者其餘前面運算都有括號等狀況致使棧已經爲空,此時須要將符號進棧 break; } // 若是是乘號或者除號,則彈出全部序列,直到碰到加好、減號、左括號爲止,最後將該操做符壓入堆棧 case "*": case "÷": if(s.size()!=0){ temp = s.pop(); if(temp.equals("+")||temp.equals("-")||temp.equals("(")){ s.push(temp); s.push(str[i]); break; } else{ s.push(str[i]); suffix2 = suffix2+temp+" "; break; } } else { s.push(str[i]); //當前爲第一次進入或者其餘前面運算都有括號等狀況致使棧已經爲空,此時須要將符號進棧 break; } // 若是碰到的是右括號,則距離棧頂的第一個左括號上面的全部運算符彈出棧並拋棄左括號 case ")": while (!s.isEmpty()) { temp = s.pop(); if (temp.equals("(")) { break; } else { suffix2 = suffix2+temp+" "; } } break; // 默認狀況,若是讀取到的是數字,則直接送至輸出序列 default: suffix2 = suffix2+str[i]+" "; break; } } // 若是堆棧不爲空,則把剩餘運算符一次彈出,送至輸出序列 while (s.size() != 0) { suffix2 = suffix2+s.pop()+" "; } if(suffix1.equals("")){ //第一個題目 suffix1 = suffix2; suffix = suffix2; } else{ if(suffix2.equals(suffix1)) suffix = ""; else suffix = suffix2; } suffix1 = suffix2; return suffix; } }
KeyAgree.java
/** * @Author 16487 */ import java.io.*; import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; public class KeyAgree{ public KeyAgree(){} public static SecretKeySpec KeyAgree(String a,String b) throws Exception{ // 讀取對方的DH公鑰 FileInputStream f1=new FileInputStream(a); ObjectInputStream b1=new ObjectInputStream(f1); PublicKey pbk=(PublicKey)b1.readObject( ); //讀取本身的DH私鑰 FileInputStream f2=new FileInputStream(b); ObjectInputStream b2=new ObjectInputStream(f2); PrivateKey prk=(PrivateKey)b2.readObject( ); // 執行密鑰協定 KeyAgreement ka=KeyAgreement.getInstance("DH"); ka.init(prk); ka.doPhase(pbk,true); //生成共享信息 byte[ ] s=ka.generateSecret(); byte []sb = new byte[24]; System.arraycopy(s, 0, sb, 0, 24); System.out.println("共享祕鑰:"); for(int i=0;i<sb.length;i++){ System.out.print(sb[i]+" "); } System.out.println(); SecretKeySpec k=new SecretKeySpec(sb,"DESede"); return k; } }
Key_DH.java
/** * @Author 16487 */ import java.io.*; import java.math.*; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; public class Key_DH{ //三個靜態變量的定義從 // C:\j2sdk-1_4_0-doc\docs\guide\security\jce\JCERefGuide.html // 拷貝而來 // The 1024 bit Diffie-Hellman modulus values used by SKIP private static final byte skip1024ModulusBytes[] = { (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58, (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD, (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4, (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B, (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D, (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C, (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C, (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6, (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0, (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B, (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB, (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D, (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD, (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43, (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C, (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C, (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C, (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40, (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C, (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72, (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03, (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29, (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C, (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB, (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B, (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08, (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D, (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C, (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22, (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB, (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55, (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7 }; // The SKIP 1024 bit modulus private static final BigInteger skip1024Modulus = new BigInteger(1, skip1024ModulusBytes); // The base used with the SKIP 1024 bit modulus private static final BigInteger skip1024Base = BigInteger.valueOf(2); public static void main(String args[ ]) throws Exception{ DHParameterSpec DHP= new DHParameterSpec(skip1024Modulus,skip1024Base); KeyPairGenerator kpg= KeyPairGenerator.getInstance("DH"); kpg.initialize(DHP); KeyPair kp=kpg.genKeyPair(); PublicKey pbk=kp.getPublic(); PrivateKey prk=kp.getPrivate(); // 保存公鑰 FileOutputStream f1=new FileOutputStream("Serverpub.dat"); ObjectOutputStream b1=new ObjectOutputStream(f1); b1.writeObject(pbk); FileOutputStream f2=new FileOutputStream("Clientpub.dat"); ObjectOutputStream b2=new ObjectOutputStream(f2); b2.writeObject(pbk); // 保存私鑰 FileOutputStream f3=new FileOutputStream("Clientpri.dat"); ObjectOutputStream b3=new ObjectOutputStream(f3); b3.writeObject(prk); FileOutputStream f4=new FileOutputStream("Serverpri.dat"); ObjectOutputStream b4=new ObjectOutputStream(f4); b4.writeObject(prk); } }
完整性校驗結對編程:1人負責客戶端,一人負責服務器
注意責任歸宿,要會經過測試證實本身沒有問題
基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBC.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密經過網絡把密文和明文的MD5値發送給服務器
客戶端和服務器用DH算法進行3DES或AES算法的密鑰交換
服務器接收到後綴表達式表達式後,進行解密,解密後計算明文的MD5值,和客戶端傳來的MD5進行比較,一致則調用MyDC.java的功能計算後綴表達式的值,把結果發送給客戶端
客戶端顯示服務器發送過來的結果
上傳測試結果截圖和碼雲連接
項目編譯和運行
Client3.java
/** * @Author 16487 */ import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; import java.security.MessageDigest; import java.util.Scanner; 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("127.1.0.0", 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(); System.out.println("請輸入中綴表達式:"); String infix = inn.nextLine(); MyBC1 myBC1 = new MyBC1(); String suffix = myBC1.infixToSuffix(infix); System.out.println(suffix); //計算明文的MD5值 MessageDigest m = MessageDigest.getInstance("MD5"); m.update(suffix.getBytes("UTF8")); byte s[] = m.digest(); String r=""; for (int i=0; i<s.length; i++){ r+=Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); } System.out.println("明文的MD5"); System.out.println(r); out.writeUTF(s.length+""); for(int i=0; i<s.length; i++){ out.writeUTF(s[i]+""); } //中綴表達式加密 Cipher cp = Cipher.getInstance("DESede"); cp.init(Cipher.ENCRYPT_MODE, k); byte ptext[] = suffix.getBytes("UTF8"); byte ctext[] = cp.doFinal(ptext); out.writeUTF(ctext.length + ""); for (int i = 0; i < ctext.length; i++) { out.writeUTF(ctext[i] + ""); } //對密鑰進行加密 KeyAgree keyAgree = new KeyAgree(); SecretKeySpec k1 = keyAgree.KeyAgree("Serverpub.dat","Clientpri.dat"); cp.init(Cipher.ENCRYPT_MODE, k1); byte ckey[] = cp.doFinal(kb); out.writeUTF(ckey.length + ""); for (int i = 0; i < ckey.length; i++) { out.writeUTF(ckey[i] + ""); } String result = in.readUTF(); System.out.println("收到客戶回答" + result); Thread.sleep(500); } catch (Exception e) { System.out.println("服務器已斷開" + e); } } }
Server3.java
/** * @Author 16487 */ import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.security.MessageDigest; public class Server3 { 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 e1){ System.out.println("客戶有需求了"+e1); } try{ System.out.println("等待客戶呼叫"); socketOnServer = serverForClient.accept(); out = new DataOutputStream(socketOnServer.getOutputStream()); in = new DataInputStream(socketOnServer.getInputStream()); //獲取明文MD5 String MD5length = in.readUTF(); byte []MD5 = new byte[Integer.parseInt(MD5length)]; for(int i=0; i<Integer.parseInt(MD5length); i++){ String temp1 = in.readUTF(); MD5[i] = Byte.parseByte(temp1); } //獲取密文 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); } //獲取密鑰 String keylength = in.readUTF(); byte []ckey = new byte[Integer.parseInt(keylength)]; for(int i=0; i<Integer.parseInt(keylength); i++){ String temp = in.readUTF(); ckey[i] = Byte.parseByte(temp); } //密鑰解密 SecretKeySpec k1 = KeyAgree.KeyAgree("Clientpub.dat","Serverpri.dat"); Cipher cp=Cipher.getInstance("DESede"); cp.init(Cipher.DECRYPT_MODE, k1); byte []pkey=cp.doFinal(ckey); //密文解密 SecretKeySpec k=new SecretKeySpec(pkey,"DESede"); cp.init(Cipher.DECRYPT_MODE, k); byte []ptext=cp.doFinal(ctext); String suffix = new String(ptext,"UTF8"); //解密後的MD5 MessageDigest m = MessageDigest.getInstance("MD5"); m.update(suffix.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("解密後的MD5"); System.out.println(result); System.out.println("客服收到客戶需求"+suffix); out.writeUTF(myDC.evaluate(suffix)+""); Thread.sleep(500); }catch (Exception e){ System.out.println("服務器斷開鏈接"); } } }
步驟 | 耗時 | 百分比 |
---|---|---|
需求分析 | 100min | 24.4% |
設計 | 150min | 36.6% |
代碼實現 | 100min | 24.4% |
測試 | 20min | 4.9% |
分析總結 | 40min | 9.7% |